blob: 9c1c7f7ae344a1ef784e2278e85ba0fd8fadad73 [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 Dupin00f16422020-03-11 11:33:04 -0700367 mSupportsBlur = supportsBlurs;
368 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800369 property_get("ro.sf.blurs_are_expensive", value, "0");
370 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800371
Ady Abraham0a525092020-03-03 12:51:24 -0800372 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700373 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
374 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
375
Dan Stozaec460082018-12-17 15:35:09 -0800376 property_get("debug.sf.luma_sampling", value, "1");
377 mLumaSampling = atoi(value);
378
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800379 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800380 mDisableClientCompositionCache = atoi(value);
381
Romain Guy11d63f42017-07-20 12:47:14 -0700382 // We should be reading 'persist.sys.sf.color_saturation' here
383 // but since /data may be encrypted, we need to wait until after vold
384 // comes online to attempt to read the property. The property is
385 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800386
387 if (useTrebleTestingOverride()) {
388 // Without the override SurfaceFlinger cannot connect to HIDL
389 // services that are not listed in the manifests. Considered
390 // deriving the setting from the set service name, but it
391 // would be brittle if the name that's not 'default' is used
392 // for production purposes later on.
393 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
394 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800395
396 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800397}
398
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800399void SurfaceFlinger::onFirstRef()
400{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800401 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800402}
403
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700404SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405
Dan Stozac7014012014-02-14 15:03:43 -0800406void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800407{
408 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700409 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410
Andy McFadden13a082e2012-08-24 10:16:42 -0700411 // restore initial conditions (default device unblank, etc)
412 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413
414 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700415 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416}
417
Robert Carr1db73f62016-12-21 12:58:51 -0800418static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700419 status_t err = client->initCheck();
420 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800421 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422 }
Robert Carr1db73f62016-12-21 12:58:51 -0800423 return nullptr;
424}
425
426sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
427 return initClient(new Client(this));
428}
429
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700430sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
431 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700432{
433 class DisplayToken : public BBinder {
434 sp<SurfaceFlinger> flinger;
435 virtual ~DisplayToken() {
436 // no more references, this display must be terminated
437 Mutex::Autolock _l(flinger->mStateLock);
438 flinger->mCurrentState.displays.removeItem(this);
439 flinger->setTransactionFlags(eDisplayTransactionNeeded);
440 }
441 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700442 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700443 : flinger(flinger) {
444 }
445 };
446
447 sp<BBinder> token = new DisplayToken(this);
448
449 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700450 // Display ID is assigned when virtual display is allocated by HWC.
451 DisplayDeviceState state;
452 state.isSecure = secure;
453 state.displayName = displayName;
454 mCurrentState.displays.add(token, state);
455 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700456 return token;
457}
458
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700459void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700460 Mutex::Autolock _l(mStateLock);
461
Dominik Laskowski075d3172018-05-24 15:50:06 -0700462 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
463 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700464 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700465 return;
466 }
467
Dominik Laskowski075d3172018-05-24 15:50:06 -0700468 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
469 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700470 ALOGE("destroyDisplay called for non-virtual display");
471 return;
472 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700473 mInterceptor->saveDisplayDeletion(state.sequenceId);
474 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700475 setTransactionFlags(eDisplayTransactionNeeded);
476}
477
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800478std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
479 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800481 const auto internalDisplayId = getInternalDisplayIdLocked();
482 if (!internalDisplayId) {
483 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700484 }
485
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800486 std::vector<PhysicalDisplayId> displayIds;
487 displayIds.reserve(mPhysicalDisplayTokens.size());
488 displayIds.push_back(internalDisplayId->value);
489
490 for (const auto& [id, token] : mPhysicalDisplayTokens) {
491 if (id != *internalDisplayId) {
492 displayIds.push_back(id.value);
493 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700494 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700495
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800496 return displayIds;
497}
498
499sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
500 Mutex::Autolock lock(mStateLock);
501 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700502}
503
Ady Abraham37965d42018-11-01 13:43:32 -0700504status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
505 if (!outGetColorManagement) {
506 return BAD_VALUE;
507 }
508 *outGetColorManagement = useColorManagement;
509 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700510}
511
Lloyd Pique441d5042018-10-18 16:49:51 -0700512HWComposer& SurfaceFlinger::getHwComposer() const {
513 return mCompositionEngine->getHwComposer();
514}
515
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700516renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
517 return mCompositionEngine->getRenderEngine();
518}
519
Lloyd Pique70d91362018-10-18 16:02:55 -0700520compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
521 return *mCompositionEngine.get();
522}
523
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800524void SurfaceFlinger::bootFinished()
525{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700526 if (mBootFinished == true) {
527 ALOGE("Extra call to bootFinished");
528 return;
529 }
530 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700531 if (mStartPropertySetThread->join() != NO_ERROR) {
532 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800533 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534 const nsecs_t now = systemTime();
535 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000536 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700537
Mikael Pessa90092f42019-08-26 17:22:04 -0700538 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000539 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700540
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541 // wait patiently for the window manager death
542 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700543 mWindowManager = defaultServiceManager()->getService(name);
544 if (mWindowManager != 0) {
545 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546 }
Robert Carr720e5062018-07-30 17:45:14 -0700547 sp<IBinder> input(defaultServiceManager()->getService(
548 String16("inputflinger")));
549 if (input == nullptr) {
550 ALOGE("Failed to link to input service");
551 } else {
552 mInputFlinger = interface_cast<IInputFlinger>(input);
553 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554
Steven Thomas050b2c82017-03-06 11:45:16 -0800555 if (mVrFlinger) {
556 mVrFlinger->OnBootFinished();
557 }
558
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700560 // formerly we would just kill the process, but we now ask it to exit so it
561 // can choose where to stop the animation.
562 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700563
564 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
565 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
566 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700567
Ana Krulecbd6654b2019-02-15 15:18:15 -0800568 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800569 readPersistentProperties();
570 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800571
Ady Abraham8a82ba62020-01-17 12:43:17 -0800572 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
573 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
574 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
575 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800576 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800577}
578
Dan Stoza436ccf32018-06-21 12:10:12 -0700579uint32_t SurfaceFlinger::getNewTexture() {
580 {
581 std::lock_guard lock(mTexturePoolMutex);
582 if (!mTexturePool.empty()) {
583 uint32_t name = mTexturePool.back();
584 mTexturePool.pop_back();
585 ATRACE_INT("TexturePoolSize", mTexturePool.size());
586 return name;
587 }
588
589 // The pool was too small, so increase it for the future
590 ++mTexturePoolSize;
591 }
592
593 // The pool was empty, so we need to get a new texture name directly using a
594 // blocking call to the main thread
595 uint32_t name = 0;
596 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
597 return name;
598}
599
Mathias Agopian3f844832013-08-07 21:24:32 -0700600void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700601 std::lock_guard lock(mTexturePoolMutex);
602 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
603 // to actually delete this or not based on mTexturePoolSize
604 mTexturePool.push_back(texture);
605 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700606}
607
Wei Wangf9b05ee2017-07-19 20:59:39 -0700608// Do not call property_set on main thread which will be blocked by init
609// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700610void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700611 ALOGI( "SurfaceFlinger's main thread ready to run. "
612 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700613 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800614
Steven Thomasb02664d2017-07-26 18:48:28 -0700615 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700616 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800617 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700618 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
619 renderengine::RenderEngineCreationArgs::Builder()
620 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
621 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
622 .setUseColorManagerment(useColorManagement)
623 .setEnableProtectedContext(enable_protected_contents(false))
624 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700625 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700626 .setContextPriority(useContextPriority
627 ? renderengine::RenderEngine::ContextPriority::HIGH
628 : renderengine::RenderEngine::ContextPriority::MEDIUM)
629 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800630 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700631
632 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
633 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700634 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800635 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800636 // Process any initial hotplug and resulting display changes.
637 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700638 const auto display = getDefaultDisplayDeviceLocked();
639 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700640 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700641 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800642
Steven Thomas050b2c82017-03-06 11:45:16 -0800643 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700644 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700645 // This callback is called from the vr flinger dispatch thread. We
646 // need to call signalTransaction(), which requires holding
647 // mStateLock when we're not on the main thread. Acquiring
648 // mStateLock from the vr flinger dispatch thread might trigger a
649 // deadlock in surface flinger (see b/66916578), so post a message
650 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700651 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700652 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
653 mVrFlingerRequestsDisplay = requestDisplay;
654 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700655 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800656 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700657 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
658 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700659 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700660 .value_or(0),
661 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800662 if (!mVrFlinger) {
663 ALOGE("Failed to start vrflinger");
664 }
665 }
666
Mathias Agopian92a979a2012-08-02 18:32:23 -0700667 // initialize our drawing state
668 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700669
Andy McFadden13a082e2012-08-24 10:16:42 -0700670 // set initial conditions (e.g. unblank default device)
671 initializeDisplays();
672
Steven Thomas137d4bc2019-07-25 16:55:14 -0700673 char primeShaderCache[PROPERTY_VALUE_MAX];
674 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
675 if (atoi(primeShaderCache)) {
676 getRenderEngine().primeCache();
677 }
Dan Stoza4e637772016-07-28 13:31:51 -0700678
Wei Wangf9b05ee2017-07-19 20:59:39 -0700679 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700680
681 const bool presentFenceReliable =
682 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
683 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700684
685 if (mStartPropertySetThread->Start() != NO_ERROR) {
686 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800687 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800688
Dan Stoza9e56aa02015-11-02 13:00:03 -0800689 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700690}
691
Romain Guy11d63f42017-07-20 12:47:14 -0700692void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700693 Mutex::Autolock _l(mStateLock);
694
Romain Guy11d63f42017-07-20 12:47:14 -0700695 char value[PROPERTY_VALUE_MAX];
696
697 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800698 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700699 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800700 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100701
702 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700703 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800704
705 property_get("persist.sys.sf.color_mode", value, "0");
706 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700707
708 property_get("persist.sys.sf.disable_blurs", value, "0");
709 bool disableBlurs = atoi(value);
710 mDisableBlurs = disableBlurs;
711 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700712}
713
Mathias Agopiana67e4182012-06-19 17:26:12 -0700714void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800715 // Start boot animation service by setting a property mailbox
716 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700717 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800718 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700719 if (mStartPropertySetThread->join() != NO_ERROR) {
720 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800721 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700722}
723
Mathias Agopian875d8e12013-06-07 15:35:48 -0700724size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700725 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700726}
727
Mathias Agopian875d8e12013-06-07 15:35:48 -0700728size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700729 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700730}
731
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800732// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800733
Jamie Gennis582270d2011-08-17 18:19:00 -0700734bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800735 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800736 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800737 return authenticateSurfaceTextureLocked(bufferProducer);
738}
739
740bool SurfaceFlinger::authenticateSurfaceTextureLocked(
741 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800742 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800743 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800744}
745
Brian Anderson6b376712017-04-04 10:51:39 -0700746status_t SurfaceFlinger::getSupportedFrameTimestamps(
747 std::vector<FrameEvent>* outSupported) const {
748 *outSupported = {
749 FrameEvent::REQUESTED_PRESENT,
750 FrameEvent::ACQUIRE,
751 FrameEvent::LATCH,
752 FrameEvent::FIRST_REFRESH_START,
753 FrameEvent::LAST_REFRESH_START,
754 FrameEvent::GPU_COMPOSITION_DONE,
755 FrameEvent::DEQUEUE_READY,
756 FrameEvent::RELEASE,
757 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700758 ConditionalLock _l(mStateLock,
759 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700760 if (!getHwComposer().hasCapability(
761 HWC2::Capability::PresentFenceIsNotReliable)) {
762 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
763 }
764 return NO_ERROR;
765}
766
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800767status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
768 if (!displayToken || !state) {
769 return BAD_VALUE;
770 }
771
772 Mutex::Autolock lock(mStateLock);
773
774 const auto display = getDisplayDeviceLocked(displayToken);
775 if (!display) {
776 return NAME_NOT_FOUND;
777 }
778
779 state->layerStack = display->getLayerStack();
780 state->orientation = display->getOrientation();
781
782 const Rect viewport = display->getViewport();
783 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
784
785 return NO_ERROR;
786}
787
788status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
789 if (!displayToken || !info) {
790 return BAD_VALUE;
791 }
792
793 Mutex::Autolock lock(mStateLock);
794
795 const auto display = getDisplayDeviceLocked(displayToken);
796 if (!display) {
797 return NAME_NOT_FOUND;
798 }
799
Dominik Laskowski55c85402020-01-21 16:25:47 -0800800 if (const auto connectionType = display->getConnectionType())
801 info->connectionType = *connectionType;
802 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800803 return INVALID_OPERATION;
804 }
805
806 if (mEmulatedDisplayDensity) {
807 info->density = mEmulatedDisplayDensity;
808 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800809 info->density = info->connectionType == DisplayConnectionType::Internal
810 ? mInternalDisplayDensity
811 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800812 }
813
814 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200815 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800816
817 return NO_ERROR;
818}
819
Dominik Laskowski22488f62019-03-28 09:53:04 -0700820status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800821 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700822 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700823 return BAD_VALUE;
824 }
825
Dominik Laskowski22488f62019-03-28 09:53:04 -0700826 Mutex::Autolock lock(mStateLock);
827
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800828 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700829 if (!displayId) {
830 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700831 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700832
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800833 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700834
Dan Stoza7f7da322014-05-02 15:26:25 -0700835 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700836
Dominik Laskowski075d3172018-05-24 15:50:06 -0700837 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800838 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700839
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800840 auto width = hwConfig->getWidth();
841 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700842
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800843 auto xDpi = hwConfig->getDpiX();
844 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700845
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800846 if (isInternal &&
847 (internalDisplayOrientation == ui::ROTATION_90 ||
848 internalDisplayOrientation == ui::ROTATION_270)) {
849 std::swap(width, height);
850 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700851 }
852
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800853 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800854
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800855 if (mEmulatedDisplayDensity) {
856 config.xDpi = mEmulatedDisplayDensity;
857 config.yDpi = mEmulatedDisplayDensity;
858 } else {
859 config.xDpi = xDpi;
860 config.yDpi = yDpi;
861 }
862
863 const nsecs_t period = hwConfig->getVsyncPeriod();
864 config.refreshRate = 1e9f / period;
865
866 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
867 config.appVsyncOffset = offsets.late.app;
868 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800869 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800870
Andy McFadden91b2ca82014-06-13 14:04:23 -0700871 // This is how far in advance a buffer must be queued for
872 // presentation at a given time. If you want a buffer to appear
873 // on the screen at time N, you must submit the buffer before
874 // (N - presentationDeadline).
875 //
876 // Normally it's one full refresh period (to give SF a chance to
877 // latch the buffer), but this can be reduced by configuring a
878 // DispSync offset. Any additional delays introduced by the hardware
879 // composer or panel must be accounted for here.
880 //
881 // We add an additional 1ms to allow for processing time and
882 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800883 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700884
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800885 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700886 }
887
Dan Stoza7f7da322014-05-02 15:26:25 -0700888 return NO_ERROR;
889}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700890
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700891status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
892 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700893 return BAD_VALUE;
894 }
895
Ana Krulecc2870422019-01-29 19:00:58 -0800896 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700897 return NO_ERROR;
898}
899
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700900int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
901 const auto display = getDisplayDevice(displayToken);
902 if (!display) {
903 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800904 return BAD_VALUE;
905 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700906
Steven Thomasc9098452019-09-30 17:15:05 -0700907 if (display->isPrimary()) {
908 std::lock_guard<std::mutex> lock(mActiveConfigLock);
909 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800910 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700911 }
Steven Thomasc9098452019-09-30 17:15:05 -0700912 }
Ady Abraham2139f732019-11-13 18:56:40 -0800913
914 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700915}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700916
Ady Abraham03b02dd2019-03-21 15:40:11 -0700917void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800918 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800919 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abraham2139f732019-11-13 18:56:40 -0800920 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800921
Ady Abrahamb838aed2019-02-12 15:30:16 -0800922 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800923 if (mDesiredActiveConfigChanged) {
924 // If a config change is pending, just cache the latest request in
925 // mDesiredActiveConfig
926 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
927 mDesiredActiveConfig = info;
928 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
929 } else {
930 // Check is we are already at the desired config
931 const auto display = getDefaultDisplayDeviceLocked();
932 if (!display || display->getActiveConfig() == refreshRate.configId) {
933 return;
934 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800935
Ady Abraham59db0a32020-03-02 18:04:20 -0800936 // Initiate a config change.
937 mDesiredActiveConfigChanged = true;
938 mDesiredActiveConfig = info;
939
Ady Abrahamb838aed2019-02-12 15:30:16 -0800940 // This will trigger HWC refresh without resetting the idle timer.
941 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700942 // Start receiving vsync samples now, so that we can detect a period
943 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800944 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700945 // As we called to set period, we will call to onRefreshRateChangeCompleted once
946 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700947 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800948
Ady Abraham9e16a482019-12-03 17:19:41 -0800949 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
950 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800951 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700952
953 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800954 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700955 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800956}
957
958status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
959 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800960
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100961 if (!displayToken) {
962 return BAD_VALUE;
963 }
Ady Abraham838de062019-02-04 10:24:03 -0800964
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100965 status_t result = NO_ERROR;
966
967 postMessageSync(new LambdaMessage([&]() {
968 const auto display = getDisplayDeviceLocked(displayToken);
969 if (!display) {
970 ALOGE("Attempt to set allowed display configs for invalid display token %p",
971 displayToken.get());
972 result = BAD_VALUE;
973 } else if (display->isVirtual()) {
974 ALOGW("Attempt to set allowed display configs for virtual display");
975 result = BAD_VALUE;
976 } else {
977 HwcConfigIndexType config(mode);
978 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
979 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
980 refreshRate.fps);
981 }
982 }));
983
984 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800985}
986
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800987void SurfaceFlinger::setActiveConfigInternal() {
988 ATRACE_CALL();
989
Dominik Laskowski22488f62019-03-28 09:53:04 -0700990 const auto display = getDefaultDisplayDeviceLocked();
991 if (!display) {
992 return;
993 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800994
Dominik Laskowski22488f62019-03-28 09:53:04 -0700995 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800996 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700997 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800998 display->setActiveConfig(mUpcomingActiveConfig.configId);
999
Ady Abraham2e1dd892020-03-05 13:48:36 -08001000 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001001 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -08001002 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1003 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -08001004 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001005
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001006 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001007 const nsecs_t vsyncPeriod =
1008 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
1009 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -08001010 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001011 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001012 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001013}
1014
Ady Abraham53852a52019-05-28 18:07:44 -07001015void SurfaceFlinger::desiredActiveConfigChangeDone() {
1016 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1017 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1018 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001019
Ady Abraham2e1dd892020-03-05 13:48:36 -08001020 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001021 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001022 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001023 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1024 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001025}
1026
Dominik Laskowski22488f62019-03-28 09:53:04 -07001027bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001028 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001029 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001030 if (mCheckPendingFence) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001031 if (previousFramePending()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001032 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001033 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001034 return true;
1035 }
1036
1037 // We received the present fence from the HWC, so we assume it successfully updated
1038 // the config, hence we update SF.
1039 mCheckPendingFence = false;
1040 setActiveConfigInternal();
1041 }
1042
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001043 // Store the local variable to release the lock.
1044 ActiveConfigInfo desiredActiveConfig;
1045 {
1046 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001047 if (!mDesiredActiveConfigChanged) {
1048 return false;
1049 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001050 desiredActiveConfig = mDesiredActiveConfig;
1051 }
1052
Ady Abraham2e1dd892020-03-05 13:48:36 -08001053 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001054 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1055 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1056 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001057 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001058 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1059 // display is not valid or we are already in the requested mode
1060 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001061 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001062 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001063 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001064
Ady Abraham838de062019-02-04 10:24:03 -08001065 // Desired active config was set, it is different than the config currently in use, however
1066 // allowed configs might have change by the time we process the refresh.
1067 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001068 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001069 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001070 return false;
1071 }
Alec Mouri7f015182019-07-11 13:56:22 -07001072
Ady Abrahamb838aed2019-02-12 15:30:16 -08001073 mUpcomingActiveConfig = desiredActiveConfig;
1074 const auto displayId = display->getId();
1075 LOG_ALWAYS_FATAL_IF(!displayId);
1076
Ady Abraham2139f732019-11-13 18:56:40 -08001077 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001078
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001079 // TODO(b/142753666) use constrains
1080 HWC2::VsyncPeriodChangeConstraints constraints;
1081 constraints.desiredTimeNanos = systemTime();
1082 constraints.seamlessRequired = false;
1083
1084 HWC2::VsyncPeriodChangeTimeline outTimeline;
1085 auto status =
1086 getHwComposer().setActiveConfigWithConstraints(*displayId,
1087 mUpcomingActiveConfig.configId.value(),
1088 constraints, &outTimeline);
1089 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001090 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1091 // to be sent. We just log the error in this case.
1092 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001093 return false;
1094 }
1095
1096 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1097 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001098 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001099 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001100}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001101
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001102status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1103 Vector<ColorMode>* outColorModes) {
1104 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001105 return BAD_VALUE;
1106 }
1107
Peiyong Lina52f0292018-03-14 17:26:31 -07001108 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001109 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001110 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001111 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1112
1113 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1114 if (!displayId) {
1115 return NAME_NOT_FOUND;
1116 }
1117
Dominik Laskowski075d3172018-05-24 15:50:06 -07001118 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001119 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001120 }
Michael Wright28f24d02016-07-12 13:30:53 -07001121 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001122
1123 // If it's built-in display and the configuration claims it's not wide color capable,
1124 // filter out all wide color modes. The typical reason why this happens is that the
1125 // hardware is not good enough to support GPU composition of wide color, and thus the
1126 // OEMs choose to disable this capability.
1127 if (isInternalDisplay && !hasWideColorDisplay) {
1128 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1129 isWideColorMode);
1130 } else {
1131 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1132 }
Michael Wright28f24d02016-07-12 13:30:53 -07001133
1134 return NO_ERROR;
1135}
1136
Daniel Solomon42d04562019-01-20 21:03:19 -08001137status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1138 ui::DisplayPrimaries &primaries) {
1139 if (!displayToken) {
1140 return BAD_VALUE;
1141 }
1142
1143 // Currently we only support this API for a single internal display.
1144 if (getInternalDisplayToken() != displayToken) {
1145 return BAD_VALUE;
1146 }
1147
1148 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1149 return NO_ERROR;
1150}
1151
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001152ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1153 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001154 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001155 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001156 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001157}
1158
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001159status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001160 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001161 Vector<ColorMode> modes;
1162 getDisplayColorModes(displayToken, &modes);
1163 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1164 if (mode < ColorMode::NATIVE || !exists) {
1165 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1166 decodeColorMode(mode).c_str(), mode, displayToken.get());
1167 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001168 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001169 const auto display = getDisplayDevice(displayToken);
1170 if (!display) {
1171 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1172 decodeColorMode(mode).c_str(), mode, displayToken.get());
1173 } else if (display->isVirtual()) {
1174 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1175 decodeColorMode(mode).c_str(), mode);
1176 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001177 display->getCompositionDisplay()->setColorProfile(
1178 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1179 RenderIntent::COLORIMETRIC,
1180 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001181 }
1182 }));
1183
Michael Wright28f24d02016-07-12 13:30:53 -07001184 return NO_ERROR;
1185}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001186
Galia Peycheva5492cb52019-10-30 14:13:16 +01001187status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1188 bool* outSupport) const {
1189 Mutex::Autolock _l(mStateLock);
1190
1191 if (!displayToken) {
1192 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1193 return BAD_VALUE;
1194 }
1195 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1196 if (!displayId) {
1197 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1198 displayToken.get());
1199 return NAME_NOT_FOUND;
1200 }
1201 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1202 HWC2::DisplayCapability::AutoLowLatencyMode);
1203 return NO_ERROR;
1204}
1205
1206void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1207 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1208}
1209
1210void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1211 if (!displayToken) {
1212 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1213 return;
1214 }
1215 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1216 if (!displayId) {
1217 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1218 displayToken.get());
1219 return;
1220 }
1221
1222 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1223}
1224
1225status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1226 bool* outSupport) const {
1227 Mutex::Autolock _l(mStateLock);
1228
1229 if (!displayToken) {
1230 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1231 return BAD_VALUE;
1232 }
1233 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1234 if (!displayId) {
1235 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1236 displayToken.get());
1237 return NAME_NOT_FOUND;
1238 }
1239
1240 std::vector<HWC2::ContentType> outSupportedContentTypes;
1241 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1242 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1243 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1244 return NO_ERROR;
1245}
1246
1247void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1248 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1249}
1250
1251void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1252 if (!displayToken) {
1253 ALOGE("setGameContentType() failed. Missing display token.");
1254 return;
1255 }
1256 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1257 if (!displayId) {
1258 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1259 displayToken.get());
1260 return;
1261 }
1262
1263 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1264 getHwComposer().setContentType(*displayId, type);
1265}
1266
Svetoslavd85084b2014-03-20 10:28:31 -07001267status_t SurfaceFlinger::clearAnimationFrameStats() {
1268 Mutex::Autolock _l(mStateLock);
1269 mAnimFrameTracker.clearStats();
1270 return NO_ERROR;
1271}
1272
1273status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1274 Mutex::Autolock _l(mStateLock);
1275 mAnimFrameTracker.getStats(outStats);
1276 return NO_ERROR;
1277}
1278
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001279status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1280 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001281 Mutex::Autolock _l(mStateLock);
1282
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001283 const auto display = getDisplayDeviceLocked(displayToken);
1284 if (!display) {
1285 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001286 return BAD_VALUE;
1287 }
1288
Peiyong Linfb069302018-04-25 14:34:31 -07001289 // At this point the DisplayDeivce should already be set up,
1290 // meaning the luminance information is already queried from
1291 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001292 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001293 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1294 capabilities.getDesiredMaxLuminance(),
1295 capabilities.getDesiredMaxAverageLuminance(),
1296 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001297
1298 return NO_ERROR;
1299}
1300
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001301std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1302 const DisplayDevice& display) const {
1303 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1304 // avoid repetitive HAL IPC and EDID parsing.
1305 const auto displayId = display.getId();
1306 LOG_FATAL_IF(!displayId);
1307
1308 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1309 LOG_FATAL_IF(!hwcDisplayId);
1310
1311 uint8_t port;
1312 DisplayIdentificationData data;
1313 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1314 ALOGV("%s: No identification data.", __FUNCTION__);
1315 return {};
1316 }
1317
1318 const auto info = parseDisplayIdentificationData(port, data);
1319 if (!info) {
1320 return {};
1321 }
1322 return info->deviceProductInfo;
1323}
1324
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001325status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1326 ui::PixelFormat* outFormat,
1327 ui::Dataspace* outDataspace,
1328 uint8_t* outComponentMask) const {
1329 if (!outFormat || !outDataspace || !outComponentMask) {
1330 return BAD_VALUE;
1331 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001332 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001333 if (!display || !display->getId()) {
1334 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1335 return BAD_VALUE;
1336 }
1337 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1338 outDataspace, outComponentMask);
1339}
1340
Kevin DuBois74e53772018-11-19 10:52:38 -08001341status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1342 bool enable, uint8_t componentMask,
1343 uint64_t maxFrames) const {
1344 const auto display = getDisplayDevice(displayToken);
1345 if (!display || !display->getId()) {
1346 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1347 return BAD_VALUE;
1348 }
1349
1350 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1351 componentMask, maxFrames);
1352}
1353
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001354status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1355 uint64_t maxFrames, uint64_t timestamp,
1356 DisplayedFrameStats* outStats) const {
1357 const auto display = getDisplayDevice(displayToken);
1358 if (!display || !display->getId()) {
1359 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1360 return BAD_VALUE;
1361 }
1362
1363 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1364 outStats);
1365}
1366
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001367status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1368 if (!outSupported) {
1369 return BAD_VALUE;
1370 }
1371 *outSupported = getRenderEngine().supportsProtectedContent();
1372 return NO_ERROR;
1373}
1374
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001375status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1376 bool* outIsWideColorDisplay) const {
1377 if (!displayToken || !outIsWideColorDisplay) {
1378 return BAD_VALUE;
1379 }
1380 Mutex::Autolock _l(mStateLock);
1381 const auto display = getDisplayDeviceLocked(displayToken);
1382 if (!display) {
1383 return BAD_VALUE;
1384 }
Peiyong Linff84a152019-05-17 18:36:19 -07001385
1386 // Use hasWideColorDisplay to override built-in display.
1387 const auto displayId = display->getId();
1388 if (displayId && displayId == getInternalDisplayIdLocked()) {
1389 *outIsWideColorDisplay = hasWideColorDisplay;
1390 return NO_ERROR;
1391 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001392 *outIsWideColorDisplay = display->hasWideColorGamut();
1393 return NO_ERROR;
1394}
1395
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001396status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001397 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001398 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001399
Dominik Laskowski6505f792019-09-18 11:10:05 -07001400 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1401 mEventQueue->setEventConnection(
1402 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001403 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001404 }));
1405
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001406 return NO_ERROR;
1407}
1408
1409status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001410 Mutex::Autolock lock(mStateLock);
1411 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001412}
1413
Lloyd Pique755e3192018-01-31 16:46:15 -08001414status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1415 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001416 // Try to acquire a lock for 1s, fail gracefully
1417 const status_t err = mStateLock.timedLock(s2ns(1));
1418 const bool locked = (err == NO_ERROR);
1419 if (!locked) {
1420 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1421 return TIMED_OUT;
1422 }
1423
1424 outLayers->clear();
1425 mCurrentState.traverseInZOrder([&](Layer* layer) {
1426 outLayers->push_back(layer->getLayerDebugInfo());
1427 });
1428
1429 mStateLock.unlock();
1430 return NO_ERROR;
1431}
1432
Peiyong Linc6780972018-10-28 15:24:08 -07001433status_t SurfaceFlinger::getCompositionPreference(
1434 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1435 Dataspace* outWideColorGamutDataspace,
1436 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001437 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001438 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001439 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001440 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001441 return NO_ERROR;
1442}
1443
Dan Stozaec460082018-12-17 15:35:09 -08001444status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1445 const sp<IBinder>& stopLayerHandle,
1446 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001447 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001448 return BAD_VALUE;
1449 }
1450 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001451 return NO_ERROR;
1452}
1453
Dan Stozaec460082018-12-17 15:35:09 -08001454status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001455 if (!listener) {
1456 return BAD_VALUE;
1457 }
Dan Stozaec460082018-12-17 15:35:09 -08001458 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001459 return NO_ERROR;
1460}
Dan Gittik57e63c52019-01-18 16:37:54 +00001461
1462status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1463 bool* outSupport) const {
1464 if (!displayToken || !outSupport) {
1465 return BAD_VALUE;
1466 }
1467 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1468 if (!displayId) {
1469 return NAME_NOT_FOUND;
1470 }
1471 *outSupport =
1472 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1473 return NO_ERROR;
1474}
1475
1476status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1477 float brightness) const {
1478 if (!displayToken) {
1479 return BAD_VALUE;
1480 }
1481 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1482 if (!displayId) {
1483 return NAME_NOT_FOUND;
1484 }
1485 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1486}
1487
Ady Abraham8532d012019-05-08 14:50:56 -07001488status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1489 PowerHint powerHint = static_cast<PowerHint>(hintId);
1490
1491 if (powerHint == PowerHint::INTERACTION) {
1492 mScheduler->notifyTouchEvent();
1493 }
1494
1495 return NO_ERROR;
1496}
1497
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001498// ----------------------------------------------------------------------------
1499
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001500sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001501 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001502 const auto& handle =
1503 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001504
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001505 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001506}
1507
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001508// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001509
1510void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001511 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001512}
1513
1514void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001515 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001516 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001517 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001518}
1519
1520void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001521 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001522 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001523 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001524}
1525
1526void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001527 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001528 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001529}
1530
1531status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001532 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001533 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001534}
1535
1536status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001537 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001538 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001539 if (res == NO_ERROR) {
1540 msg->wait();
1541 }
1542 return res;
1543}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001544
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001545void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001546 do {
1547 waitForEvent();
1548 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001549}
1550
Dominik Laskowski83b88212018-12-11 13:34:06 -08001551nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001552 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001553 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1554 return 0;
1555 }
1556
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001557 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001558}
1559
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001560void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001561 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001562 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001563 ATRACE_NAME("SF onVsync");
1564
Steven Thomas3cfac282017-02-06 12:29:30 -08001565 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001566 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001567 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001568 return;
1569 }
1570
Dominik Laskowski075d3172018-05-24 15:50:06 -07001571 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001572 return;
1573 }
1574
Dominik Laskowski075d3172018-05-24 15:50:06 -07001575 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001576 // For now, we don't do anything with external display vsyncs.
1577 return;
1578 }
1579
Alec Mourif8e689c2019-05-20 18:32:22 -07001580 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001581 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001582 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001583 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001584 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001585}
1586
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001587void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001588 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1589 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001590}
1591
Ady Abraham2139f732019-11-13 18:56:40 -08001592bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001593 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001594}
1595
Ady Abraham2139f732019-11-13 18:56:40 -08001596void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1597 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001598 const auto display = getDefaultDisplayDeviceLocked();
1599 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001600 return;
1601 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001602 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001603
Ana Krulec7d1d6832018-12-27 11:10:09 -08001604 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001605 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1606 ALOGV("Skipping config %d as it is not part of allowed configs",
1607 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001608 return;
1609 }
1610
Ady Abraham2139f732019-11-13 18:56:40 -08001611 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001612}
1613
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001614void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001615 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001616 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001617 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001618
Lloyd Piqueba04e622017-12-14 17:11:26 -08001619 // Ignore events that do not have the right sequenceId.
1620 if (sequenceId != getBE().mComposerSequenceId) {
1621 return;
1622 }
1623
Steven Thomasb02664d2017-07-26 18:48:28 -07001624 // Only lock if we're not on the main thread. This function is normally
1625 // called on a hwbinder thread, but for the primary display it's called on
1626 // the main thread with the state lock already held, so don't attempt to
1627 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001628 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001629
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001630 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001631
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001632 if (std::this_thread::get_id() == mMainThreadId) {
1633 // Process all pending hot plug events immediately if we are on the main thread.
1634 processDisplayHotplugEventsLocked();
1635 }
1636
Lloyd Piqueba04e622017-12-14 17:11:26 -08001637 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001638}
1639
Ady Abraham7159f572019-10-11 11:10:18 -07001640void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001641 int32_t sequenceId, hwc2_display_t /*display*/,
1642 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1643 Mutex::Autolock lock(mStateLock);
1644 if (sequenceId != getBE().mComposerSequenceId) {
1645 return;
1646 }
1647 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001648}
1649
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001650void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1651 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1652 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1653}
1654
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001655void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001656 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001657 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001658 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001659 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001660 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001661}
1662
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001663void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001664 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001665
1666 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1667 // display power state.
1668 postMessageAsync(new LambdaMessage(
1669 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1670}
1671
1672void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1673 ATRACE_CALL();
1674
Ady Abraham27c70212019-06-11 10:52:26 -07001675 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1676
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001677 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001678 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1679 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001680 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001681 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001682 }
Mathias Agopian86303202012-07-24 22:46:10 -07001683}
1684
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001685// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001686void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001687 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001688 // Clear the drawing state so that the logic inside of
1689 // handleTransactionLocked will fire. It will determine the delta between
1690 // mCurrentState and mDrawingState and re-apply all changes when we make the
1691 // transition.
1692 mDrawingState.displays.clear();
1693 mDisplays.clear();
1694}
1695
Steven Thomas050b2c82017-03-06 11:45:16 -08001696void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001697 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001698 if (!mVrFlinger)
1699 return;
1700 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001701 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001702 return;
1703 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001704
Lloyd Pique441d5042018-10-18 16:49:51 -07001705 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001706 ALOGE("Vr flinger is only supported for remote hardware composer"
1707 " service connections. Ignoring request to transition to vr"
1708 " flinger.");
1709 mVrFlingerRequestsDisplay = false;
1710 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001711 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001712
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001713 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001714
Steven Thomas0123ac62018-07-12 11:32:34 -07001715 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001716 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001717
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001718 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001719
1720 // Clear out all the output layers from the composition engine for all
1721 // displays before destroying the hardware composer interface. This ensures
1722 // any HWC layers are destroyed through that interface before it becomes
1723 // invalid.
1724 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001725 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001726 }
1727
Steven Thomas0123ac62018-07-12 11:32:34 -07001728 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1729 // called below. Clear the reference now so we don't accidentally use it
1730 // later.
1731 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001732
Steven Thomasb02664d2017-07-26 18:48:28 -07001733 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001734 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001735 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001736
Steven Thomasb02664d2017-07-26 18:48:28 -07001737 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001738 // Delete the current instance before creating the new one
1739 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1740 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1741 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001742 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001743
Lloyd Pique441d5042018-10-18 16:49:51 -07001744 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001745 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001746
1747 if (vrFlingerRequestsDisplay) {
1748 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001749 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001750
1751 mVisibleRegionsDirty = true;
1752 invalidateHwcGeometry();
1753
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001754 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001755 display = getDefaultDisplayDeviceLocked();
1756 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001757 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001758
Steven Thomasb02664d2017-07-26 18:48:28 -07001759 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001760 const nsecs_t vsyncPeriod = getVsyncPeriod();
1761 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001762
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001763 // The present fences returned from vr_hwc are not an accurate
1764 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001765 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001766
Steven Thomasb02664d2017-07-26 18:48:28 -07001767 // Use phase of 0 since phase is not known.
1768 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001769 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001770 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001771
Ana Krulecc2870422019-01-29 19:00:58 -08001772 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001773
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001774 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001775 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001776}
1777
Alec Mouri6d414b52020-03-17 11:18:05 -07001778sp<Fence> SurfaceFlinger::previousFrameFence() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001779 // We are storing the last 2 present fences. If sf's phase offset is to be
1780 // woken up before the actual vsync but targeting the next vsync, we need to check
1781 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001782 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1783 : mPreviousPresentFences[1];
1784}
1785
1786bool SurfaceFlinger::previousFramePending(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1787 ATRACE_CALL();
1788 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001789
Ady Abraham11579302019-09-19 12:35:58 -07001790 if (fence == Fence::NO_FENCE) {
1791 return false;
1792 }
1793
1794 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1795 fence->wait(graceTimeMs);
1796 }
1797
1798 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001799}
1800
Alec Mouri6d414b52020-03-17 11:18:05 -07001801nsecs_t SurfaceFlinger::previousFramePresentTime() NO_THREAD_SAFETY_ANALYSIS {
1802 const sp<Fence>& fence = previousFrameFence();
1803
1804 if (fence == Fence::NO_FENCE) {
1805 return Fence::SIGNAL_TIME_INVALID;
1806 }
1807
1808 return fence->getSignalTime();
1809}
1810
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001811void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001812 DisplayStatInfo stats;
1813 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001814 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001815 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001816 mExpectedPresentTime.store(
1817 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001818}
1819
Dominik Laskowski22488f62019-03-28 09:53:04 -07001820void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001821 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001822 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001823 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001824 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001825 // calculate the expected present time once and use the cached
1826 // value throughout this frame to make sure all layers are
1827 // seeing this same value.
Alec Mouri6d414b52020-03-17 11:18:05 -07001828 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001829 populateExpectedPresentTime();
1830
Ady Abraham11579302019-09-19 12:35:58 -07001831 // When Backpressure propagation is enabled we want to give a small grace period
1832 // for the present fence to fire instead of just giving up on this frame to handle cases
1833 // where present fence is just about to get signaled.
1834 const int graceTimeForPresentFenceMs =
1835 (mPropagateBackpressure &&
1836 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1837 ? 1
1838 : 0;
Alec Mouri6d414b52020-03-17 11:18:05 -07001839
1840 // Pending frames may trigger backpressure propagation.
1841 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1842 previousFramePending(
1843 graceTimeForPresentFenceMs)};
1844
1845 // Frame missed counts for metrics tracking.
1846 // A frame is missed if the prior frame is still pending. If no longer pending,
1847 // then we still count the frame as missed if the predicted present time
1848 // was further in the past than when the fence actually fired.
1849
1850 // Add some slop to correct for drift. This should generally be
1851 // smaller than a typical frame duration, but should not be so small
1852 // that it reports reasonable drift as a missed frame.
1853 DisplayStatInfo stats;
1854 mScheduler->getDisplayStatInfo(&stats);
1855 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1856 const nsecs_t previousPresentTime = previousFramePresentTime();
1857 const TracedOrdinal<bool> frameMissed =
1858 {"PrevFrameMissed",
1859 framePending ||
1860 (previousPresentTime >= 0 &&
1861 (lastExpectedPresentTime < previousPresentTime - frameMissedSlop))};
1862 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001863 mHadDeviceComposition && frameMissed};
Alec Mouri6d414b52020-03-17 11:18:05 -07001864 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001865 mHadClientComposition && frameMissed};
1866
Alec Mouricc0fc602019-02-26 21:45:19 -08001867 if (frameMissed) {
1868 mFrameMissedCount++;
1869 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001870 if (mMissedFrameJankCount == 0) {
1871 mMissedFrameJankStart = systemTime();
1872 }
1873 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001874 }
1875
Alec Mouri40189b02019-03-05 15:07:54 -08001876 if (hwcFrameMissed) {
1877 mHwcFrameMissedCount++;
1878 }
1879
1880 if (gpuFrameMissed) {
1881 mGpuFrameMissedCount++;
1882 }
1883
Alec Mouri6d414b52020-03-17 11:18:05 -07001884 if (framePending && mPropagateBackpressure) {
Ady Abrahamadb9a992019-09-19 21:21:55 +00001885 if ((hwcFrameMissed && !gpuFrameMissed) ||
1886 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001887 signalLayerUpdate();
1888 break;
1889 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001890 }
Dan Stoza50182882016-07-08 12:02:20 -07001891
Alec Mouri989ddbe2020-02-06 09:26:19 -08001892 // Our jank window is always at least 100ms since we missed a
1893 // frame...
1894 static constexpr nsecs_t kMinJankyDuration =
1895 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1896 // ...but if it's larger than 1s then we missed the trace cutoff.
1897 static constexpr nsecs_t kMaxJankyDuration =
1898 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1899 // If we're in a user build then don't push any atoms
1900 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1901 const auto displayDevice = getDefaultDisplayDeviceLocked();
1902 // Only report jank when the display is on, as displays in DOZE
1903 // power mode may operate at a different frame rate than is
1904 // reported in their config, which causes noticeable (but less
1905 // severe) jank.
1906 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1907 const nsecs_t currentTime = systemTime();
1908 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1909 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1910 ATRACE_NAME("Jank detected");
1911 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1912 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1913 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1914 jankyDurationMillis, mMissedFrameJankCount);
1915 }
1916
1917 // We either reported a jank event or we missed the trace
1918 // window, so clear counters here.
1919 if (jankDuration > kMinJankyDuration) {
1920 mMissedFrameJankCount = 0;
1921 mMissedFrameJankStart = 0;
1922 }
1923 }
1924 }
1925
Steven Thomas050b2c82017-03-06 11:45:16 -08001926 // Now that we're going to make it to the handleMessageTransaction()
1927 // call below it's safe to call updateVrFlinger(), which will
1928 // potentially trigger a display handoff.
1929 updateVrFlinger();
1930
Dan Stoza6b9454d2014-11-07 16:00:59 -08001931 bool refreshNeeded = handleMessageTransaction();
1932 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001933
Ana Krulecc84d09b2019-11-02 23:10:29 +01001934 // Layers need to get updated (in the previous line) before we can use them for
1935 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001936 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1937 // and may eventually call to ~Layer() if it holds the last reference
1938 {
1939 Mutex::Autolock _l(mStateLock);
1940 mScheduler->chooseRefreshRateForContent();
1941 }
1942
Ana Krulecc84d09b2019-11-02 23:10:29 +01001943 if (performSetActiveConfig()) {
1944 break;
1945 }
1946
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001947 updateCursorAsync();
1948 updateInputFlinger();
1949
Dan Stoza58784442014-12-02 16:58:17 -08001950 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001951 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001952 // Signal a refresh if a transaction modified the window state,
1953 // a new buffer was latched, or if HWC has requested a full
1954 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001955 if (mFrameStartTime <= 0) {
1956 // We should only use the time of the first invalidate
1957 // message that signals a refresh as the beginning of the
1958 // frame. Otherwise the real frame time will be
1959 // underestimated.
1960 mFrameStartTime = frameStart;
1961 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001962 signalRefresh();
1963 }
1964 break;
1965 }
1966 case MessageQueue::REFRESH: {
1967 handleMessageRefresh();
1968 break;
1969 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001970 }
1971}
1972
Dan Stoza6b9454d2014-11-07 16:00:59 -08001973bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001974 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001975 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001976
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001977 bool flushedATransaction = flushTransactionQueues();
1978
1979 bool runHandleTransaction = transactionFlags &&
1980 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1981
1982 if (runHandleTransaction) {
1983 handleTransaction(eTransactionMask);
1984 } else {
1985 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001986 }
1987
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001988 if (transactionFlushNeeded()) {
1989 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001990 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001991
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001992 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001993}
1994
Mathias Agopian4fec8732012-06-29 14:12:52 -07001995void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001996 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001997
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001998 mRefreshPending = false;
1999
Lloyd Piqueab039b52019-02-13 14:22:42 -08002000 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002001 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002002 for (const auto& [_, display] : mDisplays) {
2003 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2004 }
2005 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002006 if (auto layerFE = layer->getCompositionEngineLayerFE())
2007 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002008 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002009 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2010 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002011 if (auto layerFE = layer->getCompositionEngineLayerFE())
2012 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002013 }
2014
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002015 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002016 refreshArgs.outputColorSetting = useColorManagement
2017 ? mDisplayColorSetting
2018 : compositionengine::OutputColorSetting::kUnmanaged;
2019 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2020 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002021
2022 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2023 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002024 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002025
2026 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2027 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2028 mDrawingState.colorMatrixChanged = false;
2029 }
2030
2031 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2032
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002033 if (mDebugRegion != 0) {
2034 refreshArgs.devOptFlashDirtyRegionsDelay =
2035 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2036 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002037
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002038 mGeometryInvalid = false;
2039
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002040 // Store the present time just before calling to the composition engine so we could notify
2041 // the scheduler.
2042 const auto presentTime = systemTime();
2043
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002044 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002045 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2046 // Reset the frame start time now that we've recorded this frame.
2047 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002048
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002049 mScheduler->onDisplayRefreshed(presentTime);
2050
David Sodmanfa9b2af2017-12-24 13:28:59 -08002051 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002052 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002053
Lloyd Pique66d68602019-02-13 14:23:31 -08002054 mHadClientComposition =
2055 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2056 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002057 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2058 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002059 });
2060 mHadDeviceComposition =
2061 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2062 auto& displayDevice = tokenDisplayPair.second;
2063 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2064 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002065 mReusedClientComposition =
2066 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2067 auto& displayDevice = tokenDisplayPair.second;
2068 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2069 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002070
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002071 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002072
David Sodman7e4ae112018-02-09 15:02:28 -08002073 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002074 if (mVisibleRegionsDirty) {
2075 mVisibleRegionsDirty = false;
2076 if (mTracingEnabled) {
2077 mTracing.notify("visibleRegionsDirty");
2078 }
2079 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002080
2081 if (mCompositionEngine->needsAnotherUpdate()) {
2082 signalLayerUpdate();
2083 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002084}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002085
David Sodmanfa9b2af2017-12-24 13:28:59 -08002086
2087bool SurfaceFlinger::handleMessageInvalidate() {
2088 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002089 bool refreshNeeded = handlePageFlip();
2090
Vishnu Nair4351ad52019-02-11 14:13:02 -08002091 if (mVisibleRegionsDirty) {
2092 computeLayerBounds();
2093 }
2094
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002095 for (auto& layer : mLayersPendingRefresh) {
2096 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002097 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002098 invalidateLayerStack(layer, visibleReg);
2099 }
2100 mLayersPendingRefresh.clear();
2101 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002102}
2103
Ana Krulece588e312018-09-18 12:32:24 -07002104void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2105 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002106 // Update queue of past composite+present times and determine the
2107 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002108 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002109 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002110 while (!getBE().mCompositePresentTimes.empty()) {
2111 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002112 // Cached values should have been updated before calling this method,
2113 // which helps avoid duplicate syscalls.
2114 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2115 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2116 break;
2117 }
2118 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002119 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002120 }
2121
2122 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002123 while (getBE().mCompositePresentTimes.size() > 16) {
2124 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002125 }
2126
Ana Krulece588e312018-09-18 12:32:24 -07002127 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002128}
2129
Ana Krulece588e312018-09-18 12:32:24 -07002130void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2131 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002132 // Integer division and modulo round toward 0 not -inf, so we need to
2133 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002134 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2135 ? (stats.vsyncPeriod -
2136 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2137 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002138
Ady Abraham9e16a482019-12-03 17:19:41 -08002139 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002140 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002141 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002142 }
2143
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002144 // Snap the latency to a value that removes scheduling jitter from the
2145 // composition and present times, which often have >1ms of jitter.
2146 // Reducing jitter is important if an app attempts to extrapolate
2147 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002148 // Snapping also allows an app to precisely calculate
2149 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002150 nsecs_t bias = stats.vsyncPeriod / 2;
2151 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2152 nsecs_t snappedCompositeToPresentLatency =
2153 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002154
David Sodman99974d22017-11-28 12:04:33 -08002155 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002156 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2157 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002158 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002159}
2160
David Sodman2b406362017-12-15 13:33:47 -08002161void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002162{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002163 ATRACE_CALL();
2164 ALOGV("postComposition");
2165
Brian Andersonf6386862016-10-31 16:34:13 -07002166 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002167 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002168 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002169 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002170 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002171 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002172
David Sodman73beded2017-11-15 11:56:06 -08002173 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002174 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002175 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002176 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002177 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2178 ->getRenderSurface()
2179 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002180 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002181 } else {
2182 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2183 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002184
David Sodman73beded2017-11-15 11:56:06 -08002185 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002186 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2187 mPreviousPresentFences[0] = displayDevice
2188 ? getHwComposer().getPresentFence(*displayDevice->getId())
2189 : Fence::NO_FENCE;
2190 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002191 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002192
Ana Krulece588e312018-09-18 12:32:24 -07002193 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002194 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002195
Lloyd Piqueab039b52019-02-13 14:22:42 -08002196 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2197 // be sampled a little later than when we started doing work for this frame,
2198 // but that should be okay since updateCompositorTiming has snapping logic.
2199 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2200 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002201 CompositorTiming compositorTiming;
2202 {
David Sodman99974d22017-11-28 12:04:33 -08002203 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2204 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002205 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002206
Edgar Arriaga844fa672020-01-16 14:21:42 -08002207 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002208 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2209 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002210 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002211 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002212 }
Robert Carr2047fae2016-11-28 14:09:09 -08002213 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002214
Ady Abraham92fa2f42020-02-11 15:33:56 -08002215 if (displayDevice && displayDevice->isPrimary() &&
2216 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002217 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002218 }
2219
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002220 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002221 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2222 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002223 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002224 }
2225 }
2226
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002227 if (mAnimCompositionPending) {
2228 mAnimCompositionPending = false;
2229
Brian Anderson4e606e32017-03-16 15:34:57 -07002230 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002231 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002232 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002233 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002234 // The HWC doesn't support present fences, so use the refresh
2235 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002236 const nsecs_t presentTime =
2237 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002238 mAnimFrameTracker.setActualPresentTime(presentTime);
2239 }
2240 mAnimFrameTracker.advanceFrame();
2241 }
Dan Stozab90cf072015-03-05 11:05:59 -08002242
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002243 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002244 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002245 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002246 }
2247
Vishnu Nair9b079a22020-01-21 14:36:08 -08002248 if (mReusedClientComposition) {
2249 mTimeStats->incrementClientCompositionReusedFrames();
2250 }
2251
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002252 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002253
Alec Mouri717bcb62020-02-10 17:07:19 -08002254 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2255 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2256 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2257
Lloyd Pique32cbe282018-10-19 13:09:22 -07002258 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2259 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002260 return;
2261 }
2262
2263 nsecs_t currentTime = systemTime();
2264 if (mHasPoweredOff) {
2265 mHasPoweredOff = false;
2266 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002267 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002268 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002269 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2270 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002271 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002272 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002273 }
David Sodman4a36e932017-11-07 14:29:47 -08002274 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002275 }
David Sodman4a36e932017-11-07 14:29:47 -08002276 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002277
2278 {
2279 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002280 if (mTexturePool.size() < mTexturePoolSize) {
2281 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002282 const size_t offset = mTexturePool.size();
2283 mTexturePool.resize(mTexturePoolSize);
2284 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2285 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002286 } else if (mTexturePool.size() > mTexturePoolSize) {
2287 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2288 const size_t offset = mTexturePoolSize;
2289 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2290 mTexturePool.resize(mTexturePoolSize);
2291 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002292 }
2293 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002294
Ady Abrahambe0f9482019-04-24 15:41:53 -07002295 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002296 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002297
Kevin DuBois413287f2019-02-25 08:46:47 -08002298 if (mLumaSampling && mRegionSamplingThread) {
2299 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002300 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002301
2302 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2303 // side-effect of getTotalSize(), so we check that again here
2304 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002305 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002306 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2307 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002308}
2309
Vishnu Nair4351ad52019-02-11 14:13:02 -08002310void SurfaceFlinger::computeLayerBounds() {
2311 for (const auto& pair : mDisplays) {
2312 const auto& displayDevice = pair.second;
2313 const auto display = displayDevice->getCompositionDisplay();
2314 for (const auto& layer : mDrawingState.layersSortedByZ) {
2315 // only consider the layers on the given layer stack
2316 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002317 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002318 }
2319
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002320 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2321 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002322 }
2323 }
2324}
2325
David Sodmanfa9b2af2017-12-24 13:28:59 -08002326void SurfaceFlinger::postFrame()
2327{
2328 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002329 const auto display = getDefaultDisplayDeviceLocked();
2330 if (display && getHwComposer().isConnected(*display->getId())) {
2331 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002332 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2333 logFrameStats();
2334 }
2335 }
2336}
2337
Mathias Agopian87baae12012-07-31 12:38:26 -07002338void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002339{
Mathias Agopian841cde52012-03-01 15:44:37 -08002340 ATRACE_CALL();
2341
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002342 // here we keep a copy of the drawing state (that is the state that's
2343 // going to be overwritten by handleTransactionLocked()) outside of
2344 // mStateLock so that the side-effects of the State assignment
2345 // don't happen with mStateLock held (which can cause deadlocks).
2346 State drawingState(mDrawingState);
2347
Mathias Agopianca4d3602011-05-19 15:38:14 -07002348 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002349 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002350
Mathias Agopianca4d3602011-05-19 15:38:14 -07002351 // Here we're guaranteed that some transaction flags are set
2352 // so we can call handleTransactionLocked() unconditionally.
2353 // We call getTransactionFlags(), which will also clear the flags,
2354 // with mStateLock held to guarantee that mCurrentState won't change
2355 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002356
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002357 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002358 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002359 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002360
Mathias Agopianca4d3602011-05-19 15:38:14 -07002361 mDebugInTransaction = 0;
2362 invalidateHwcGeometry();
2363 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002364}
2365
Lloyd Piqueba04e622017-12-14 17:11:26 -08002366void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2367 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002368 const std::optional<DisplayIdentificationInfo> info =
2369 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002370
Dominik Laskowski075d3172018-05-24 15:50:06 -07002371 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002372 continue;
2373 }
2374
Dominik Laskowski55c85402020-01-21 16:25:47 -08002375 const DisplayId displayId = info->id;
2376 const auto it = mPhysicalDisplayTokens.find(displayId);
2377
Lloyd Piqueba04e622017-12-14 17:11:26 -08002378 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002379 if (it == mPhysicalDisplayTokens.end()) {
2380 ALOGV("Creating display %s", to_string(displayId).c_str());
2381
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002382 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002383 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002384 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002385
Dominik Laskowski075d3172018-05-24 15:50:06 -07002386 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002387 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002388 state.isSecure = true; // All physical displays are currently considered secure.
2389 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002390
2391 sp<IBinder> token = new BBinder();
2392 mCurrentState.displays.add(token, state);
2393 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2394
Dominik Laskowski075d3172018-05-24 15:50:06 -07002395 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002396 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002397 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002398 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002399
Dominik Laskowski55c85402020-01-21 16:25:47 -08002400 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002401 if (index >= 0) {
2402 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2403 mInterceptor->saveDisplayDeletion(state.sequenceId);
2404 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002405 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002406 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002407 }
2408
2409 processDisplayChangesLocked();
2410 }
2411
2412 mPendingHotplugEvents.clear();
2413}
2414
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002415void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002416 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2417 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002418}
2419
Lloyd Pique99d3da52018-01-22 17:48:03 -08002420sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002421 const wp<IBinder>& displayToken,
2422 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002423 const DisplayDeviceState& state,
2424 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002425 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002426 auto displayId = compositionDisplay->getDisplayId();
2427 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002428 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002429 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002430 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002431 creationArgs.hasWideColorGamut = false;
2432 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002433
Dominik Laskowski55c85402020-01-21 16:25:47 -08002434 if (const auto& physical = state.physical) {
2435 creationArgs.connectionType = physical->type;
2436 }
2437
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002438 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002439 creationArgs.isPrimary = isInternalDisplay;
2440
2441 if (useColorManagement && displayId) {
2442 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002443 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002444 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002445 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002446 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002447
Dominik Laskowski7e045462018-05-30 13:02:02 -07002448 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002449 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002450 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002451 }
tangrobin6753a022018-08-10 10:58:54 +08002452 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002453
Dominik Laskowski075d3172018-05-24 15:50:06 -07002454 if (displayId) {
2455 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002456 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002457 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002458 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002459
Lloyd Pique90c115d2018-09-18 21:39:42 -07002460 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002461 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002462 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002463
Lloyd Pique99d3da52018-01-22 17:48:03 -08002464 // Make sure that composition can never be stalled by a virtual display
2465 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002466 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002467 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002468 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2469 }
2470
Dominik Laskowski718f9602019-11-09 20:01:35 -08002471 creationArgs.physicalOrientation =
2472 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002473
Lloyd Pique99d3da52018-01-22 17:48:03 -08002474 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002475 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002476
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002477 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002478
2479 if (maxFrameBufferAcquiredBuffers >= 3) {
2480 nativeWindowSurface->preallocateBuffers();
2481 }
2482
2483 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002484 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002485 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002486 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002487 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002488 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002489 display->getCompositionDisplay()->setColorProfile(
2490 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2491 RenderIntent::COLORIMETRIC,
2492 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002493 if (!state.isVirtual()) {
2494 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002495 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2496 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002497 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002498
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002499 display->setLayerStack(state.layerStack);
2500 display->setProjection(state.orientation, state.viewport, state.frame);
2501 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002502
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002503 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002504}
2505
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002506void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2507 const DisplayDeviceState& state) {
2508 int width = 0;
2509 int height = 0;
2510 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2511 if (state.physical) {
2512 const auto& activeConfig =
2513 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2514 width = activeConfig->getWidth();
2515 height = activeConfig->getHeight();
2516 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2517 } else if (state.surface != nullptr) {
2518 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2519 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2520 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2521 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2522 int intPixelFormat;
2523 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2524 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2525 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2526 } else {
2527 // Virtual displays without a surface are dormant:
2528 // they have external state (layer stack, projection,
2529 // etc.) but no internal state (i.e. a DisplayDevice).
2530 return;
2531 }
2532
2533 compositionengine::DisplayCreationArgsBuilder builder;
2534 if (const auto& physical = state.physical) {
2535 builder.setPhysical({physical->id, physical->type});
2536 }
2537 builder.setPixels(ui::Size(width, height));
2538 builder.setPixelFormat(pixelFormat);
2539 builder.setIsSecure(state.isSecure);
2540 builder.setLayerStackId(state.layerStack);
2541 builder.setPowerAdvisor(&mPowerAdvisor);
2542 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2543 builder.setName(state.displayName);
2544 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2545
2546 sp<compositionengine::DisplaySurface> displaySurface;
2547 sp<IGraphicBufferProducer> producer;
2548 sp<IGraphicBufferProducer> bqProducer;
2549 sp<IGraphicBufferConsumer> bqConsumer;
2550 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2551
2552 std::optional<DisplayId> displayId = compositionDisplay->getId();
2553
2554 if (state.isVirtual()) {
2555 sp<VirtualDisplaySurface> vds =
2556 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2557 bqConsumer, state.displayName);
2558
2559 displaySurface = vds;
2560 producer = vds;
2561 } else {
2562 ALOGE_IF(state.surface != nullptr,
2563 "adding a supported display, but rendering "
2564 "surface is provided (%p), ignoring it",
2565 state.surface.get());
2566
2567 LOG_ALWAYS_FATAL_IF(!displayId);
2568 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2569 maxGraphicsWidth, maxGraphicsHeight);
2570 producer = bqProducer;
2571 }
2572
2573 if (displaySurface != nullptr) {
2574 mDisplays.emplace(displayToken,
2575 setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2576 displaySurface, producer));
2577 if (!state.isVirtual()) {
2578 LOG_ALWAYS_FATAL_IF(!displayId);
2579 dispatchDisplayHotplugEvent(displayId->value, true);
2580 }
2581
2582 const auto displayDevice = mDisplays[displayToken];
2583 if (displayDevice->isPrimary()) {
2584 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2585 displayDevice->getHeight());
2586 }
2587 }
2588}
2589
2590void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2591 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2592 // Save display ID before disconnecting.
2593 const auto displayId = display->getId();
2594 display->disconnect();
2595
2596 if (!display->isVirtual()) {
2597 LOG_ALWAYS_FATAL_IF(!displayId);
2598 dispatchDisplayHotplugEvent(displayId->value, false);
2599 }
2600 }
2601
2602 mDisplays.erase(displayToken);
2603}
2604
2605void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2606 const DisplayDeviceState& currentState,
2607 const DisplayDeviceState& drawingState) {
2608 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2609 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
2610 if (currentBinder != drawingBinder) {
2611 // changing the surface is like destroying and recreating the DisplayDevice
2612 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2613 display->disconnect();
2614 }
2615 mDisplays.erase(displayToken);
2616 processDisplayAdded(displayToken, currentState);
2617 return;
2618 }
2619
2620 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2621 if (currentState.layerStack != drawingState.layerStack) {
2622 display->setLayerStack(currentState.layerStack);
2623 }
2624 if ((currentState.orientation != drawingState.orientation) ||
2625 (currentState.viewport != drawingState.viewport) ||
2626 (currentState.frame != drawingState.frame)) {
2627 display->setProjection(currentState.orientation, currentState.viewport,
2628 currentState.frame);
2629 }
2630 if (currentState.width != drawingState.width ||
2631 currentState.height != drawingState.height) {
2632 display->setDisplaySize(currentState.width, currentState.height);
2633 if (display->isPrimary()) {
2634 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2635 }
2636 }
2637 }
2638}
2639
Lloyd Pique347200f2017-12-14 17:00:15 -08002640void SurfaceFlinger::processDisplayChangesLocked() {
2641 // here we take advantage of Vector's copy-on-write semantics to
2642 // improve performance by skipping the transaction entirely when
2643 // know that the lists are identical
2644 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2645 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2646 if (!curr.isIdenticalTo(draw)) {
2647 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002648
2649 // find the displays that were removed
2650 // (ie: in drawing state but not in current state)
2651 // also handle displays that changed
2652 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002653 for (size_t i = 0; i < draw.size(); i++) {
2654 const wp<IBinder>& displayToken = draw.keyAt(i);
2655 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002656 if (j < 0) {
2657 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002658 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002659 } else {
2660 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002661 const DisplayDeviceState& currentState = curr[j];
2662 const DisplayDeviceState& drawingState = draw[i];
2663 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002664 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002665 }
2666
2667 // find displays that were added
2668 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002669 for (size_t i = 0; i < curr.size(); i++) {
2670 const wp<IBinder>& displayToken = curr.keyAt(i);
2671 if (draw.indexOfKey(displayToken) < 0) {
2672 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002673 }
2674 }
2675 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002676
2677 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002678}
2679
Mathias Agopian87baae12012-07-31 12:38:26 -07002680void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002681{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002682 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2683
Dan Stoza7dde5992015-05-22 09:51:44 -07002684 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002685 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002686 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002687 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002688
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002689 /*
2690 * Traversal of the children
2691 * (perform the transaction for each of them if needed)
2692 */
2693
Marissa Wall06255332019-03-27 13:48:27 -07002694 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002695 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002696 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002697 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002698
2699 const uint32_t flags = layer->doTransaction(0);
2700 if (flags & Layer::eVisibleRegion)
2701 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002702
2703 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002704 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002705 }
Robert Carr2047fae2016-11-28 14:09:09 -08002706 });
Marissa Wall06255332019-03-27 13:48:27 -07002707 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002708 }
2709
2710 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002711 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002712 */
2713
Mathias Agopiane57f2922012-08-09 16:29:12 -07002714 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002715 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002716 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002717 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002719 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002720 // The transform hint might have changed for some layers
2721 // (either because a display has changed, or because a layer
2722 // as changed).
2723 //
2724 // Walk through all the layers in currentLayers,
2725 // and update their transform hint.
2726 //
2727 // If a layer is visible only on a single display, then that
2728 // display is used to calculate the hint, otherwise we use the
2729 // default display.
2730 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002731 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002732 // the hint is set before we acquire a buffer from the surface texture.
2733 //
2734 // NOTE: layer transactions have taken place already, so we use their
2735 // drawing state. However, SurfaceFlinger's own transaction has not
2736 // happened yet, so we must use the current state layer list
2737 // (soon to become the drawing state list).
2738 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002739 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002740 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002741 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002742 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002743 // NOTE: we rely on the fact that layers are sorted by
2744 // layerStack first (so we don't have to traverse the list
2745 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002746 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002747 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002748 currentlayerStack = layerStack;
2749 // figure out if this layerstack is mirrored
2750 // (more than one display) if so, pick the default display,
2751 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002752 hintDisplay = nullptr;
2753 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002754 if (display->getCompositionDisplay()
2755 ->belongsInOutput(layer->getLayerStack(),
2756 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002757 if (hintDisplay) {
2758 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002759 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002760 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002761 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002762 }
2763 }
2764 }
2765 }
Chet Haase91d25932013-04-11 15:24:55 -07002766
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002767 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002768 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2769 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002770
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002771 // could be null when this layer is using a layerStack
2772 // that is not visible on any display. Also can occur at
2773 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002774 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002775 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002776
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002777 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002778 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002779 if (hintDisplay) {
2780 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002781 }
Robert Carr2047fae2016-11-28 14:09:09 -08002782
2783 first = false;
2784 });
Mathias Agopian84300952012-11-21 16:02:13 -08002785 }
2786
2787
Mathias Agopian3559b072012-08-15 13:46:03 -07002788 /*
2789 * Perform our own transaction if needed
2790 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002791
2792 if (mLayersAdded) {
2793 mLayersAdded = false;
2794 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002795 mVisibleRegionsDirty = true;
2796 }
2797
2798 // some layers might have been removed, so
2799 // we need to update the regions they're exposing.
2800 if (mLayersRemoved) {
2801 mLayersRemoved = false;
2802 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002803 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002804 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002805 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002806 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002807 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002808 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002809 }
Robert Carr2047fae2016-11-28 14:09:09 -08002810 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811 }
2812
Vishnu Nairec0ab382019-02-13 15:32:56 -08002813 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002815}
2816
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002817void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002818 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002819 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002820 return;
2821 }
2822
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002823 if (mVisibleRegionsDirty || mInputInfoChanged) {
2824 mInputInfoChanged = false;
2825 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002826 } else if (mInputWindowCommands.syncInputWindows) {
2827 // If the caller requested to sync input windows, but there are no
2828 // changes to input windows, notify immediately.
2829 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002830 }
2831
Arthur Hung6cbb9752019-09-05 16:38:18 +08002832 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002833}
2834
2835void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002836 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002837
Robert Carra1257842020-01-31 13:48:28 -08002838 // We use a simple caching algorithm here. mInputDirty begins as true,
2839 // after we call setInputWindows we set it to false, so
2840 // in the future we wont call it again.. We set input dirty to true again
2841 // when any layer that hasInput() has a transaction performed on it
2842 // or when any parent or relative parent of such a layer has a transaction
2843 // performed on it. Not all of these transactions will really result in
2844 // input changes but all input changes will spring from these transactions
2845 // so the cache is safe but not optimal. It seems like it might be annoyingly
2846 // costly to cache and comapre the actual InputWindowHandle vector though.
Robert Carr0854b992020-03-11 12:09:42 -07002847 if (!mInputDirty && !mInputWindowCommands.syncInputWindows) {
Robert Carra1257842020-01-31 13:48:28 -08002848 return;
2849 }
2850
Robert Carr720e5062018-07-30 17:45:14 -07002851 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2852 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002853 // When calculating the screen bounds we ignore the transparent region since it may
2854 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002855 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002856 }
2857 });
chaviw291d88a2019-02-14 10:33:58 -08002858
2859 mInputFlinger->setInputWindows(inputHandles,
2860 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2861 : nullptr);
Robert Carra1257842020-01-31 13:48:28 -08002862
2863 mInputDirty = false;
Robert Carr720e5062018-07-30 17:45:14 -07002864}
2865
Vishnu Nairec0ab382019-02-13 15:32:56 -08002866void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002867 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002868 mPendingInputWindowCommands.clear();
2869}
2870
Riley Andrews03414a12014-07-01 14:22:59 -07002871void SurfaceFlinger::updateCursorAsync()
2872{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002873 compositionengine::CompositionRefreshArgs refreshArgs;
2874 for (const auto& [_, display] : mDisplays) {
2875 if (display->getId()) {
2876 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002877 }
2878 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002879
2880 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002881}
2882
Ady Abraham2139f732019-11-13 18:56:40 -08002883void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002884 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2885 // If this is called from the main thread mStateLock must be locked before
2886 // Currently the only way to call this function from the main thread is from
2887 // Sheduler::chooseRefreshRateForContent
2888
2889 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002890 changeRefreshRateLocked(refreshRate, event);
2891}
2892
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002893void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2894 if (mScheduler) {
2895 // In practice it's not allowed to hotplug in/out the primary display once it's been
2896 // connected during startup, but some tests do it, so just warn and return.
2897 ALOGW("Can't re-init scheduler");
2898 return;
2899 }
2900
Ady Abraham2139f732019-11-13 18:56:40 -08002901 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002902 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002903 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002904 primaryDisplayId),
2905 currentConfig);
2906 mRefreshRateStats =
2907 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2908 currentConfig, HWC_POWER_MODE_OFF);
2909 mRefreshRateStats->setConfigMode(currentConfig);
2910
Ady Abraham9e16a482019-12-03 17:19:41 -08002911 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2912
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002913 // start the EventThread
2914 mScheduler =
2915 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002916 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002917 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002918 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002919 impl::EventThread::InterceptVSyncsCallback());
2920 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002921 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002922 [this](nsecs_t timestamp) {
2923 mInterceptor->saveVSyncEvent(timestamp);
2924 });
2925
2926 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2927 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002928 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002929
2930 mRegionSamplingThread =
2931 new RegionSamplingThread(*this, *mScheduler,
2932 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002933 // Dispatch a config change request for the primary display on scheduler
2934 // initialization, so that the EventThreads always contain a reference to a
2935 // prior configuration.
2936 //
2937 // This is a bit hacky, but this avoids a back-pointer into the main SF
2938 // classes from EventThread, and there should be no run-time binder cost
2939 // anyway since there are no connected apps at this point.
2940 const nsecs_t vsyncPeriod =
2941 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2942 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2943 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002944}
2945
Mathias Agopian4fec8732012-06-29 14:12:52 -07002946void SurfaceFlinger::commitTransaction()
2947{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002948 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002949
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002950 mTransactionPending = false;
2951 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002952 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002953}
2954
Lloyd Pique58e24a32019-08-01 15:50:14 -07002955void SurfaceFlinger::commitTransactionLocked() {
2956 if (!mLayersPendingRemoval.isEmpty()) {
2957 // Notify removed layers now that they can't be drawn from
2958 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002959 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002960
2961 // Ensure any buffers set to display on any children are released.
2962 if (l->isRemovedFromCurrentState()) {
2963 l->latchAndReleaseBuffer();
2964 }
2965
2966 // If the layer has been removed and has no parent, then it will not be reachable
2967 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2968 // ensure we can copy its current to drawing state.
2969 if (!l->getParent()) {
2970 mOffscreenLayers.emplace(l.get());
2971 }
2972 }
2973 mLayersPendingRemoval.clear();
2974 }
2975
2976 // If this transaction is part of a window animation then the next frame
2977 // we composite should be considered an animation as well.
2978 mAnimCompositionPending = mAnimTransactionPending;
2979
2980 mDrawingState = mCurrentState;
2981 // clear the "changed" flags in current state
2982 mCurrentState.colorMatrixChanged = false;
2983
Edgar Arriaga844fa672020-01-16 14:21:42 -08002984 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002985 layer->commitChildList();
2986
2987 // If the layer can be reached when traversing mDrawingState, then the layer is no
2988 // longer offscreen. Remove the layer from the offscreenLayer set.
2989 if (mOffscreenLayers.count(layer)) {
2990 mOffscreenLayers.erase(layer);
2991 }
2992 });
2993
2994 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002995 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002996}
2997
Nataniel Borges2b796da2019-02-15 13:32:18 -08002998void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2999 if (mTracingEnabledChanged) {
3000 mTracingEnabled = mTracing.isEnabled();
3001 mTracingEnabledChanged = false;
3002 }
3003
3004 // Synchronize with Tracing thread
3005 std::unique_lock<std::mutex> lock;
3006 if (mTracingEnabled) {
3007 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3008 }
3009
3010 lockedOperation();
3011
3012 // Synchronize with Tracing thread
3013 if (mTracingEnabled) {
3014 lock.unlock();
3015 }
3016}
3017
chaviw74d90ad2019-04-26 14:45:26 -07003018void SurfaceFlinger::commitOffscreenLayers() {
3019 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003020 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003021 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3022 if (!trFlags) return;
3023
3024 layer->doTransaction(0);
3025 layer->commitChildList();
3026 });
3027 }
3028}
3029
Chia-I Wuab0c3192017-08-01 11:29:00 -07003030void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003031 for (const auto& [token, displayDevice] : mDisplays) {
3032 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003033 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003034 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003035 }
3036 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003037}
3038
Dan Stoza6b9454d2014-11-07 16:00:59 -08003039bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003040{
Ady Abraham09bd3922019-04-08 10:44:56 -07003041 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003042 ALOGV("handlePageFlip");
3043
Brian Andersond6927fb2016-07-23 23:37:30 -07003044 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003045
Mathias Agopian4fec8732012-06-29 14:12:52 -07003046 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003047 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003048 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003049
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003050 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3051
Eric Penner51c59cd2014-07-28 19:51:58 -07003052 // Store the set of layers that need updates. This set must not change as
3053 // buffers are being latched, as this could result in a deadlock.
3054 // Example: Two producers share the same command stream and:
3055 // 1.) Layer 0 is latched
3056 // 2.) Layer 0 gets a new frame
3057 // 2.) Layer 1 gets a new frame
3058 // 3.) Layer 1 is latched.
3059 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3060 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003061 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003062 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003063 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003064 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003065 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003066 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003067 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003068 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003069 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003070 } else {
3071 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003072 }
Robert Carr2047fae2016-11-28 14:09:09 -08003073 });
3074
chaviw49a108c2019-08-12 11:23:06 -07003075 // The client can continue submitting buffers for offscreen layers, but they will not
3076 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3077 // layers to ensure dequeueBuffer doesn't block indefinitely.
3078 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003079 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003080 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3081 }
3082
Lloyd Piquef2c79392018-12-20 16:23:33 -08003083 if (!mLayersWithQueuedFrames.empty()) {
3084 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3085 // writes to Layer current state. See also b/119481871
3086 Mutex::Autolock lock(mStateLock);
3087
3088 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003089 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003090 mLayersPendingRefresh.push_back(layer);
3091 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003092 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003093 if (layer->isBufferLatched()) {
3094 newDataLatched = true;
3095 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003096 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003097 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003098
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003099 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003100
3101 // If we will need to wake up at some time in the future to deal with a
3102 // queued frame that shouldn't be displayed during this vsync period, wake
3103 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003104 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003105 signalLayerUpdate();
3106 }
3107
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003108 // enter boot animation on first buffer latch
3109 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3110 ALOGI("Enter boot animation");
3111 mBootStage = BootStage::BOOTANIMATION;
3112 }
3113
Edgar Arriaga844fa672020-01-16 14:21:42 -08003114 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003115
Dan Stoza6b9454d2014-11-07 16:00:59 -08003116 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003117 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003118}
3119
Mathias Agopianad456f92011-01-13 17:53:01 -08003120void SurfaceFlinger::invalidateHwcGeometry()
3121{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003122 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003123}
3124
Robert Carrc0df3122019-04-11 13:18:21 -07003125status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3126 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3127 const sp<IBinder>& parentHandle,
3128 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003129 // add this layer to the current state list
3130 {
3131 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003132 sp<Layer> parent;
3133 if (parentHandle != nullptr) {
3134 parent = fromHandle(parentHandle);
3135 if (parent == nullptr) {
3136 return NAME_NOT_FOUND;
3137 }
3138 } else {
3139 parent = parentLayer;
3140 }
3141
Ady Abraham0a525092020-03-03 12:51:24 -08003142 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003143 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003144 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003145 return NO_MEMORY;
3146 }
Robert Carrc0df3122019-04-11 13:18:21 -07003147
3148 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3149
Robert Carrb89ea9d2018-12-10 13:01:14 -08003150 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003151 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003152 } else if (parent == nullptr) {
3153 lbc->onRemovedFromCurrentState();
3154 } else if (parent->isRemovedFromCurrentState()) {
3155 parent->addChild(lbc);
3156 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003157 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003158 parent->addChild(lbc);
3159 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003160
Yiwei Zhang243b3782018-05-15 17:40:04 -07003161 if (gbc != nullptr) {
3162 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3163 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3164 mMaxGraphicBufferProducerListSize,
3165 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3166 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003167 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003168 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003169 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003170 }
3171
Mathias Agopian96f08192010-06-02 23:28:45 -07003172 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003173 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003174
Dan Stoza7d89d062015-04-30 13:29:25 -07003175 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003176}
3177
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003178uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003179 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003180}
3181
Mathias Agopian3f844832013-08-07 21:24:32 -07003182uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003183 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003184}
3185
Mathias Agopian3f844832013-08-07 21:24:32 -07003186uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003187 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003188}
3189
3190uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003191 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003192 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003193 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003194 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003195 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003196 }
3197 return old;
3198}
3199
Marissa Wall713b63f2018-10-17 15:42:43 -07003200bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003201 // to prevent onHandleDestroyed from being called while the lock is held,
3202 // we must keep a copy of the transactions (specifically the composer
3203 // states) around outside the scope of the lock
3204 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003205 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003206 {
3207 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003208
Valerie Haufce31b82019-04-30 16:41:14 -07003209 auto it = mTransactionQueues.begin();
3210 while (it != mTransactionQueues.end()) {
3211 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003212
Valerie Haufce31b82019-04-30 16:41:14 -07003213 while (!transactionQueue.empty()) {
3214 const auto& transaction = transactionQueue.front();
3215 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003216 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003217 transaction.states)) {
3218 setTransactionFlags(eTransactionFlushNeeded);
3219 break;
3220 }
3221 transactions.push_back(transaction);
3222 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3223 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003224 transaction.buffer, transaction.postTime,
3225 transaction.privileged, transaction.hasListenerCallbacks,
3226 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003227 transactionQueue.pop();
3228 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003229 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003230
Valerie Haufce31b82019-04-30 16:41:14 -07003231 if (transactionQueue.empty()) {
3232 it = mTransactionQueues.erase(it);
3233 mTransactionCV.broadcast();
3234 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003235 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003236 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003237 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003238 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003239 return flushedATransaction;
3240}
3241
3242bool SurfaceFlinger::transactionFlushNeeded() {
3243 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003244}
3245
chaviwca27f252018-02-06 16:46:39 -08003246
Marissa Wall17b4e452018-12-26 16:32:34 -08003247bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003248 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003249 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003250 if (!useCachedExpectedPresentTime)
3251 populateExpectedPresentTime();
3252
3253 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003254 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3255 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3256 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3257 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3258 return false;
3259 }
3260
Marissa Wall713b63f2018-10-17 15:42:43 -07003261 for (const ComposerState& state : states) {
3262 const layer_state_t& s = state.state;
3263 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3264 continue;
3265 }
3266 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003267 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003268 }
3269 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003270 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003271}
3272
Valerie Hau9dab9732019-08-20 09:29:25 -07003273void SurfaceFlinger::setTransactionState(
3274 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3275 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3276 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3277 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003278 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003279
Valerie Haubc6ddb12019-03-08 11:10:15 -08003280 const int64_t postTime = systemTime();
3281
Robert Carr14167e02019-02-13 13:50:55 -08003282 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3283
Mathias Agopian698c0872011-06-28 19:09:31 -07003284 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003285
Marissa Wall713b63f2018-10-17 15:42:43 -07003286 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003287 auto itr = mTransactionQueues.find(applyToken);
3288 // if this is an animation frame, wait until prior animation frame has
3289 // been applied by SF
3290 if (flags & eAnimation) {
3291 while (itr != mTransactionQueues.end()) {
3292 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3293 if (CC_UNLIKELY(err != NO_ERROR)) {
3294 ALOGW_IF(err == TIMED_OUT,
3295 "setTransactionState timed out "
3296 "waiting for animation frame to apply");
3297 break;
3298 }
3299 itr = mTransactionQueues.find(applyToken);
3300 }
3301 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003302
3303 // Expected present time is computed and cached on invalidate, so it may be stale.
3304 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3305 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003306 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003307 uncacheBuffer, postTime, privileged,
3308 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003309 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003310 return;
3311 }
3312
Valerie Haubc6ddb12019-03-08 11:10:15 -08003313 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003314 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3315 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003316}
3317
Valerie Hau9dab9732019-08-20 09:29:25 -07003318void SurfaceFlinger::applyTransactionState(
3319 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3320 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3321 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3322 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3323 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003324 uint32_t transactionFlags = 0;
3325
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003326 if (flags & eAnimation) {
3327 // For window updates that are part of an animation we must wait for
3328 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003329 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003330 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003331 if (CC_UNLIKELY(err != NO_ERROR)) {
3332 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003333 // caller after a few seconds.
3334 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3335 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003336 mAnimTransactionPending = false;
3337 break;
3338 }
3339 }
3340 }
3341
chaviwca27f252018-02-06 16:46:39 -08003342 for (const DisplayState& display : displays) {
3343 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003344 }
3345
Valerie Hau9dab9732019-08-20 09:29:25 -07003346 // start and end registration for listeners w/ no surface so they can get their callback. Note
3347 // that listeners with SurfaceControls will start registration during setClientStateLocked
3348 // below.
3349 for (const auto& listener : listenerCallbacks) {
3350 mTransactionCompletedThread.startRegistration(listener);
3351 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003352 }
3353
Valerie Hau9dab9732019-08-20 09:29:25 -07003354 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003355 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003356 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003357 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3358 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003359 }
3360
Valerie Hau9dab9732019-08-20 09:29:25 -07003361 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003362 mTransactionCompletedThread.endRegistration(listenerCallback);
3363 }
3364
Marissa Walle2ffb422018-10-12 11:33:52 -07003365 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003366 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003367 mTransactionCompletedThread.sendCallbacks();
3368 }
3369 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003370
chaviw273171b2018-12-26 11:46:30 -08003371 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3372
Marissa Wall947d34e2019-03-29 14:03:53 -07003373 if (uncacheBuffer.isValid()) {
3374 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003375 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003376 }
3377
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003378 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3379 // anyway. This can be used as a flush mechanism for previous async transactions.
3380 // Empty animation transaction can be used to simulate back-pressure, so also force a
3381 // transaction for empty animation transactions.
3382 if (transactionFlags == 0 &&
3383 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003384 transactionFlags = eTransactionNeeded;
3385 }
3386
Marissa Wall06255332019-03-27 13:48:27 -07003387 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3388 // so we don't have to wake up again next frame to preform an uneeded traversal.
3389 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3390 transactionFlags = transactionFlags & (~eTraversalNeeded);
3391 mTraversalNeededMainThread = true;
3392 }
3393
Mathias Agopian386aa982011-11-07 21:58:03 -08003394 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003395 if (mInterceptor->isEnabled()) {
3396 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003397 }
Irvel468051e2016-06-13 16:44:44 -07003398
Mathias Agopian386aa982011-11-07 21:58:03 -08003399 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003400 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3401 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003402 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003403
3404 // if this is a synchronous transaction, wait for it to take effect
3405 // before returning.
3406 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003407 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003408 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003409 if (flags & eAnimation) {
3410 mAnimTransactionPending = true;
3411 }
chaviw4fe36852019-04-15 16:25:49 -07003412 if (mPendingInputWindowCommands.syncInputWindows) {
3413 mPendingSyncInputWindows = true;
3414 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003415
3416 // applyTransactionState can be called by either the main SF thread or by
3417 // another process through setTransactionState. While a given process may wish
3418 // to wait on synchronous transactions, the main SF thread should never
3419 // be blocked. Therefore, we only wait if isMainThread is false.
3420 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003421 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3422 if (CC_UNLIKELY(err != NO_ERROR)) {
3423 // just in case something goes wrong in SF, return to the
3424 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003425 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3426 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003427 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003428 break;
3429 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003430 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003431 }
3432}
3433
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003434uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3435 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3436 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003437
Mathias Agopiane57f2922012-08-09 16:29:12 -07003438 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003439 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3440
3441 const uint32_t what = s.what;
3442 if (what & DisplayState::eSurfaceChanged) {
3443 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3444 state.surface = s.surface;
3445 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003446 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003447 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003448 if (what & DisplayState::eLayerStackChanged) {
3449 if (state.layerStack != s.layerStack) {
3450 state.layerStack = s.layerStack;
3451 flags |= eDisplayTransactionNeeded;
3452 }
3453 }
3454 if (what & DisplayState::eDisplayProjectionChanged) {
3455 if (state.orientation != s.orientation) {
3456 state.orientation = s.orientation;
3457 flags |= eDisplayTransactionNeeded;
3458 }
3459 if (state.frame != s.frame) {
3460 state.frame = s.frame;
3461 flags |= eDisplayTransactionNeeded;
3462 }
3463 if (state.viewport != s.viewport) {
3464 state.viewport = s.viewport;
3465 flags |= eDisplayTransactionNeeded;
3466 }
3467 }
3468 if (what & DisplayState::eDisplaySizeChanged) {
3469 if (state.width != s.width) {
3470 state.width = s.width;
3471 flags |= eDisplayTransactionNeeded;
3472 }
3473 if (state.height != s.height) {
3474 state.height = s.height;
3475 flags |= eDisplayTransactionNeeded;
3476 }
3477 }
3478
Mathias Agopiane57f2922012-08-09 16:29:12 -07003479 return flags;
3480}
3481
Robert Carr14167e02019-02-13 13:50:55 -08003482bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003483 IPCThreadState* ipc = IPCThreadState::self();
3484 const int pid = ipc->getCallingPid();
3485 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003486 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003487 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003488 return false;
3489 }
3490 return true;
3491}
3492
Marissa Wall3dad52d2019-03-22 14:03:19 -07003493uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003494 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3495 bool privileged,
3496 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003497 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003498
Valerie Hau9dab9732019-08-20 09:29:25 -07003499 for (auto& listener : s.listeners) {
3500 // note that startRegistration will not re-register if the listener has
3501 // already be registered for a prior surface control
3502 mTransactionCompletedThread.startRegistration(listener);
3503 listenerCallbacks.insert(listener);
3504 }
3505
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003506 sp<Layer> layer = nullptr;
3507 if (s.surface) {
3508 layer = fromHandle(s.surface);
3509 } else {
3510 // The client may provide us a null handle. Treat it as if the layer was removed.
3511 ALOGW("Attempt to set client state with a null layer handle");
3512 }
chaviw8b3871a2017-11-01 17:41:01 -07003513 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003514 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003515 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003516 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003517 }
chaviw8b3871a2017-11-01 17:41:01 -07003518 return 0;
3519 }
3520
chaviw8b3871a2017-11-01 17:41:01 -07003521 uint32_t flags = 0;
3522
Garfield Tan8a3083e2018-12-03 13:21:07 -08003523 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003524
3525 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3526 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003527 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003528 layer->pushPendingState();
3529 }
3530
Valerie Hau871d6352020-01-29 08:44:02 -08003531 // Only set by BLAST adapter layers
3532 if (what & layer_state_t::eProducerDisconnect) {
3533 layer->onDisconnect();
3534 }
3535
chaviw8b3871a2017-11-01 17:41:01 -07003536 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003537 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003538 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003539 }
chaviw8b3871a2017-11-01 17:41:01 -07003540 }
3541 if (what & layer_state_t::eLayerChanged) {
3542 // NOTE: index needs to be calculated before we update the state
3543 const auto& p = layer->getParent();
3544 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003545 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003546 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003547 mCurrentState.layersSortedByZ.removeAt(idx);
3548 mCurrentState.layersSortedByZ.add(layer);
3549 // we need traversal (state changed)
3550 // AND transaction (list changed)
3551 flags |= eTransactionNeeded|eTraversalNeeded;
3552 }
chaviw8b3871a2017-11-01 17:41:01 -07003553 } else {
3554 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003555 flags |= eTransactionNeeded|eTraversalNeeded;
3556 }
3557 }
chaviw8b3871a2017-11-01 17:41:01 -07003558 }
3559 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003560 // NOTE: index needs to be calculated before we update the state
3561 const auto& p = layer->getParent();
3562 if (p == nullptr) {
3563 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3564 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3565 mCurrentState.layersSortedByZ.removeAt(idx);
3566 mCurrentState.layersSortedByZ.add(layer);
3567 // we need traversal (state changed)
3568 // AND transaction (list changed)
3569 flags |= eTransactionNeeded|eTraversalNeeded;
3570 }
3571 } else {
3572 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3573 flags |= eTransactionNeeded|eTraversalNeeded;
3574 }
chaviw8b3871a2017-11-01 17:41:01 -07003575 }
3576 }
3577 if (what & layer_state_t::eSizeChanged) {
3578 if (layer->setSize(s.w, s.h)) {
3579 flags |= eTraversalNeeded;
3580 }
3581 }
3582 if (what & layer_state_t::eAlphaChanged) {
3583 if (layer->setAlpha(s.alpha))
3584 flags |= eTraversalNeeded;
3585 }
3586 if (what & layer_state_t::eColorChanged) {
3587 if (layer->setColor(s.color))
3588 flags |= eTraversalNeeded;
3589 }
Peiyong Lind3788632018-09-18 16:01:31 -07003590 if (what & layer_state_t::eColorTransformChanged) {
3591 if (layer->setColorTransform(s.colorTransform)) {
3592 flags |= eTraversalNeeded;
3593 }
3594 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003595 if (what & layer_state_t::eBackgroundColorChanged) {
3596 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3597 flags |= eTraversalNeeded;
3598 }
3599 }
chaviw8b3871a2017-11-01 17:41:01 -07003600 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003601 // TODO: b/109894387
3602 //
3603 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3604 // rotation. To see the problem observe that if we have a square parent, and a child
3605 // of the same size, then we rotate the child 45 degrees around it's center, the child
3606 // must now be cropped to a non rectangular 8 sided region.
3607 //
3608 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3609 // private API, and the WindowManager only uses rotation in one case, which is on a top
3610 // level layer in which cropping is not an issue.
3611 //
3612 // However given that abuse of rotation matrices could lead to surfaces extending outside
3613 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3614 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3615 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003616 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003617 flags |= eTraversalNeeded;
3618 }
3619 if (what & layer_state_t::eTransparentRegionChanged) {
3620 if (layer->setTransparentRegionHint(s.transparentRegion))
3621 flags |= eTraversalNeeded;
3622 }
3623 if (what & layer_state_t::eFlagsChanged) {
3624 if (layer->setFlags(s.flags, s.mask))
3625 flags |= eTraversalNeeded;
3626 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003627 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003628 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003629 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003630 if (what & layer_state_t::eCornerRadiusChanged) {
3631 if (layer->setCornerRadius(s.cornerRadius))
3632 flags |= eTraversalNeeded;
3633 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003634 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003635 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3636 }
chaviw8b3871a2017-11-01 17:41:01 -07003637 if (what & layer_state_t::eLayerStackChanged) {
3638 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3639 // We only allow setting layer stacks for top level layers,
3640 // everything else inherits layer stack from its parent.
3641 if (layer->hasParent()) {
3642 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003643 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003644 } else if (idx < 0) {
3645 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003646 "that also does not appear in the top level layer list. Something"
3647 " has gone wrong.",
3648 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003649 } else if (layer->setLayerStack(s.layerStack)) {
3650 mCurrentState.layersSortedByZ.removeAt(idx);
3651 mCurrentState.layersSortedByZ.add(layer);
3652 // we need traversal (state changed)
3653 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003654 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003655 }
3656 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003657 if (what & layer_state_t::eDeferTransaction_legacy) {
3658 if (s.barrierHandle_legacy != nullptr) {
3659 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3660 } else if (s.barrierGbp_legacy != nullptr) {
3661 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003662 if (authenticateSurfaceTextureLocked(gbp)) {
3663 const auto& otherLayer =
3664 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003665 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003666 } else {
3667 ALOGE("Attempt to defer transaction to to an"
3668 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003669 }
3670 }
chaviw8b3871a2017-11-01 17:41:01 -07003671 // We don't trigger a traversal here because if no other state is
3672 // changed, we don't want this to cause any more work
3673 }
chaviw8b3871a2017-11-01 17:41:01 -07003674 if (what & layer_state_t::eReparentChildren) {
3675 if (layer->reparentChildren(s.reparentHandle)) {
3676 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003677 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003678 }
chaviw8b3871a2017-11-01 17:41:01 -07003679 if (what & layer_state_t::eDetachChildren) {
3680 layer->detachChildren();
3681 }
3682 if (what & layer_state_t::eOverrideScalingModeChanged) {
3683 layer->setOverrideScalingMode(s.overrideScalingMode);
3684 // We don't trigger a traversal here because if no other state is
3685 // changed, we don't want this to cause any more work
3686 }
Marissa Wall61c58622018-07-18 10:12:20 -07003687 if (what & layer_state_t::eTransformChanged) {
3688 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3689 }
3690 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3691 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3692 flags |= eTraversalNeeded;
3693 }
3694 if (what & layer_state_t::eCropChanged) {
3695 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3696 }
Marissa Wall861616d2018-10-22 12:52:23 -07003697 if (what & layer_state_t::eFrameChanged) {
3698 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3699 }
Marissa Wall61c58622018-07-18 10:12:20 -07003700 if (what & layer_state_t::eAcquireFenceChanged) {
3701 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3702 }
3703 if (what & layer_state_t::eDataspaceChanged) {
3704 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3705 }
3706 if (what & layer_state_t::eHdrMetadataChanged) {
3707 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3708 }
3709 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3710 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3711 }
3712 if (what & layer_state_t::eApiChanged) {
3713 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3714 }
3715 if (what & layer_state_t::eSidebandStreamChanged) {
3716 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3717 }
Robert Carr720e5062018-07-30 17:45:14 -07003718 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003719 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003720 layer->setInputInfo(s.inputInfo);
3721 flags |= eTraversalNeeded;
3722 } else {
3723 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3724 }
Robert Carr720e5062018-07-30 17:45:14 -07003725 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003726 if (what & layer_state_t::eMetadataChanged) {
3727 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3728 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003729 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3730 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3731 flags |= eTraversalNeeded;
3732 }
3733 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003734 if (what & layer_state_t::eShadowRadiusChanged) {
3735 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3736 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003737 if (what & layer_state_t::eFrameRateSelectionPriority) {
3738 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3739 flags |= eTraversalNeeded;
3740 }
3741 }
Steven Thomas3172e202020-01-06 19:25:30 -08003742 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003743 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3744 "SurfaceFlinger::setClientStateLocked") &&
3745 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3746 Layer::FrameRate::convertCompatibility(
3747 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003748 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003749 }
Steven Thomas3172e202020-01-06 19:25:30 -08003750 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003751 // This has to happen after we reparent children because when we reparent to null we remove
3752 // child layers from current state and remove its relative z. If the children are reparented in
3753 // the same transaction, then we have to make sure we reparent the children first so we do not
3754 // lose its relative z order.
3755 if (what & layer_state_t::eReparent) {
3756 bool hadParent = layer->hasParent();
3757 if (layer->reparent(s.parentHandleForChild)) {
3758 if (!hadParent) {
3759 mCurrentState.layersSortedByZ.remove(layer);
3760 }
3761 flags |= eTransactionNeeded | eTraversalNeeded;
3762 }
3763 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003764 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003765 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3766 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003767 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3768 }
3769 }
Marissa Wall78b72202019-03-15 14:58:34 -07003770 bool bufferChanged = what & layer_state_t::eBufferChanged;
3771 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3772 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003773 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003774 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003775 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3776 if (success) {
3777 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3778 success = ClientCache::getInstance()
3779 .registerErasedRecipient(s.cachedBuffer,
3780 wp<ClientCache::ErasedRecipient>(this));
3781 if (!success) {
3782 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3783 }
3784 }
Marissa Wall78b72202019-03-15 14:58:34 -07003785 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003786 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003787 } else if (bufferChanged) {
3788 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003789 }
Marissa Wall78b72202019-03-15 14:58:34 -07003790 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003791 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3792 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003793 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003794 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003795 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003796 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3797 // Do not put anything that updates layer state or modifies flags after
3798 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003799 return flags;
3800}
3801
chaviw273171b2018-12-26 11:46:30 -08003802uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3803 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003804 if (inputWindowCommands.syncInputWindows) {
3805 flags |= eTraversalNeeded;
3806 }
3807
Vishnu Nairec0ab382019-02-13 15:32:56 -08003808 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003809 return flags;
3810}
3811
chaviwfe94a222019-08-21 13:52:59 -07003812status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3813 sp<IBinder>* outHandle) {
3814 if (!mirrorFromHandle) {
3815 return NAME_NOT_FOUND;
3816 }
3817
3818 sp<Layer> mirrorLayer;
3819 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003820 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003821
3822 {
3823 Mutex::Autolock _l(mStateLock);
3824 mirrorFrom = fromHandle(mirrorFromHandle);
3825 if (!mirrorFrom) {
3826 return NAME_NOT_FOUND;
3827 }
3828
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003829 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3830 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003831 if (result != NO_ERROR) {
3832 return result;
3833 }
3834
3835 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3836 }
3837
3838 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3839}
3840
Marissa Wall2d814fb2019-04-09 18:52:57 +00003841status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3842 uint32_t h, PixelFormat format, uint32_t flags,
3843 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003844 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003845 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3846 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003847 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003848 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003849 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003850 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003851 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003852
Robert Carrc0df3122019-04-11 13:18:21 -07003853 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3854 "Expected only one of parentLayer or parentHandle to be non-null. "
3855 "Programmer error?");
3856
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003857 status_t result = NO_ERROR;
3858
3859 sp<Layer> layer;
3860
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003861 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003862
Evan Roskya1f1e152019-01-24 16:17:46 -08003863 bool primaryDisplayOnly = false;
3864
3865 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3866 // TODO b/64227542
3867 if (metadata.has(METADATA_WINDOW_TYPE)) {
3868 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3869 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003870 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003871 primaryDisplayOnly = true;
3872 }
3873 }
3874
Mathias Agopian3165cc22012-08-08 19:42:09 -07003875 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003876 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003877 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3878 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003879
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003880 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003881 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003882 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003883 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003884 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003885 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003886 // check if buffer size is set for color layer.
3887 if (w > 0 || h > 0) {
3888 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3889 int(w), int(h));
3890 return BAD_VALUE;
3891 }
3892
Vishnu Nairfa247b12020-02-11 08:58:26 -08003893 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3894 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003895 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003896 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003897 // check if buffer size is set for container layer.
3898 if (w > 0 || h > 0) {
3899 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3900 int(w), int(h));
3901 return BAD_VALUE;
3902 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003903 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3904 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003905 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003906 default:
3907 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003908 break;
3909 }
3910
Dan Stoza7d89d062015-04-30 13:29:25 -07003911 if (result != NO_ERROR) {
3912 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003913 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003914
Evan Roskya1f1e152019-01-24 16:17:46 -08003915 if (primaryDisplayOnly) {
3916 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003917 }
3918
Robert Carrb89ea9d2018-12-10 13:01:14 -08003919 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003920 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3921 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003922 if (result != NO_ERROR) {
3923 return result;
3924 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003925 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003926
3927 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003928 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003929}
3930
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003931std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3932 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003933
3934 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003935 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003936
Dan Stoza436ccf32018-06-21 12:10:12 -07003937 // Grab the state lock since we're accessing mCurrentState
3938 Mutex::Autolock lock(mStateLock);
3939
Cody Northropbc755282017-03-31 12:00:08 -06003940 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003941 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003942 while (matchFound) {
3943 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003944 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003945 if (layer->getName() == uniqueName) {
3946 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003947 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003948 }
3949 });
3950 }
3951
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003952 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003953 return uniqueName;
3954}
3955
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003956status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003957 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003958 LayerMetadata metadata, PixelFormat& format,
3959 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003960 sp<IGraphicBufferProducer>* gbp,
3961 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003962 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003963 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003964 case PIXEL_FORMAT_TRANSPARENT:
3965 case PIXEL_FORMAT_TRANSLUCENT:
3966 format = PIXEL_FORMAT_RGBA_8888;
3967 break;
3968 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003969 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003970 break;
3971 }
3972
chaviwb4c6e582019-08-16 14:35:07 -07003973 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003974 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003975 args.textureName = getNewTexture();
3976 {
3977 // Grab the SF state lock during this since it's the only safe way to access
3978 // RenderEngine when creating a BufferLayerConsumer
3979 // TODO: Check if this lock is still needed here
3980 Mutex::Autolock lock(mStateLock);
3981 layer = getFactory().createBufferQueueLayer(args);
3982 }
3983
Marissa Wallfd668622018-05-10 10:21:13 -07003984 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003985 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003986 *handle = layer->getHandle();
3987 *gbp = layer->getProducer();
3988 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003989 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003990
Marissa Wallfd668622018-05-10 10:21:13 -07003991 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003992 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003993}
3994
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003995status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003996 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003997 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003998 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003999 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004000 args.displayDevice = getDefaultDisplayDevice();
4001 args.textureName = getNewTexture();
4002 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07004003 if (outTransformHint) {
4004 *outTransformHint = layer->getTransformHint();
4005 }
Marissa Wall61c58622018-07-18 10:12:20 -07004006 *handle = layer->getHandle();
4007 *outLayer = layer;
4008
4009 return NO_ERROR;
4010}
4011
Vishnu Nairfa247b12020-02-11 08:58:26 -08004012status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4013 uint32_t h, uint32_t flags, LayerMetadata metadata,
4014 sp<IBinder>* handle, sp<Layer>* outLayer) {
4015 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004016 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004017 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004018 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004019}
4020
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004021status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004022 uint32_t w, uint32_t h, uint32_t flags,
4023 LayerMetadata metadata, sp<IBinder>* handle,
4024 sp<Layer>* outLayer) {
4025 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004026 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004027 *handle = (*outLayer)->getHandle();
4028 return NO_ERROR;
4029}
4030
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004031void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004032 mLayersPendingRemoval.add(layer);
4033 mLayersRemoved = true;
4034 setTransactionFlags(eTransactionNeeded);
4035}
4036
Robert Carr695d5282018-12-18 15:27:58 -08004037void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004038{
Robert Carr2e102c92018-10-23 12:11:15 -07004039 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004040 // If a layer has a parent, we allow it to out-live it's handle
4041 // with the idea that the parent holds a reference and will eventually
4042 // be cleaned up. However no one cleans up the top-level so we do so
4043 // here.
4044 if (layer->getParent() == nullptr) {
4045 mCurrentState.layersSortedByZ.remove(layer);
4046 }
4047 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004048
4049 auto it = mLayersByLocalBinderToken.begin();
4050 while (it != mLayersByLocalBinderToken.end()) {
4051 if (it->second == layer) {
4052 it = mLayersByLocalBinderToken.erase(it);
4053 } else {
4054 it++;
4055 }
4056 }
4057
Robert Carr695d5282018-12-18 15:27:58 -08004058 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004059}
4060
Mathias Agopianb60314a2012-04-10 22:09:54 -07004061// ---------------------------------------------------------------------------
4062
Andy McFadden13a082e2012-08-24 10:16:42 -07004063void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004064 const auto display = getDefaultDisplayDeviceLocked();
4065 if (!display) return;
4066
4067 const sp<IBinder> token = display->getDisplayToken().promote();
4068 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004069
Jesse Hall01e29052013-02-19 16:13:35 -08004070 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004071 Vector<ComposerState> state;
4072 Vector<DisplayState> displays;
4073 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004074 d.what = DisplayState::eDisplayProjectionChanged |
4075 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004076 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004077 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004078 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004079 d.frame.makeInvalid();
4080 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004081 d.width = 0;
4082 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004083 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004084 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4085 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004086
Dominik Laskowskie9774092018-12-11 10:04:24 -08004087 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004088
Dominik Laskowski83b88212018-12-11 13:34:06 -08004089 const nsecs_t vsyncPeriod = getVsyncPeriod();
4090 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004091
Brian Andersond0010582017-03-07 13:20:31 -08004092 // Use phase of 0 since phase is not known.
4093 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004094 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004095 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004096}
4097
4098void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004099 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004100 postMessageAsync(
4101 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004102}
4103
Ady Abraham27c70212019-06-11 10:52:26 -07004104void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4105 if (mHWCVsyncState != enabled) {
4106 getHwComposer().setVsyncEnabled(displayId, enabled);
4107 mHWCVsyncState = enabled;
4108 }
4109}
4110
Dominik Laskowskie9774092018-12-11 10:04:24 -08004111void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004112 if (display->isVirtual()) {
4113 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004114 return;
4115 }
4116
Dominik Laskowski075d3172018-05-24 15:50:06 -07004117 const auto displayId = display->getId();
4118 LOG_ALWAYS_FATAL_IF(!displayId);
4119
Dominik Laskowski34157762018-10-31 13:07:19 -07004120 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004121
4122 int currentMode = display->getPowerMode();
4123 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004124 return;
4125 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004126
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004127 display->setPowerMode(mode);
4128
Lloyd Pique4dccc412018-01-22 17:21:36 -08004129 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004130 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004131 }
4132
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004133 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004134 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004135 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004136 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004137 mScheduler->onScreenAcquired(mAppConnectionHandle);
4138 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004139 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004140
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004141 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004142 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004143 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004144
4145 struct sched_param param = {0};
4146 param.sched_priority = 1;
4147 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4148 ALOGW("Couldn't set SCHED_FIFO on display on");
4149 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004150 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004151 // Turn off the display
4152 struct sched_param param = {0};
4153 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4154 ALOGW("Couldn't set SCHED_OTHER on display off");
4155 }
4156
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004157 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004158 mScheduler->disableHardwareVsync(true);
4159 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004160 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004161
Ady Abraham27c70212019-06-11 10:52:26 -07004162 // Make sure HWVsync is disabled before turning off the display
4163 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4164
Dominik Laskowski075d3172018-05-24 15:50:06 -07004165 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004166 mVisibleRegionsDirty = true;
4167 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004168 } else if (mode == HWC_POWER_MODE_DOZE ||
4169 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004170 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004171 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004172 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004173 mScheduler->onScreenAcquired(mAppConnectionHandle);
4174 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004175 }
4176 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4177 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004178 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004179 mScheduler->disableHardwareVsync(true);
4180 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004181 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004182 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004183 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004184 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004185 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004186 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004187
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004188 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004189 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004190 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004191 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004192 }
4193
Dominik Laskowski34157762018-10-31 13:07:19 -07004194 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004195}
4196
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004197void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004198 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004199 const auto display = getDisplayDevice(displayToken);
4200 if (!display) {
4201 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4202 displayToken.get());
4203 } else if (display->isVirtual()) {
4204 ALOGW("Attempt to set power mode %d for virtual display", mode);
4205 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004206 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004207 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004208 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004209}
4210
4211// ---------------------------------------------------------------------------
4212
Dominik Laskowskic2867142019-01-21 11:33:38 -08004213status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4214 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004215 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004216
Mathias Agopianbd115332013-04-18 16:41:04 -07004217 IPCThreadState* ipc = IPCThreadState::self();
4218 const int pid = ipc->getCallingPid();
4219 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004220
Mathias Agopianbd115332013-04-18 16:41:04 -07004221 if ((uid != AID_SHELL) &&
4222 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004223 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4224 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004225 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004226 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004227 // (this would indicate SF is stuck, but we want to be able to
4228 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004229 status_t err = mStateLock.timedLock(s2ns(1));
4230 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004231 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004232 StringAppendF(&result,
4233 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4234 "(no locks held)\n",
4235 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004236 }
4237
Dominik Laskowskic2867142019-01-21 11:33:38 -08004238 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004239 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004240 {"--dispsync"s,
4241 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004242 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004243 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4244 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4245 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4246 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4247 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4248 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004249 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004250 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4251 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004252
Dominik Laskowskic2867142019-01-21 11:33:38 -08004253 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004254
Dominik Laskowski46470112019-08-02 13:13:11 -07004255 const auto it = dumpers.find(flag);
4256 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004257 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004258 } else if (!asProto) {
4259 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004260 }
4261
Mathias Agopian9795c422009-08-26 16:36:26 -07004262 if (locked) {
4263 mStateLock.unlock();
4264 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004265
Dominik Laskowski46470112019-08-02 13:13:11 -07004266 if (it == dumpers.end()) {
4267 const LayersProto layersProto = dumpProtoFromMainThread();
4268 if (asProto) {
4269 result.append(layersProto.SerializeAsString());
4270 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004271 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004272 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4273 result.append(LayerProtoParser::layerTreeToString(layerTree));
4274 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004275 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004276 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004277 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004278 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004279 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004280 return NO_ERROR;
4281}
4282
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004283status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4284 if (asProto && mTracing.isEnabled()) {
4285 mTracing.writeToFileAsync();
4286 }
4287
4288 return doDump(fd, DumpArgs(), asProto);
4289}
4290
Dominik Laskowskic2867142019-01-21 11:33:38 -08004291void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004292 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004293 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004294}
4295
Dominik Laskowskic2867142019-01-21 11:33:38 -08004296void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004297 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004298
Dominik Laskowskic2867142019-01-21 11:33:38 -08004299 if (args.size() > 1) {
4300 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004301 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004302 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004303 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004304 }
Robert Carr2047fae2016-11-28 14:09:09 -08004305 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004306 } else {
4307 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004308 }
4309}
4310
Dominik Laskowskic2867142019-01-21 11:33:38 -08004311void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004312 const bool clearAll = args.size() < 2;
4313 const auto name = clearAll ? String8() : String8(args[1]);
4314
Edgar Arriaga844fa672020-01-16 14:21:42 -08004315 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004316 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004317 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004318 }
Robert Carr2047fae2016-11-28 14:09:09 -08004319 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004320
Svetoslavd85084b2014-03-20 10:28:31 -07004321 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004322}
4323
Dominik Laskowskic2867142019-01-21 11:33:38 -08004324void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4325 mTimeStats->parseArgs(asProto, args, result);
4326}
4327
Jamie Gennis6547ff42013-07-16 20:12:42 -07004328// This should only be called from the main thread. Otherwise it would need
4329// the lock and should use mCurrentState rather than mDrawingState.
4330void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004331 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004332 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004333 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004334
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004335 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004336}
4337
Yiwei Zhang5434a782018-12-05 18:06:32 -08004338void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004339 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004340
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004341 if (isLayerTripleBufferingDisabled())
4342 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004343
Yiwei Zhang5434a782018-12-05 18:06:32 -08004344 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4345 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4346 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4347 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4348 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4349 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004350 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004351}
4352
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004353void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004354 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004355
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004356 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004357 result.append("\n");
4358
Ady Abraham9e16a482019-12-03 17:19:41 -08004359 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004360 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004361 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004362 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004363
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004364 HwcConfigIndexType defaultConfig;
4365 float minFps, maxFps;
4366 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004367 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004368 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004369 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004370 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004371 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4372 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004373
Ana Krulecc2870422019-01-29 19:00:58 -08004374 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004375}
4376
Yiwei Zhang5434a782018-12-05 18:06:32 -08004377void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4378 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004379 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4380 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004381 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004382 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004383 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004384 }
David Sodman4a36e932017-11-07 14:29:47 -08004385 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004386 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004387 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004388 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4389 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004390}
4391
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004392void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4393 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004394 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4395 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004396 for (const auto& segment : history) {
4397 if (!segment.usedThirdBuffer) {
4398 stats.twoBufferTime += segment.totalTime;
4399 }
4400 if (segment.occupancyAverage < 1.0f) {
4401 stats.doubleBufferedTime += segment.totalTime;
4402 } else if (segment.occupancyAverage < 2.0f) {
4403 stats.tripleBufferedTime += segment.totalTime;
4404 }
4405 ++stats.numSegments;
4406 stats.totalTime += segment.totalTime;
4407 }
4408}
4409
Yiwei Zhang5434a782018-12-05 18:06:32 -08004410void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4411 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004412
4413 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4414 const size_t count = currentLayers.size();
4415 for (size_t i=0 ; i<count ; i++) {
4416 currentLayers[i]->dumpFrameEvents(result);
4417 }
4418}
4419
Yiwei Zhang5434a782018-12-05 18:06:32 -08004420void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004421 result.append("Buffering stats:\n");
4422 result.append(" [Layer name] <Active time> <Two buffer> "
4423 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004424 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004425 typedef std::tuple<std::string, float, float, float> BufferTuple;
4426 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004427 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004428 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004429 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004430 if (stats.numSegments == 0) {
4431 continue;
4432 }
4433 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4434 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4435 stats.totalTime;
4436 float doubleBufferRatio = static_cast<float>(
4437 stats.doubleBufferedTime) / stats.totalTime;
4438 float tripleBufferRatio = static_cast<float>(
4439 stats.tripleBufferedTime) / stats.totalTime;
4440 sorted.insert({activeTime, {name, twoBufferRatio,
4441 doubleBufferRatio, tripleBufferRatio}});
4442 }
4443 for (const auto& sortedPair : sorted) {
4444 float activeTime = sortedPair.first;
4445 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004446 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4447 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004448 }
4449 result.append("\n");
4450}
4451
Yiwei Zhang5434a782018-12-05 18:06:32 -08004452void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004453 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004454 const auto displayId = display->getId();
4455 if (!displayId) {
4456 continue;
4457 }
4458 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004459 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004460 continue;
4461 }
4462
Yiwei Zhang5434a782018-12-05 18:06:32 -08004463 StringAppendF(&result,
4464 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4465 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004466 uint8_t port;
4467 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004468 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004469 result.append("no identification data\n");
4470 continue;
4471 }
4472
4473 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004474 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004475 continue;
4476 }
4477
4478 const auto edid = parseEdid(data);
4479 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004480 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004481 continue;
4482 }
4483
Yiwei Zhang5434a782018-12-05 18:06:32 -08004484 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004485 result.append(edid->displayName.data(), edid->displayName.length());
4486 result.append("\"\n");
4487 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004488}
4489
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004490void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4491 std::string& result) const {
4492 hwc2_display_t hwcDisplayId;
4493 uint8_t port;
4494 DisplayIdentificationData data;
4495
4496 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4497 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4498 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4499 }
4500}
4501
Yiwei Zhang5434a782018-12-05 18:06:32 -08004502void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004503 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004504 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4505 StringAppendF(&result, "DisplayColorSetting: %s\n",
4506 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004507
4508 // TODO: print out if wide-color mode is active or not
4509
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004510 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004511 const auto displayId = display->getId();
4512 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004513 continue;
4514 }
4515
Yiwei Zhang5434a782018-12-05 18:06:32 -08004516 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004517 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004518 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004519 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004520 }
4521
Lloyd Pique32cbe282018-10-19 13:09:22 -07004522 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004523 StringAppendF(&result, " Current color mode: %s (%d)\n",
4524 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004525 }
4526 result.append("\n");
4527}
4528
Alec Mouri5793c7d2020-03-10 19:55:50 -07004529LayersProto SurfaceFlinger::dumpDrawingStateProto(
4530 uint32_t traceFlags, const sp<const DisplayDevice>& displayDevice) const {
chaviw1d044282017-09-27 12:19:28 -07004531 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004532 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Alec Mouri5793c7d2020-03-10 19:55:50 -07004533 layer->writeToProto(layersProto, traceFlags, displayDevice);
chaviw08f3cb22020-01-13 13:17:21 -08004534 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004535
chaviw1d044282017-09-27 12:19:28 -07004536 return layersProto;
4537}
4538
Alec Mouri6b9e9912020-01-21 10:50:24 -08004539void SurfaceFlinger::dumpHwc(std::string& result) const {
4540 getHwComposer().dump(result);
4541}
4542
Vishnu Nair0f085c62019-08-30 08:49:12 -07004543void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4544 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4545 // it.
4546 LayerProto* rootProto = layersProto.add_layers();
4547 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4548 rootProto->set_id(offscreenRootLayerId);
4549 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004550 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004551
4552 for (Layer* offscreenLayer : mOffscreenLayers) {
4553 // Add layer as child of the fake root
4554 rootProto->add_children(offscreenLayer->sequence);
4555
4556 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004557 LayerProto* layerProto =
4558 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004559 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004560 }
4561}
4562
Vishnu Nair8406fd72019-07-30 11:29:31 -07004563LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4564 LayersProto layersProto;
Alec Mouri5793c7d2020-03-10 19:55:50 -07004565 postMessageSync(new LambdaMessage([&]() {
4566 const auto& displayDevice = getDefaultDisplayDeviceLocked();
4567 layersProto = dumpDrawingStateProto(traceFlags, displayDevice);
4568 }));
Vishnu Nair8406fd72019-07-30 11:29:31 -07004569 return layersProto;
4570}
4571
Vishnu Nair0f085c62019-08-30 08:49:12 -07004572void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4573 result.append("Offscreen Layers:\n");
4574 postMessageSync(new LambdaMessage([&]() {
4575 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004576 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004577 layer->dumpCallingUidPid(result);
4578 });
4579 }
4580 }));
4581}
4582
Dominik Laskowskic2867142019-01-21 11:33:38 -08004583void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4584 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004585 Colorizer colorizer(colorize);
4586
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004587 // figure out if we're stuck somewhere
4588 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004589 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004590 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4591
4592 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004593 * Dump library configuration.
4594 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004595
4596 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004597 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004598 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004599 appendSfConfigString(result);
4600 appendUiConfigString(result);
4601 appendGuiConfigString(result);
4602 result.append("\n");
4603
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004604 result.append("\nDisplay identification data:\n");
4605 dumpDisplayIdentificationData(result);
4606
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004607 result.append("\nWide-Color information:\n");
4608 dumpWideColorInfo(result);
4609
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004610 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004611 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004612 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004613 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004614 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004615
Andy McFadden41d67d72014-04-25 16:58:34 -07004616 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004617 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004618 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004619 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004620 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004621
Dan Stozab90cf072015-03-05 11:05:59 -08004622 dumpStaticScreenStats(result);
4623 result.append("\n");
4624
Alec Mouri40189b02019-03-05 15:07:54 -08004625 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4626 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4627 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004628
Dan Stozae77c7662016-05-13 11:37:28 -07004629 dumpBufferingStats(result);
4630
Andy McFadden4803b742012-09-24 19:07:20 -07004631 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004632 * Dump the visible layer list
4633 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004634 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004635 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004636 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4637 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004638 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004639
Chia-I Wu2f884132018-09-13 15:17:58 -07004640 {
Lloyd Pique207def92019-02-28 16:09:52 -08004641 StringAppendF(&result, "Composition layers\n");
4642 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004643 auto* compositionState = layer->getCompositionState();
4644 if (!compositionState) return;
4645
4646 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4647 layer->getDebugName() ? layer->getDebugName()
4648 : "<unknown>");
4649 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004650 });
4651 }
4652
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004653 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004654 * Dump Display state
4655 */
4656
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004657 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004658 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004659 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004660 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004661 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004662 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004663 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004664
4665 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004666 * Dump CompositionEngine state
4667 */
4668
4669 mCompositionEngine->dump(result);
4670
4671 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004672 * Dump SurfaceFlinger global state
4673 */
4674
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004675 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004676 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004677 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004678
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004679 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004680
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004681 DebugEGLImageTracker::getInstance()->dump(result);
4682
Dominik Laskowski075d3172018-05-24 15:50:06 -07004683 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004684 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4685 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004686 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4687 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004688 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004689 StringAppendF(&result,
4690 " transaction-flags : %08x\n"
4691 " gpu_to_cpu_unsupported : %d\n",
4692 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004693
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004694 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004695 displayId && getHwComposer().isConnected(*displayId)) {
4696 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004697 StringAppendF(&result,
4698 " refresh-rate : %f fps\n"
4699 " x-dpi : %f\n"
4700 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004701 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4702 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004703 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004704
Yiwei Zhang5434a782018-12-05 18:06:32 -08004705 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004706
Dan Stozae22aec72016-08-01 13:20:59 -07004707 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004708 * Tracing state
4709 */
4710 mTracing.dump(result);
4711 result.append("\n");
4712
4713 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004714 * HWC layer minidump
4715 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004716 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004717 const auto displayId = display->getId();
4718 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004719 continue;
4720 }
4721
Yiwei Zhang5434a782018-12-05 18:06:32 -08004722 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004723 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004724 const sp<DisplayDevice> displayDevice = display;
4725 mCurrentState.traverseInZOrder(
4726 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004727 result.append("\n");
4728 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004729
4730 /*
4731 * Dump HWComposer state
4732 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004733 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004734 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004735 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004736 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004737 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004738 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004739
4740 /*
4741 * Dump gralloc state
4742 */
4743 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4744 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004745
4746 /*
4747 * Dump VrFlinger state if in use.
4748 */
4749 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4750 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004751 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004752 result.append("\n");
4753 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004754
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004755 result.append(mTimeStats->miniDump());
4756 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004757}
4758
Chia-I Wu28f320b2018-05-03 11:02:56 -07004759void SurfaceFlinger::updateColorMatrixLocked() {
4760 mat4 colorMatrix;
4761 if (mGlobalSaturationFactor != 1.0f) {
4762 // Rec.709 luma coefficients
4763 float3 luminance{0.213f, 0.715f, 0.072f};
4764 luminance *= 1.0f - mGlobalSaturationFactor;
4765 mat4 saturationMatrix = mat4(
4766 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4767 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4768 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4769 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4770 );
4771 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4772 } else {
4773 colorMatrix = mClientColorMatrix * mDaltonizer();
4774 }
4775
4776 if (mCurrentState.colorMatrix != colorMatrix) {
4777 mCurrentState.colorMatrix = colorMatrix;
4778 mCurrentState.colorMatrixChanged = true;
4779 setTransactionFlags(eTransactionNeeded);
4780 }
4781}
4782
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004783status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004784#pragma clang diagnostic push
4785#pragma clang diagnostic error "-Wswitch-enum"
4786 switch (static_cast<ISurfaceComposerTag>(code)) {
4787 // These methods should at minimum make sure that the client requested
4788 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004789 case BOOT_FINISHED:
4790 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004791 case CREATE_DISPLAY:
4792 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004793 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004794 case GET_ANIMATION_FRAME_STATS:
4795 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004796 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004797 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004798 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004799 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4800 case SET_AUTO_LOW_LATENCY_MODE:
4801 case GET_GAME_CONTENT_TYPE_SUPPORT:
4802 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004803 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004804 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004805 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004806 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004807 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004808 case NOTIFY_POWER_HINT:
4809 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004810 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4811 IPCThreadState* ipc = IPCThreadState::self();
4812 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4813 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004814 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004815 }
Robert Carr1db73f62016-12-21 12:58:51 -08004816 return OK;
4817 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004818 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004819 IPCThreadState* ipc = IPCThreadState::self();
4820 const int pid = ipc->getCallingPid();
4821 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004822 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4823 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004824 return PERMISSION_DENIED;
4825 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004826 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004827 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004828 // Used by apps to hook Choreographer to SurfaceFlinger.
4829 case CREATE_DISPLAY_EVENT_CONNECTION:
4830 // The following calls are currently used by clients that do not
4831 // request necessary permissions. However, they do not expose any secret
4832 // information, so it is OK to pass them.
4833 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004834 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004835 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004836 case GET_PHYSICAL_DISPLAY_IDS:
4837 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004838 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004839 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004840 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004841 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004842 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004843 case GET_DISPLAY_STATS:
4844 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4845 // Calling setTransactionState is safe, because you need to have been
4846 // granted a reference to Client* and Handle* to do anything with it.
4847 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004848 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004849 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004850 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004851 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004852 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004853 // setFrameRate() is deliberately available for apps to call without any
4854 // special permissions.
4855 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004856 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4857 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004858 return OK;
4859 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004860 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004861 case CAPTURE_SCREEN:
4862 case ADD_REGION_SAMPLING_LISTENER:
4863 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004864 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004865 IPCThreadState* ipc = IPCThreadState::self();
4866 const int pid = ipc->getCallingPid();
4867 const int uid = ipc->getCallingUid();
4868 if ((uid != AID_GRAPHICS) &&
4869 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4870 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4871 return PERMISSION_DENIED;
4872 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004873 return OK;
4874 }
chaviw93df2ea2019-04-30 16:45:12 -07004875 case CAPTURE_SCREEN_BY_ID: {
4876 IPCThreadState* ipc = IPCThreadState::self();
4877 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004878 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004879 return OK;
4880 }
4881 return PERMISSION_DENIED;
4882 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004883 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004884
4885 // These codes are used for the IBinder protocol to either interrogate the recipient
4886 // side of the transaction for its canonical interface descriptor or to dump its state.
4887 // We let them pass by default.
4888 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4889 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4890 code == IBinder::SYSPROPS_TRANSACTION) {
4891 return OK;
4892 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004893 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004894 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004895 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004896 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4897 return OK;
4898 }
4899 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4900 return PERMISSION_DENIED;
4901#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004902}
4903
Ana Krulec13be8ad2018-08-21 02:43:56 +00004904status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4905 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004906 status_t credentialCheck = CheckTransactCodeCredentials(code);
4907 if (credentialCheck != OK) {
4908 return credentialCheck;
4909 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004910
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004911 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4912 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004913 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004914 IPCThreadState* ipc = IPCThreadState::self();
4915 const int uid = ipc->getCallingUid();
4916 if (CC_UNLIKELY(uid != AID_SYSTEM
4917 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004918 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004919 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004920 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004921 return PERMISSION_DENIED;
4922 }
4923 int n;
4924 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004925 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004926 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004927 return NO_ERROR;
4928 case 1002: // SHOW_UPDATES
4929 n = data.readInt32();
4930 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004931 invalidateHwcGeometry();
4932 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004933 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004934 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004935 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004936 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004937 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004938 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004939 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004940 setTransactionFlags(
4941 eTransactionNeeded|
4942 eDisplayTransactionNeeded|
4943 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004944 return NO_ERROR;
4945 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004946 case 1006:{ // send empty update
4947 signalRefresh();
4948 return NO_ERROR;
4949 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004950 case 1008: // toggle use of hw composer
4951 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004952 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004953 invalidateHwcGeometry();
4954 repaintEverything();
4955 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004956 case 1009: // toggle use of transform hint
4957 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004958 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004959 invalidateHwcGeometry();
4960 repaintEverything();
4961 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004962 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004963 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004964 reply->writeInt32(0);
4965 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004966 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004967 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004968 return NO_ERROR;
4969 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004970 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004971 if (!display) {
4972 return NAME_NOT_FOUND;
4973 }
4974
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004975 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004976 return NO_ERROR;
4977 }
4978 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004979 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004980 // daltonize
4981 n = data.readInt32();
4982 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004983 case 1:
4984 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4985 break;
4986 case 2:
4987 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4988 break;
4989 case 3:
4990 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4991 break;
4992 default:
4993 mDaltonizer.setType(ColorBlindnessType::None);
4994 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004995 }
4996 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004997 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004998 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004999 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005000 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005001
5002 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005003 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005004 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005005 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005006 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005007 // apply a color matrix
5008 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005009 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005010 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005011 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005012 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005013 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005014 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005015 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005016 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005017 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005018 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005019
5020 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5021 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005022 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005023 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5024 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5025 }
5026
Chia-I Wu28f320b2018-05-03 11:02:56 -07005027 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005028 return NO_ERROR;
5029 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005030 case 1016: { // Unused.
5031 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005032 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005033 case 1017: {
5034 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005035 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005036 return NO_ERROR;
5037 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005038 case 1018: { // Modify Choreographer's phase offset
5039 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005040 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005041 return NO_ERROR;
5042 }
5043 case 1019: { // Modify SurfaceFlinger's phase offset
5044 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005045 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005046 return NO_ERROR;
5047 }
Irvel468051e2016-06-13 16:44:44 -07005048 case 1020: { // Layer updates interceptor
5049 n = data.readInt32();
5050 if (n) {
5051 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005052 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005053 }
5054 else{
5055 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005056 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005057 }
5058 return NO_ERROR;
5059 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005060 case 1021: { // Disable HWC virtual displays
5061 n = data.readInt32();
5062 mUseHwcVirtualDisplays = !n;
5063 return NO_ERROR;
5064 }
Romain Guy0147a172017-06-01 13:53:56 -07005065 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005066 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005067 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005068
Chia-I Wu28f320b2018-05-03 11:02:56 -07005069 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005070 return NO_ERROR;
5071 }
Romain Guy54f154a2017-10-24 21:40:32 +01005072 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005073 int32_t colorMode;
5074
Chia-I Wu0d711262018-05-21 15:19:35 -07005075 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005076 if (data.readInt32(&colorMode) == NO_ERROR) {
5077 mForceColorMode = static_cast<ColorMode>(colorMode);
5078 }
Romain Guy54f154a2017-10-24 21:40:32 +01005079 invalidateHwcGeometry();
5080 repaintEverything();
5081 return NO_ERROR;
5082 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005083 // Deprecate, use 1030 to check whether the device is color managed.
5084 case 1024: {
5085 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005086 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005087 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005088 n = data.readInt32();
5089 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005090 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005091 Mutex::Autolock lock(mStateLock);
5092 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005093 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005094 reply->writeInt32(NO_ERROR);
5095 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005096 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005097 bool writeFile = false;
5098 {
5099 Mutex::Autolock lock(mStateLock);
5100 mTracingEnabledChanged = true;
5101 writeFile = mTracing.disable();
5102 }
5103
5104 if (writeFile) {
5105 reply->writeInt32(mTracing.writeToFile());
5106 } else {
5107 reply->writeInt32(NO_ERROR);
5108 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005109 }
5110 return NO_ERROR;
5111 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005112 case 1026: { // Get layer tracing status
5113 reply->writeBool(mTracing.isEnabled());
5114 return NO_ERROR;
5115 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005116 // Is a DisplayColorSetting supported?
5117 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005118 const auto display = getDefaultDisplayDevice();
5119 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005120 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005121 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005122
5123 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5124 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005125 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005126 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005127 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005128 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005129 reply->writeBool(true);
5130 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005131 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005132 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005133 break;
5134 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005135 reply->writeBool(
5136 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005137 break;
5138 }
5139 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005140 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005141 // Is VrFlinger active?
5142 case 1028: {
5143 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005144 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005145 return NO_ERROR;
5146 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005147 // Set buffer size for SF tracing (value in KB)
5148 case 1029: {
5149 n = data.readInt32();
5150 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5151 ALOGW("Invalid buffer size: %d KB", n);
5152 reply->writeInt32(BAD_VALUE);
5153 return BAD_VALUE;
5154 }
5155
5156 ALOGD("Updating trace buffer to %d KB", n);
5157 mTracing.setBufferSize(n * 1024);
5158 reply->writeInt32(NO_ERROR);
5159 return NO_ERROR;
5160 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005161 // Is device color managed?
5162 case 1030: {
5163 reply->writeBool(useColorManagement);
5164 return NO_ERROR;
5165 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005166 // Override default composition data space
5167 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5168 // && adb shell stop zygote && adb shell start zygote
5169 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5170 // adb shell stop zygote && adb shell start zygote
5171 case 1031: {
5172 Mutex::Autolock _l(mStateLock);
5173 n = data.readInt32();
5174 if (n) {
5175 n = data.readInt32();
5176 if (n) {
5177 Dataspace dataspace = static_cast<Dataspace>(n);
5178 if (!validateCompositionDataspace(dataspace)) {
5179 return BAD_VALUE;
5180 }
5181 mDefaultCompositionDataspace = dataspace;
5182 }
5183 n = data.readInt32();
5184 if (n) {
5185 Dataspace dataspace = static_cast<Dataspace>(n);
5186 if (!validateCompositionDataspace(dataspace)) {
5187 return BAD_VALUE;
5188 }
5189 mWideColorGamutCompositionDataspace = dataspace;
5190 }
5191 } else {
5192 // restore composition data space.
5193 mDefaultCompositionDataspace = defaultCompositionDataspace;
5194 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5195 }
5196 return NO_ERROR;
5197 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005198 // Set trace flags
5199 case 1033: {
5200 n = data.readUint32();
5201 ALOGD("Updating trace flags to 0x%x", n);
5202 mTracing.setTraceFlags(n);
5203 reply->writeInt32(NO_ERROR);
5204 return NO_ERROR;
5205 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005206 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005207 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005208 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005209 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005210 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005211 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005212 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005213 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005214 } else {
5215 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005216 }
5217 return NO_ERROR;
5218 }
Ady Abraham34392f72019-04-10 11:29:27 -07005219 case 1035: {
5220 n = data.readInt32();
5221 mDebugDisplayConfigSetByBackdoor = false;
5222 if (n >= 0) {
5223 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005224 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005225 if (result != NO_ERROR) {
5226 return result;
5227 }
5228 mDebugDisplayConfigSetByBackdoor = true;
5229 }
5230 return NO_ERROR;
5231 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005232 }
5233 }
5234 return err;
5235}
5236
Steven Thomas6d8110b2017-08-31 18:24:21 -07005237void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005238 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005239 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005240}
5241
Ana Krulec7d1d6832018-12-27 11:10:09 -08005242void SurfaceFlinger::repaintEverythingForHWC() {
5243 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005244 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005245 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005246}
5247
Ady Abrahama09852a2020-02-20 14:23:42 -08005248void SurfaceFlinger::kernelTimerChanged(bool expired) {
5249 static bool updateOverlay =
5250 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5251 if (!updateOverlay || !mRefreshRateOverlay) return;
5252
5253 // Update the overlay on the main thread to avoid race conditions with
5254 // mRefreshRateConfigs->getCurrentRefreshRate()
5255 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5256 if (mRefreshRateOverlay) {
5257 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5258 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005259 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005260 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5261 if (mDesiredActiveConfigChanged) {
5262 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5263 mDesiredActiveConfig.configId);
5264 }
5265
5266 return mRefreshRateConfigs->getCurrentRefreshRate();
5267 }();
5268 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5269
5270 if (current != min) {
5271 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5272 mEventQueue->invalidate();
5273 }
5274 }
5275 }));
5276}
5277
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005278// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5279class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005280public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005281 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5282 ~WindowDisconnector() {
5283 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005284 }
5285
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005286private:
5287 ANativeWindow* mWindow;
5288 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005289};
5290
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005291status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005292 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005293 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5294 const Rect& sourceCrop, uint32_t reqWidth,
5295 uint32_t reqHeight, bool useIdentityTransform,
5296 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005297 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005298
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005299 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005300
Dominik Laskowski718f9602019-11-09 20:01:35 -08005301 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5302 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5303 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5304 renderAreaRotation = ui::Transform::ROT_0;
5305 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005306
Chia-I Wu20261cb2018-08-23 12:55:44 -07005307 sp<DisplayDevice> display;
5308 {
5309 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005310
Chia-I Wu20261cb2018-08-23 12:55:44 -07005311 display = getDisplayDeviceLocked(displayToken);
5312 if (!display) return BAD_VALUE;
5313
Chia-I Wucb023152018-08-28 12:57:23 -07005314 // set the requested width/height to the logical display viewport size
5315 // by default
5316 if (reqWidth == 0 || reqHeight == 0) {
5317 reqWidth = uint32_t(display->getViewport().width());
5318 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005319 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005320 }
5321
Peiyong Lin0e003c92018-09-17 11:09:51 -07005322 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005323 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005324
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005325 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5326 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005327 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005328 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005329}
5330
chaviw93df2ea2019-04-30 16:45:12 -07005331static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5332 switch (colorMode) {
5333 case ColorMode::DISPLAY_P3:
5334 case ColorMode::BT2100_PQ:
5335 case ColorMode::BT2100_HLG:
5336 case ColorMode::DISPLAY_BT2020:
5337 return Dataspace::DISPLAY_P3;
5338 default:
5339 return Dataspace::V0_SRGB;
5340 }
5341}
5342
5343const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5344 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5345 if (displayToken) {
5346 return getDisplayDeviceLocked(displayToken);
5347 }
5348 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5349 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005350 return getDisplayByLayerStack(displayOrLayerStack);
5351}
5352
5353const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005354 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005355 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005356 return display;
5357 }
5358 }
5359 return nullptr;
5360}
5361
5362status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5363 sp<GraphicBuffer>* outBuffer) {
5364 sp<DisplayDevice> display;
5365 uint32_t width;
5366 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005367 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005368 {
5369 Mutex::Autolock _l(mStateLock);
5370 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5371 if (!display) {
5372 return BAD_VALUE;
5373 }
5374
5375 width = uint32_t(display->getViewport().width());
5376 height = uint32_t(display->getViewport().height());
5377
Dominik Laskowski718f9602019-11-09 20:01:35 -08005378 const auto orientation = display->getOrientation();
5379 captureOrientation = ui::Transform::toRotationFlags(orientation);
5380
5381 switch (captureOrientation) {
5382 case ui::Transform::ROT_90:
5383 captureOrientation = ui::Transform::ROT_270;
5384 break;
5385
5386 case ui::Transform::ROT_270:
5387 captureOrientation = ui::Transform::ROT_90;
5388 break;
5389
5390 case ui::Transform::ROT_INVALID:
5391 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5392 captureOrientation = ui::Transform::ROT_0;
5393 break;
5394
5395 default:
5396 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005397 }
chaviw93df2ea2019-04-30 16:45:12 -07005398 *outDataspace =
5399 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5400 }
5401
5402 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5403 false /* captureSecureLayers */);
5404
5405 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5406 std::placeholders::_1);
5407 bool ignored = false;
5408 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5409 false /* useIdentityTransform */,
5410 ignored /* outCapturedSecureLayers */);
5411}
5412
Robert Carr866455f2019-04-02 16:28:26 -07005413status_t SurfaceFlinger::captureLayers(
5414 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5415 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5416 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5417 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005418 ATRACE_CALL();
5419
5420 class LayerRenderArea : public RenderArea {
5421 public:
Robert Carr578038f2018-03-09 12:25:24 -08005422 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005423 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005424 bool childrenOnly, const Rect& displayViewport)
5425 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005426 mLayer(layer),
5427 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005428 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005429 mFlinger(flinger),
5430 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005431 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005432 Rect getBounds() const override {
5433 const Layer::State& layerState(mLayer->getDrawingState());
5434 return mLayer->getBufferSize(layerState);
5435 }
Marissa Wall61c58622018-07-18 10:12:20 -07005436 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005437 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005438 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005439 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005440 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005441 }
chaviwa76b2712017-09-20 12:02:26 -07005442 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005443 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005444 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005445 Rect getSourceCrop() const override {
5446 if (mCrop.isEmpty()) {
5447 return getBounds();
5448 } else {
5449 return mCrop;
5450 }
5451 }
Robert Carr578038f2018-03-09 12:25:24 -08005452 class ReparentForDrawing {
5453 public:
5454 const sp<Layer>& oldParent;
5455 const sp<Layer>& newParent;
5456
Vishnu Nair4351ad52019-02-11 14:13:02 -08005457 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5458 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005459 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005460 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005461 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5462 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005463 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005464 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005465 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005466 };
5467
5468 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005469 const Rect sourceCrop = getSourceCrop();
5470 // no need to check rotation because there is none
5471 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5472 sourceCrop.height() != getReqHeight();
5473
Robert Carr578038f2018-03-09 12:25:24 -08005474 if (!mChildrenOnly) {
5475 mTransform = mLayer->getTransform().inverse();
5476 drawLayers();
5477 } else {
5478 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005479 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5480 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005481 // In the "childrenOnly" case we reparent the children to a screenshot
5482 // layer which has no properties set and which does not draw.
5483 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005484 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5485 "Screenshot Parent"s, w, h, 0,
5486 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005487
Vishnu Nair4351ad52019-02-11 14:13:02 -08005488 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005489 drawLayers();
5490 }
5491 }
chaviwa76b2712017-09-20 12:02:26 -07005492
chaviwa76b2712017-09-20 12:02:26 -07005493 private:
chaviw7206d492017-11-10 16:16:12 -08005494 const sp<Layer> mLayer;
5495 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005496
Peiyong Linefefaac2018-08-17 12:27:51 -07005497 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005498 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005499
5500 SurfaceFlinger* mFlinger;
5501 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005502 };
5503
Robert Carrc0df3122019-04-11 13:18:21 -07005504 int reqWidth = 0;
5505 int reqHeight = 0;
5506 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005507 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005508 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005509 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005510 {
5511 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005512
Robert Carrc0df3122019-04-11 13:18:21 -07005513 parent = fromHandle(layerHandleBinder);
5514 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5515 ALOGE("captureLayers called with an invalid or removed parent");
5516 return NAME_NOT_FOUND;
5517 }
5518
5519 const int uid = IPCThreadState::self()->getCallingUid();
5520 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5521 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5522 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5523 return PERMISSION_DENIED;
5524 }
5525
Vishnu Nairefc42e22019-12-03 17:36:12 -08005526 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005527 if (sourceCrop.width() <= 0) {
5528 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005529 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005530 }
5531
5532 if (sourceCrop.height() <= 0) {
5533 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005534 crop.bottom = parentSourceBounds.getHeight();
5535 }
5536
5537 if (crop.isEmpty() || frameScale <= 0.0f) {
5538 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5539 // crop was not specified, or an invalid frame scale was provided.
5540 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005541 }
5542 reqWidth = crop.width() * frameScale;
5543 reqHeight = crop.height() * frameScale;
5544
5545 for (const auto& handle : excludeHandles) {
5546 sp<Layer> excludeLayer = fromHandle(handle);
5547 if (excludeLayer != nullptr) {
5548 excludeLayers.emplace(excludeLayer);
5549 } else {
5550 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5551 return NAME_NOT_FOUND;
5552 }
5553 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005554
5555 auto display = getDisplayByLayerStack(parent->getLayerStack());
5556 if (!display) {
5557 return BAD_VALUE;
5558 }
5559
5560 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005561 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005562
Chia-I Wu20261cb2018-08-23 12:55:44 -07005563 // really small crop or frameScale
5564 if (reqWidth <= 0) {
5565 reqWidth = 1;
5566 }
5567 if (reqHeight <= 0) {
5568 reqHeight = 1;
5569 }
5570
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005571 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5572 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005573 auto traverseLayers = [parent, childrenOnly,
5574 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005575 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5576 if (!layer->isVisible()) {
5577 return;
Robert Carr578038f2018-03-09 12:25:24 -08005578 } else if (childrenOnly && layer == parent.get()) {
5579 return;
chaviwa76b2712017-09-20 12:02:26 -07005580 }
Robert Carr866455f2019-04-02 16:28:26 -07005581
5582 sp<Layer> p = layer;
5583 while (p != nullptr) {
5584 if (excludeLayers.count(p) != 0) {
5585 return;
5586 }
5587 p = p->getParent();
5588 }
5589
chaviwa76b2712017-09-20 12:02:26 -07005590 visitor(layer);
5591 });
5592 };
Robert Carr108b2c72019-04-02 16:32:58 -07005593
5594 bool outCapturedSecureLayers = false;
5595 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5596 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005597}
5598
5599status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5600 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005601 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005602 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005603 bool useIdentityTransform,
5604 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005605 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005606
Peiyong Lin0e003c92018-09-17 11:09:51 -07005607 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005608 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5609 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005610 *outBuffer =
5611 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5612 static_cast<android_pixel_format>(reqPixelFormat), 1,
5613 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005614
Robert Carr108b2c72019-04-02 16:32:58 -07005615 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5616 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005617}
5618
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005619status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5620 TraverseLayersFunction traverseLayers,
5621 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005622 bool useIdentityTransform,
5623 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005624 // This mutex protects syncFd and captureResult for communication of the return values from the
5625 // main thread back to this Binder thread
5626 std::mutex captureMutex;
5627 std::condition_variable captureCondition;
5628 std::unique_lock<std::mutex> captureLock(captureMutex);
5629 int syncFd = -1;
5630 std::optional<status_t> captureResult;
5631
Robert Carr03480e22018-01-04 16:02:06 -08005632 const int uid = IPCThreadState::self()->getCallingUid();
5633 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5634
Dominik Laskowski8c001672018-05-30 16:52:06 -07005635 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005636 // If there is a refresh pending, bug out early and tell the binder thread to try again
5637 // after the refresh.
5638 if (mRefreshPending) {
5639 ATRACE_NAME("Skipping screenshot for now");
5640 std::unique_lock<std::mutex> captureLock(captureMutex);
5641 captureResult = std::make_optional<status_t>(EAGAIN);
5642 captureCondition.notify_one();
5643 return;
5644 }
5645
5646 status_t result = NO_ERROR;
5647 int fd = -1;
5648 {
5649 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005650 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005651 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005652 useIdentityTransform, forSystem, &fd,
5653 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005654 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005655 }
5656
5657 {
5658 std::unique_lock<std::mutex> captureLock(captureMutex);
5659 syncFd = fd;
5660 captureResult = std::make_optional<status_t>(result);
5661 captureCondition.notify_one();
5662 }
5663 });
5664
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005665 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005666 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005667 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005668 while (*captureResult == EAGAIN) {
5669 captureResult.reset();
5670 result = postMessageAsync(message);
5671 if (result != NO_ERROR) {
5672 return result;
5673 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005674 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005675 }
5676 result = *captureResult;
5677 }
5678
5679 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005680 sync_wait(syncFd, -1);
5681 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005682 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005683
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005684 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005685}
5686
chaviwa76b2712017-09-20 12:02:26 -07005687void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005688 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005689 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5690 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005691 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005692
chaviwa76b2712017-09-20 12:02:26 -07005693 const auto reqWidth = renderArea.getReqWidth();
5694 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005695 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005696 const auto transform = renderArea.getTransform();
5697 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005698 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005699
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005700 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005701 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005702
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005703 // assume that bounds are never offset, and that they are the same as the
5704 // buffer bounds.
5705 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005706 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005707 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005708
5709 // Now take into account the rotation flag. We append a transform that
5710 // rotates the layer stack about the origin, then translate by buffer
5711 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005712 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005713 int displacementX = 0;
5714 int displacementY = 0;
5715 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5716 switch (rotation) {
5717 case ui::Transform::ROT_90:
5718 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005719 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005720 break;
5721 case ui::Transform::ROT_180:
5722 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005723 displacementY = renderArea.getBounds().getWidth();
5724 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005725 break;
5726 case ui::Transform::ROT_270:
5727 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005728 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005729 break;
5730 default:
5731 break;
5732 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005733
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005734 // We need to transform the clipping window into the right spot.
5735 // First, rotate the clipping rectangle by the rotation hint to get the
5736 // right orientation
5737 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5738 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5739 const vec4 rotClipTL = rotMatrix * clipTL;
5740 const vec4 rotClipBR = rotMatrix * clipBR;
5741 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5742 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5743 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5744 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5745
5746 // Now reposition the clipping rectangle with the displacement vector
5747 // computed above.
5748 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005749 clientCompositionDisplay.clip =
5750 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5751 newClipRight + displacementX, newClipBottom + displacementY);
5752
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005753 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005754 clientCompositionDisplay.globalTransform =
5755 clipTransform * clientCompositionDisplay.globalTransform;
5756
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005757 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5758 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005759
chaviw50da5042018-04-09 13:49:37 -07005760 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005761
Vishnu Nair9b079a22020-01-21 14:36:08 -08005762 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005763 fillLayer.source.buffer.buffer = nullptr;
5764 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5765 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5766 fillLayer.alpha = half(alpha);
5767 clientCompositionLayers.push_back(fillLayer);
5768
5769 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005770 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005771 const bool supportProtectedContent = false;
5772 Region clip(renderArea.getBounds());
5773 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5774 clip,
5775 useIdentityTransform,
5776 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5777 renderArea.isSecure(),
5778 supportProtectedContent,
5779 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005780 displayViewport,
5781 clientCompositionDisplay.outputDataspace,
5782 true, /* realContentIsVisible */
5783 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005784 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005785 std::vector<compositionengine::LayerFE::LayerSettings> results =
5786 layer->prepareClientCompositionList(targetSettings);
5787 clientCompositionLayers.insert(clientCompositionLayers.end(),
5788 std::make_move_iterator(results.begin()),
5789 std::make_move_iterator(results.end()));
5790 results.clear();
5791
chaviwa76b2712017-09-20 12:02:26 -07005792 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005793
Vishnu Nair9b079a22020-01-21 14:36:08 -08005794 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5795 clientCompositionLayers.reserve(clientCompositionLayers.size());
5796 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5797 std::back_inserter(clientCompositionLayerPointers),
5798 [](compositionengine::LayerFE::LayerSettings& settings)
5799 -> renderengine::LayerSettings* { return &settings; });
5800
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005801 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005802 // Use an empty fence for the buffer fence, since we just created the buffer so
5803 // there is no need for synchronization with the GPU.
5804 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005805 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005806 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005807 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005808 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005809
5810 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005811}
5812
chaviwa76b2712017-09-20 12:02:26 -07005813status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5814 TraverseLayersFunction traverseLayers,
5815 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005816 bool useIdentityTransform, bool forSystem,
5817 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005818 ATRACE_CALL();
5819
chaviwa76b2712017-09-20 12:02:26 -07005820 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005821 outCapturedSecureLayers =
5822 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005823 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005824
Robert Carr03480e22018-01-04 16:02:06 -08005825 // We allow the system server to take screenshots of secure layers for
5826 // use in situations like the Screen-rotation animation and place
5827 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005828 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005829 ALOGW("FB is protected: PERMISSION_DENIED");
5830 return PERMISSION_DENIED;
5831 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005832 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005833 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005834}
5835
chaviw95ef3c42019-02-14 10:55:09 -08005836void SurfaceFlinger::setInputWindowsFinished() {
5837 Mutex::Autolock _l(mStateLock);
5838
5839 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005840
chaviw95ef3c42019-02-14 10:55:09 -08005841 mTransactionCV.broadcast();
5842}
chaviw5f21a5e2019-02-14 10:00:34 -08005843
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005844// ---------------------------------------------------------------------------
5845
Edgar Arriaga844fa672020-01-16 14:21:42 -08005846void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5847 layersSortedByZ.traverse(visitor);
5848}
5849
Dan Stoza412903f2017-04-27 13:42:17 -07005850void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5851 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005852}
5853
Dan Stoza412903f2017-04-27 13:42:17 -07005854void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5855 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005856}
5857
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005858void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005859 const LayerVector::Visitor& visitor) {
5860 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005861 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005862 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005863 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005864 continue;
5865 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005866 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005867 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005868 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005869 return;
5870 }
chaviwa76b2712017-09-20 12:02:26 -07005871 if (!layer->isVisible()) {
5872 return;
5873 }
5874 visitor(layer);
5875 });
5876 }
5877}
5878
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005879status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5880 HwcConfigIndexType defaultConfig,
5881 float minRefreshRate,
5882 float maxRefreshRate) {
5883 Mutex::Autolock lock(mStateLock);
5884
Dominik Laskowski22488f62019-03-28 09:53:04 -07005885 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005886 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5887 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5888 // it should go thru setDesiredActiveConfig, similar to primary display.
5889 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5890 const auto displayId = display->getId();
5891 LOG_ALWAYS_FATAL_IF(!displayId);
5892
5893 HWC2::VsyncPeriodChangeConstraints constraints;
5894 constraints.desiredTimeNanos = systemTime();
5895 constraints.seamlessRequired = false;
5896
5897 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005898 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5899 constraints, &timeline) < 0) {
5900 return BAD_VALUE;
5901 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005902 if (timeline.refreshRequired) {
5903 repaintEverythingForHWC();
5904 }
5905
Ady Abrahamdfa37362020-01-21 18:02:39 -08005906 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005907 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005908 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5909 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005910 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005911 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005912 }
5913
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005914 if (mDebugDisplayConfigSetByBackdoor) {
5915 // ignore this request as config is overridden by backdoor
5916 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005917 }
5918
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005919 bool policyChanged;
5920 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5921 &policyChanged) < 0) {
5922 return BAD_VALUE;
5923 }
5924 if (!policyChanged) {
5925 return NO_ERROR;
5926 }
5927
5928 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5929 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005930
5931 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5932 // that listeners that care about a change in allowed configs can get the notification.
5933 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005934 const nsecs_t vsyncPeriod =
5935 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005936 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005937 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005938
Ana Krulec3f6a2062020-01-23 15:48:01 -08005939 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005940 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005941 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5942 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5943 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5944 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5945 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5946
5947 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5948 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5949 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005950 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005951 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005952 }
5953
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005954 return NO_ERROR;
5955}
5956
Ana Krulec0782b882019-10-15 17:34:54 -07005957status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005958 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005959 float maxRefreshRate) {
5960 ATRACE_CALL();
5961
5962 if (!displayToken) {
5963 return BAD_VALUE;
5964 }
5965
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005966 status_t result = NO_ERROR;
5967
Ana Krulec234bb162019-11-10 22:55:55 +01005968 postMessageSync(new LambdaMessage([&]() {
5969 const auto display = getDisplayDeviceLocked(displayToken);
5970 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005971 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005972 ALOGE("Attempt to set desired display configs for invalid display token %p",
5973 displayToken.get());
5974 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005975 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005976 ALOGW("Attempt to set desired display configs for virtual display");
5977 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005978 result =
5979 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5980 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005981 }
5982 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005983
5984 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005985}
5986
5987status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005988 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005989 float* outMinRefreshRate,
5990 float* outMaxRefreshRate) {
5991 ATRACE_CALL();
5992
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005993 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005994 return BAD_VALUE;
5995 }
5996
5997 Mutex::Autolock lock(mStateLock);
5998 const auto display = getDisplayDeviceLocked(displayToken);
5999 if (!display) {
6000 return NAME_NOT_FOUND;
6001 }
6002
6003 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006004 HwcConfigIndexType defaultConfig;
6005 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
6006 *outDefaultConfig = defaultConfig.value();
6007 return NO_ERROR;
6008 } else if (display->isVirtual()) {
6009 return BAD_VALUE;
6010 } else {
6011 const auto displayId = display->getId();
6012 if (!displayId) {
6013 return BAD_VALUE;
6014 }
6015 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6016 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6017 *outMinRefreshRate = 1e9f / vsyncPeriod;
6018 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6019 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006020 }
Ana Krulec0782b882019-10-15 17:34:54 -07006021}
6022
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006023void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006024 mFlinger->setInputWindowsFinished();
6025}
6026
Robert Carrc0df3122019-04-11 13:18:21 -07006027sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006028 BBinder* b = nullptr;
6029 if (handle) {
6030 b = handle->localBinder();
6031 }
Robert Carrc0df3122019-04-11 13:18:21 -07006032 if (b == nullptr) {
6033 return nullptr;
6034 }
6035 auto it = mLayersByLocalBinderToken.find(b);
6036 if (it != mLayersByLocalBinderToken.end()) {
6037 return it->second.promote();
6038 }
6039 return nullptr;
6040}
6041
Dominik Laskowski75848362019-11-11 17:57:20 -08006042void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006043 mNumLayers++;
6044 mScheduler->registerLayer(layer);
6045}
6046
6047void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6048 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006049 removeFromOffscreenLayers(layer);
6050}
6051
6052// WARNING: ONLY CALL THIS FROM LAYER DTOR
6053// Here we add children in the current state to offscreen layers and remove the
6054// layer itself from the offscreen layer list. Since
6055// this is the dtor, it is safe to access the current state. This keeps us
6056// from dangling children layers such that they are not reachable from the
6057// Drawing state nor the offscreen layer list
6058// See b/141111965
6059void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6060 for (auto& child : layer->getCurrentChildren()) {
6061 mOffscreenLayers.emplace(child.get());
6062 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006063 mOffscreenLayers.erase(layer);
6064}
6065
Alec Mouri4545a8a2019-08-08 20:05:32 -07006066void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6067 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6068}
6069
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006070status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6071 float lightPosY, float lightPosZ,
6072 float lightRadius) {
6073 Mutex::Autolock _l(mStateLock);
6074 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6075 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6076 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6077 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6078 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6079
6080 // these values are overridden when calculating the shadow settings for a layer.
6081 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6082 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006083 return NO_ERROR;
6084}
6085
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006086const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6087 const {
6088 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6089 // on the work to remove the table in that bug rather than adding more to
6090 // it.
6091 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6092 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6093 // supported, and exposed via the
6094 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6095 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6096 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6097 };
6098 return genericLayerMetadataKeyMap;
6099}
6100
Steven Thomas62a4cf82020-01-31 12:04:03 -08006101status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6102 int8_t compatibility) {
6103 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6104 return BAD_VALUE;
6105 }
6106
Ady Abraham60e42ea2020-03-09 19:17:31 -07006107 postMessageAsync(new LambdaMessage([=]() NO_THREAD_SAFETY_ANALYSIS {
6108 Mutex::Autolock lock(mStateLock);
6109 if (authenticateSurfaceTextureLocked(surface)) {
6110 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6111 if (layer->setFrameRate(
6112 Layer::FrameRate(frameRate,
6113 Layer::FrameRate::convertCompatibility(compatibility)))) {
6114 setTransactionFlags(eTraversalNeeded);
6115 }
6116 } else {
6117 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6118 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006119 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006120 return NO_ERROR;
6121 }));
6122
Steven Thomas62a4cf82020-01-31 12:04:03 -08006123 return NO_ERROR;
6124}
6125
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006126} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006127
Mathias Agopian3f844832013-08-07 21:24:32 -07006128#if defined(__gl_h_)
6129#error "don't include gl/gl.h in this file"
6130#endif
6131
6132#if defined(__gl2_h_)
6133#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006134#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006135
6136// TODO(b/129481165): remove the #pragma below and fix conversion issues
6137#pragma clang diagnostic pop // ignored "-Wconversion"