blob: bbb07a8c650b7fa4b888cf8a5cc982ed85344f94 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri989ddbe2020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri989ddbe2020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri989ddbe2020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800104#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
111#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700114#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/EventControlThread.h"
116#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700117#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700118#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700119#include "Scheduler/Scheduler.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800120#include "StartPropertySetThread.h"
121#include "SurfaceFlingerProperties.h"
122#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800123#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700124#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800125#include "android-base/stringprintf.h"
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Steven Thomasb02664d2017-07-26 18:48:28 -0700143namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700144
145#pragma clang diagnostic push
146#pragma clang diagnostic error "-Wswitch-enum"
147
148bool isWideColorMode(const ColorMode colorMode) {
149 switch (colorMode) {
150 case ColorMode::DISPLAY_P3:
151 case ColorMode::ADOBE_RGB:
152 case ColorMode::DCI_P3:
153 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700154 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700155 case ColorMode::BT2100_PQ:
156 case ColorMode::BT2100_HLG:
157 return true;
158 case ColorMode::NATIVE:
159 case ColorMode::STANDARD_BT601_625:
160 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
161 case ColorMode::STANDARD_BT601_525:
162 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
163 case ColorMode::STANDARD_BT709:
164 case ColorMode::SRGB:
165 return false;
166 }
167 return false;
168}
169
170#pragma clang diagnostic pop
171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172class ConditionalLock {
173public:
174 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
175 if (lock) {
176 mMutex.lock();
177 }
178 }
179 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
180private:
181 Mutex& mMutex;
182 bool mLocked;
183};
Peiyong Linfca547f2018-07-09 13:03:33 -0700184
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800185// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
186constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
187
188float getDensityFromProperty(const char* property, bool required) {
189 char value[PROPERTY_VALUE_MAX];
190 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
191 if (!density && required) {
192 ALOGE("%s must be defined as a build property", property);
193 return FALLBACK_DENSITY;
194 }
195 return density / 160.f;
196}
197
Peiyong Lin9d846a52018-11-05 13:18:20 -0800198// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
199bool validateCompositionDataspace(Dataspace dataspace) {
200 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
201}
202
Steven Thomasb02664d2017-07-26 18:48:28 -0700203} // namespace anonymous
204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205// ---------------------------------------------------------------------------
206
Mathias Agopian99b49842011-06-27 16:05:52 -0700207const String16 sHardwareTest("android.permission.HARDWARE_TEST");
208const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
209const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
210const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800211const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700212
213// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700214int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700215bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800217bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800218bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800219int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100220uint32_t SurfaceFlinger::maxGraphicsWidth;
221uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600222bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800223ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700224bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700225bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700226Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
227ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
228Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
229ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800230bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700231
Kalle Raitaa099a242017-01-11 11:17:29 -0800232std::string getHwcServiceName() {
233 char value[PROPERTY_VALUE_MAX] = {};
234 property_get("debug.sf.hwc_service_name", value, "default");
235 ALOGI("Using HWComposer service: '%s'", value);
236 return std::string(value);
237}
238
239bool useTrebleTestingOverride() {
240 char value[PROPERTY_VALUE_MAX] = {};
241 property_get("debug.sf.treble_testing_override", value, "false");
242 ALOGI("Treble testing override: '%s'", value);
243 return std::string(value) == "true";
244}
245
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800246std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
247 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800248 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700249 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800250 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700251 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800252 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700253 return std::string("Enhanced");
254 default:
255 return std::string("Unknown ") +
256 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800258}
259
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700260SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800261
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700262SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
263 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700264 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700265 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700266 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700267 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700268 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800269 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
270 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800271
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700272SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800273 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800274
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700278
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900279 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700280
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900281 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800282
Steven Thomas050b2c82017-03-06 11:45:16 -0800283 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800287
Brian Lindahla13f2d52020-03-05 11:54:17 +0100288 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
289 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 mDefaultCompositionDataspace =
296 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700297 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
298 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 defaultCompositionDataspace = mDefaultCompositionDataspace;
300 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
301 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
302 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
303 wideColorGamutCompositionPixelFormat =
304 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700305
Yichi Chenda901bf2019-06-28 14:58:27 +0800306 mColorSpaceAgnosticDataspace =
307 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
308
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800310
Dominik Laskowski718f9602019-11-09 20:01:35 -0800311 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
312 switch (primary_display_orientation(Values::ORIENTATION_0)) {
313 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800314 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800315 case Values::ORIENTATION_90:
316 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800317 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800318 case Values::ORIENTATION_180:
319 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800320 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800321 case Values::ORIENTATION_270:
322 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800323 break;
324 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800325 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800326
Sundong Ahn85131bd2019-02-18 15:51:53 +0900327 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800328
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800329 // debugging stuff...
330 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700331
Mathias Agopianb4b17302013-03-20 18:36:41 -0700332 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700333 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700334
Alec Mouri989ddbe2020-02-06 09:26:19 -0800335 property_get("ro.build.type", value, "user");
336 mIsUserBuild = strcmp(value, "user") == 0;
337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 property_get("debug.sf.showupdates", value, "0");
339 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700340
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700341 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000342
343 // DDMS debugging deprecated (b/120782499)
344 property_get("debug.sf.ddms", value, "0");
345 int debugDdms = atoi(value);
346 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700347
348 property_get("debug.sf.disable_backpressure", value, "0");
349 mPropagateBackpressure = !atoi(value);
350 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700351
Ady Abrahamadb9a992019-09-19 21:21:55 +0000352 property_get("debug.sf.enable_gl_backpressure", value, "0");
353 mPropagateBackpressureClientComposition = atoi(value);
354 ALOGI_IF(mPropagateBackpressureClientComposition,
355 "Enabling backpressure propagation for Client Composition");
356
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800357 property_get("debug.sf.enable_hwc_vds", value, "0");
358 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800359 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800360
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800361 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800362 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800363 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700364
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800365 property_get("ro.surface_flinger.supports_background_blur", value, "0");
366 bool supportsBlurs = atoi(value);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800367 property_get("debug.sf.disable_blurs", value, "0");
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800368 bool disableBlurs = atoi(value);
369 mEnableBlurs = supportsBlurs && !disableBlurs;
370 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
371 disableBlurs);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800372 property_get("ro.sf.blurs_are_expensive", value, "0");
373 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800374
Ady Abraham0a525092020-03-03 12:51:24 -0800375 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700376 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
377 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
378
Dan Stozaec460082018-12-17 15:35:09 -0800379 property_get("debug.sf.luma_sampling", value, "1");
380 mLumaSampling = atoi(value);
381
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800382 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800383 mDisableClientCompositionCache = atoi(value);
384
Romain Guy11d63f42017-07-20 12:47:14 -0700385 // We should be reading 'persist.sys.sf.color_saturation' here
386 // but since /data may be encrypted, we need to wait until after vold
387 // comes online to attempt to read the property. The property is
388 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800389
390 if (useTrebleTestingOverride()) {
391 // Without the override SurfaceFlinger cannot connect to HIDL
392 // services that are not listed in the manifests. Considered
393 // deriving the setting from the set service name, but it
394 // would be brittle if the name that's not 'default' is used
395 // for production purposes later on.
396 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
397 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800398
399 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800400}
401
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800402void SurfaceFlinger::onFirstRef()
403{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800404 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800405}
406
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700407SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408
Dan Stozac7014012014-02-14 15:03:43 -0800409void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410{
411 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700412 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413
Andy McFadden13a082e2012-08-24 10:16:42 -0700414 // restore initial conditions (default device unblank, etc)
415 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416
417 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700418 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800419}
420
Robert Carr1db73f62016-12-21 12:58:51 -0800421static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700422 status_t err = client->initCheck();
423 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800424 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800425 }
Robert Carr1db73f62016-12-21 12:58:51 -0800426 return nullptr;
427}
428
429sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
430 return initClient(new Client(this));
431}
432
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700433sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
434 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700435{
436 class DisplayToken : public BBinder {
437 sp<SurfaceFlinger> flinger;
438 virtual ~DisplayToken() {
439 // no more references, this display must be terminated
440 Mutex::Autolock _l(flinger->mStateLock);
441 flinger->mCurrentState.displays.removeItem(this);
442 flinger->setTransactionFlags(eDisplayTransactionNeeded);
443 }
444 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700445 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700446 : flinger(flinger) {
447 }
448 };
449
450 sp<BBinder> token = new DisplayToken(this);
451
452 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700453 // Display ID is assigned when virtual display is allocated by HWC.
454 DisplayDeviceState state;
455 state.isSecure = secure;
456 state.displayName = displayName;
457 mCurrentState.displays.add(token, state);
458 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700459 return token;
460}
461
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700462void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700463 Mutex::Autolock _l(mStateLock);
464
Dominik Laskowski075d3172018-05-24 15:50:06 -0700465 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
466 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700467 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700468 return;
469 }
470
Dominik Laskowski075d3172018-05-24 15:50:06 -0700471 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
472 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700473 ALOGE("destroyDisplay called for non-virtual display");
474 return;
475 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700476 mInterceptor->saveDisplayDeletion(state.sequenceId);
477 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700478 setTransactionFlags(eDisplayTransactionNeeded);
479}
480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800481std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
482 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700483
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800484 const auto internalDisplayId = getInternalDisplayIdLocked();
485 if (!internalDisplayId) {
486 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700487 }
488
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800489 std::vector<PhysicalDisplayId> displayIds;
490 displayIds.reserve(mPhysicalDisplayTokens.size());
491 displayIds.push_back(internalDisplayId->value);
492
493 for (const auto& [id, token] : mPhysicalDisplayTokens) {
494 if (id != *internalDisplayId) {
495 displayIds.push_back(id.value);
496 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700497 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700498
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800499 return displayIds;
500}
501
502sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
503 Mutex::Autolock lock(mStateLock);
504 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700505}
506
Ady Abraham37965d42018-11-01 13:43:32 -0700507status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
508 if (!outGetColorManagement) {
509 return BAD_VALUE;
510 }
511 *outGetColorManagement = useColorManagement;
512 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700513}
514
Lloyd Pique441d5042018-10-18 16:49:51 -0700515HWComposer& SurfaceFlinger::getHwComposer() const {
516 return mCompositionEngine->getHwComposer();
517}
518
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700519renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
520 return mCompositionEngine->getRenderEngine();
521}
522
Lloyd Pique70d91362018-10-18 16:02:55 -0700523compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
524 return *mCompositionEngine.get();
525}
526
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800527void SurfaceFlinger::bootFinished()
528{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700529 if (mBootFinished == true) {
530 ALOGE("Extra call to bootFinished");
531 return;
532 }
533 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700534 if (mStartPropertySetThread->join() != NO_ERROR) {
535 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800536 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800537 const nsecs_t now = systemTime();
538 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000539 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700540
Mikael Pessa90092f42019-08-26 17:22:04 -0700541 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000542 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700543
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700544 // wait patiently for the window manager death
545 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700546 mWindowManager = defaultServiceManager()->getService(name);
547 if (mWindowManager != 0) {
548 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700549 }
Robert Carr720e5062018-07-30 17:45:14 -0700550 sp<IBinder> input(defaultServiceManager()->getService(
551 String16("inputflinger")));
552 if (input == nullptr) {
553 ALOGE("Failed to link to input service");
554 } else {
555 mInputFlinger = interface_cast<IInputFlinger>(input);
556 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700557
Steven Thomas050b2c82017-03-06 11:45:16 -0800558 if (mVrFlinger) {
559 mVrFlinger->OnBootFinished();
560 }
561
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700562 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700563 // formerly we would just kill the process, but we now ask it to exit so it
564 // can choose where to stop the animation.
565 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700566
567 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
568 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
569 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700570
Ana Krulecbd6654b2019-02-15 15:18:15 -0800571 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800572 readPersistentProperties();
573 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800574
Ady Abraham8a82ba62020-01-17 12:43:17 -0800575 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
576 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
577 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
578 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800579 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800580}
581
Dan Stoza436ccf32018-06-21 12:10:12 -0700582uint32_t SurfaceFlinger::getNewTexture() {
583 {
584 std::lock_guard lock(mTexturePoolMutex);
585 if (!mTexturePool.empty()) {
586 uint32_t name = mTexturePool.back();
587 mTexturePool.pop_back();
588 ATRACE_INT("TexturePoolSize", mTexturePool.size());
589 return name;
590 }
591
592 // The pool was too small, so increase it for the future
593 ++mTexturePoolSize;
594 }
595
596 // The pool was empty, so we need to get a new texture name directly using a
597 // blocking call to the main thread
598 uint32_t name = 0;
599 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
600 return name;
601}
602
Mathias Agopian3f844832013-08-07 21:24:32 -0700603void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700604 std::lock_guard lock(mTexturePoolMutex);
605 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
606 // to actually delete this or not based on mTexturePoolSize
607 mTexturePool.push_back(texture);
608 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700609}
610
Wei Wangf9b05ee2017-07-19 20:59:39 -0700611// Do not call property_set on main thread which will be blocked by init
612// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700613void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700614 ALOGI( "SurfaceFlinger's main thread ready to run. "
615 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700616 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800617
Steven Thomasb02664d2017-07-26 18:48:28 -0700618 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700619 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800620 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700621 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
622 renderengine::RenderEngineCreationArgs::Builder()
623 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
624 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
625 .setUseColorManagerment(useColorManagement)
626 .setEnableProtectedContext(enable_protected_contents(false))
627 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800628 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700629 .setContextPriority(useContextPriority
630 ? renderengine::RenderEngine::ContextPriority::HIGH
631 : renderengine::RenderEngine::ContextPriority::MEDIUM)
632 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800633 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700634
635 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
636 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700637 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800638 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800639 // Process any initial hotplug and resulting display changes.
640 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700641 const auto display = getDefaultDisplayDeviceLocked();
642 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700643 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700644 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800645
Steven Thomas050b2c82017-03-06 11:45:16 -0800646 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700647 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700648 // This callback is called from the vr flinger dispatch thread. We
649 // need to call signalTransaction(), which requires holding
650 // mStateLock when we're not on the main thread. Acquiring
651 // mStateLock from the vr flinger dispatch thread might trigger a
652 // deadlock in surface flinger (see b/66916578), so post a message
653 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700654 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700655 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
656 mVrFlingerRequestsDisplay = requestDisplay;
657 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700658 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800659 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700660 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
661 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700662 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700663 .value_or(0),
664 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800665 if (!mVrFlinger) {
666 ALOGE("Failed to start vrflinger");
667 }
668 }
669
Mathias Agopian92a979a2012-08-02 18:32:23 -0700670 // initialize our drawing state
671 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700672
Andy McFadden13a082e2012-08-24 10:16:42 -0700673 // set initial conditions (e.g. unblank default device)
674 initializeDisplays();
675
Steven Thomas137d4bc2019-07-25 16:55:14 -0700676 char primeShaderCache[PROPERTY_VALUE_MAX];
677 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
678 if (atoi(primeShaderCache)) {
679 getRenderEngine().primeCache();
680 }
Dan Stoza4e637772016-07-28 13:31:51 -0700681
Wei Wangf9b05ee2017-07-19 20:59:39 -0700682 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700683
684 const bool presentFenceReliable =
685 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
686 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700687
688 if (mStartPropertySetThread->Start() != NO_ERROR) {
689 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800690 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800691
Dan Stoza9e56aa02015-11-02 13:00:03 -0800692 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700693}
694
Romain Guy11d63f42017-07-20 12:47:14 -0700695void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700696 Mutex::Autolock _l(mStateLock);
697
Romain Guy11d63f42017-07-20 12:47:14 -0700698 char value[PROPERTY_VALUE_MAX];
699
700 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800701 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700702 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800703 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100704
705 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700706 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800707
708 property_get("persist.sys.sf.color_mode", value, "0");
709 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700710}
711
Mathias Agopiana67e4182012-06-19 17:26:12 -0700712void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800713 // Start boot animation service by setting a property mailbox
714 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700715 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800716 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700717 if (mStartPropertySetThread->join() != NO_ERROR) {
718 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800719 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700720}
721
Mathias Agopian875d8e12013-06-07 15:35:48 -0700722size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700723 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700724}
725
Mathias Agopian875d8e12013-06-07 15:35:48 -0700726size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700727 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700728}
729
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800730// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800731
Jamie Gennis582270d2011-08-17 18:19:00 -0700732bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800733 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800734 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800735 return authenticateSurfaceTextureLocked(bufferProducer);
736}
737
738bool SurfaceFlinger::authenticateSurfaceTextureLocked(
739 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800740 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800741 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800742}
743
Brian Anderson6b376712017-04-04 10:51:39 -0700744status_t SurfaceFlinger::getSupportedFrameTimestamps(
745 std::vector<FrameEvent>* outSupported) const {
746 *outSupported = {
747 FrameEvent::REQUESTED_PRESENT,
748 FrameEvent::ACQUIRE,
749 FrameEvent::LATCH,
750 FrameEvent::FIRST_REFRESH_START,
751 FrameEvent::LAST_REFRESH_START,
752 FrameEvent::GPU_COMPOSITION_DONE,
753 FrameEvent::DEQUEUE_READY,
754 FrameEvent::RELEASE,
755 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700756 ConditionalLock _l(mStateLock,
757 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700758 if (!getHwComposer().hasCapability(
759 HWC2::Capability::PresentFenceIsNotReliable)) {
760 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
761 }
762 return NO_ERROR;
763}
764
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800765status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
766 if (!displayToken || !state) {
767 return BAD_VALUE;
768 }
769
770 Mutex::Autolock lock(mStateLock);
771
772 const auto display = getDisplayDeviceLocked(displayToken);
773 if (!display) {
774 return NAME_NOT_FOUND;
775 }
776
777 state->layerStack = display->getLayerStack();
778 state->orientation = display->getOrientation();
779
780 const Rect viewport = display->getViewport();
781 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
782
783 return NO_ERROR;
784}
785
786status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
787 if (!displayToken || !info) {
788 return BAD_VALUE;
789 }
790
791 Mutex::Autolock lock(mStateLock);
792
793 const auto display = getDisplayDeviceLocked(displayToken);
794 if (!display) {
795 return NAME_NOT_FOUND;
796 }
797
Dominik Laskowski55c85402020-01-21 16:25:47 -0800798 if (const auto connectionType = display->getConnectionType())
799 info->connectionType = *connectionType;
800 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800801 return INVALID_OPERATION;
802 }
803
804 if (mEmulatedDisplayDensity) {
805 info->density = mEmulatedDisplayDensity;
806 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800807 info->density = info->connectionType == DisplayConnectionType::Internal
808 ? mInternalDisplayDensity
809 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800810 }
811
812 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200813 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800814
815 return NO_ERROR;
816}
817
Dominik Laskowski22488f62019-03-28 09:53:04 -0700818status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800819 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700820 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700821 return BAD_VALUE;
822 }
823
Dominik Laskowski22488f62019-03-28 09:53:04 -0700824 Mutex::Autolock lock(mStateLock);
825
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800826 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700827 if (!displayId) {
828 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700829 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700830
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800831 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700832
Dan Stoza7f7da322014-05-02 15:26:25 -0700833 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700834
Dominik Laskowski075d3172018-05-24 15:50:06 -0700835 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800836 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700837
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800838 auto width = hwConfig->getWidth();
839 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700840
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800841 auto xDpi = hwConfig->getDpiX();
842 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700843
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800844 if (isInternal &&
845 (internalDisplayOrientation == ui::ROTATION_90 ||
846 internalDisplayOrientation == ui::ROTATION_270)) {
847 std::swap(width, height);
848 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700849 }
850
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800851 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800852
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800853 if (mEmulatedDisplayDensity) {
854 config.xDpi = mEmulatedDisplayDensity;
855 config.yDpi = mEmulatedDisplayDensity;
856 } else {
857 config.xDpi = xDpi;
858 config.yDpi = yDpi;
859 }
860
861 const nsecs_t period = hwConfig->getVsyncPeriod();
862 config.refreshRate = 1e9f / period;
863
864 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
865 config.appVsyncOffset = offsets.late.app;
866 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800867 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800868
Andy McFadden91b2ca82014-06-13 14:04:23 -0700869 // This is how far in advance a buffer must be queued for
870 // presentation at a given time. If you want a buffer to appear
871 // on the screen at time N, you must submit the buffer before
872 // (N - presentationDeadline).
873 //
874 // Normally it's one full refresh period (to give SF a chance to
875 // latch the buffer), but this can be reduced by configuring a
876 // DispSync offset. Any additional delays introduced by the hardware
877 // composer or panel must be accounted for here.
878 //
879 // We add an additional 1ms to allow for processing time and
880 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800881 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700882
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800883 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700884 }
885
Dan Stoza7f7da322014-05-02 15:26:25 -0700886 return NO_ERROR;
887}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700888
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700889status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
890 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700891 return BAD_VALUE;
892 }
893
Ana Krulecc2870422019-01-29 19:00:58 -0800894 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700895 return NO_ERROR;
896}
897
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700898int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
899 const auto display = getDisplayDevice(displayToken);
900 if (!display) {
901 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800902 return BAD_VALUE;
903 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700904
Steven Thomasc9098452019-09-30 17:15:05 -0700905 if (display->isPrimary()) {
906 std::lock_guard<std::mutex> lock(mActiveConfigLock);
907 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800908 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700909 }
Steven Thomasc9098452019-09-30 17:15:05 -0700910 }
Ady Abraham2139f732019-11-13 18:56:40 -0800911
912 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700913}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700914
Ady Abraham03b02dd2019-03-21 15:40:11 -0700915void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800916 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800917 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abraham2139f732019-11-13 18:56:40 -0800918 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800919
Ady Abrahamb838aed2019-02-12 15:30:16 -0800920 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800921 if (mDesiredActiveConfigChanged) {
922 // If a config change is pending, just cache the latest request in
923 // mDesiredActiveConfig
924 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
925 mDesiredActiveConfig = info;
926 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
927 } else {
928 // Check is we are already at the desired config
929 const auto display = getDefaultDisplayDeviceLocked();
930 if (!display || display->getActiveConfig() == refreshRate.configId) {
931 return;
932 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800933
Ady Abraham59db0a32020-03-02 18:04:20 -0800934 // Initiate a config change.
935 mDesiredActiveConfigChanged = true;
936 mDesiredActiveConfig = info;
937
Ady Abrahamb838aed2019-02-12 15:30:16 -0800938 // This will trigger HWC refresh without resetting the idle timer.
939 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700940 // Start receiving vsync samples now, so that we can detect a period
941 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800942 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700943 // As we called to set period, we will call to onRefreshRateChangeCompleted once
944 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700945 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800946
Ady Abraham9e16a482019-12-03 17:19:41 -0800947 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
948 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800949 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700950
951 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800952 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700953 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800954}
955
956status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
957 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800958
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100959 if (!displayToken) {
960 return BAD_VALUE;
961 }
Ady Abraham838de062019-02-04 10:24:03 -0800962
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100963 status_t result = NO_ERROR;
964
965 postMessageSync(new LambdaMessage([&]() {
966 const auto display = getDisplayDeviceLocked(displayToken);
967 if (!display) {
968 ALOGE("Attempt to set allowed display configs for invalid display token %p",
969 displayToken.get());
970 result = BAD_VALUE;
971 } else if (display->isVirtual()) {
972 ALOGW("Attempt to set allowed display configs for virtual display");
973 result = BAD_VALUE;
974 } else {
975 HwcConfigIndexType config(mode);
976 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
977 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
978 refreshRate.fps);
979 }
980 }));
981
982 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800983}
984
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800985void SurfaceFlinger::setActiveConfigInternal() {
986 ATRACE_CALL();
987
Dominik Laskowski22488f62019-03-28 09:53:04 -0700988 const auto display = getDefaultDisplayDeviceLocked();
989 if (!display) {
990 return;
991 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800992
Alec Mouri8de697e2020-03-19 10:52:01 -0700993 auto& oldRefreshRate =
994 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
995
Dominik Laskowski22488f62019-03-28 09:53:04 -0700996 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800997 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700998 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800999 display->setActiveConfig(mUpcomingActiveConfig.configId);
1000
Ady Abraham2e1dd892020-03-05 13:48:36 -08001001 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001002 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Alec Mouri8de697e2020-03-19 10:52:01 -07001003 if (refreshRate.vsyncPeriod != oldRefreshRate.vsyncPeriod) {
1004 mTimeStats->incrementRefreshRateSwitches();
1005 }
Ady Abraham9e16a482019-12-03 17:19:41 -08001006 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1007 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -08001008 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001009
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001010 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001011 const nsecs_t vsyncPeriod =
1012 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
1013 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -08001014 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001015 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001016 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001017}
1018
Ady Abraham53852a52019-05-28 18:07:44 -07001019void SurfaceFlinger::desiredActiveConfigChangeDone() {
1020 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1021 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1022 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001023
Ady Abraham2e1dd892020-03-05 13:48:36 -08001024 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001025 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001026 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001027 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1028 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001029}
1030
Dominik Laskowski22488f62019-03-28 09:53:04 -07001031bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001032 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001033 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001034 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001035 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001036 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001037 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001038 return true;
1039 }
1040
1041 // We received the present fence from the HWC, so we assume it successfully updated
1042 // the config, hence we update SF.
1043 mCheckPendingFence = false;
1044 setActiveConfigInternal();
1045 }
1046
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001047 // Store the local variable to release the lock.
1048 ActiveConfigInfo desiredActiveConfig;
1049 {
1050 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001051 if (!mDesiredActiveConfigChanged) {
1052 return false;
1053 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001054 desiredActiveConfig = mDesiredActiveConfig;
1055 }
1056
Ady Abraham2e1dd892020-03-05 13:48:36 -08001057 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001058 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1059 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1060 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001061 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001062 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1063 // display is not valid or we are already in the requested mode
1064 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001065 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001066 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001067 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001068
Ady Abraham838de062019-02-04 10:24:03 -08001069 // Desired active config was set, it is different than the config currently in use, however
1070 // allowed configs might have change by the time we process the refresh.
1071 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001072 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001073 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001074 return false;
1075 }
Alec Mouri7f015182019-07-11 13:56:22 -07001076
Ady Abrahamb838aed2019-02-12 15:30:16 -08001077 mUpcomingActiveConfig = desiredActiveConfig;
1078 const auto displayId = display->getId();
1079 LOG_ALWAYS_FATAL_IF(!displayId);
1080
Ady Abraham2139f732019-11-13 18:56:40 -08001081 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001082
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001083 // TODO(b/142753666) use constrains
1084 HWC2::VsyncPeriodChangeConstraints constraints;
1085 constraints.desiredTimeNanos = systemTime();
1086 constraints.seamlessRequired = false;
1087
1088 HWC2::VsyncPeriodChangeTimeline outTimeline;
1089 auto status =
1090 getHwComposer().setActiveConfigWithConstraints(*displayId,
1091 mUpcomingActiveConfig.configId.value(),
1092 constraints, &outTimeline);
1093 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001094 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1095 // to be sent. We just log the error in this case.
1096 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001097 return false;
1098 }
1099
1100 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1101 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001102 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001103 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001104}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001105
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001106status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1107 Vector<ColorMode>* outColorModes) {
1108 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001109 return BAD_VALUE;
1110 }
1111
Peiyong Lina52f0292018-03-14 17:26:31 -07001112 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001113 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001114 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001115 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1116
1117 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1118 if (!displayId) {
1119 return NAME_NOT_FOUND;
1120 }
1121
Dominik Laskowski075d3172018-05-24 15:50:06 -07001122 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001123 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001124 }
Michael Wright28f24d02016-07-12 13:30:53 -07001125 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001126
1127 // If it's built-in display and the configuration claims it's not wide color capable,
1128 // filter out all wide color modes. The typical reason why this happens is that the
1129 // hardware is not good enough to support GPU composition of wide color, and thus the
1130 // OEMs choose to disable this capability.
1131 if (isInternalDisplay && !hasWideColorDisplay) {
1132 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1133 isWideColorMode);
1134 } else {
1135 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1136 }
Michael Wright28f24d02016-07-12 13:30:53 -07001137
1138 return NO_ERROR;
1139}
1140
Daniel Solomon42d04562019-01-20 21:03:19 -08001141status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1142 ui::DisplayPrimaries &primaries) {
1143 if (!displayToken) {
1144 return BAD_VALUE;
1145 }
1146
1147 // Currently we only support this API for a single internal display.
1148 if (getInternalDisplayToken() != displayToken) {
1149 return BAD_VALUE;
1150 }
1151
1152 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1153 return NO_ERROR;
1154}
1155
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001156ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1157 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001158 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001159 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001160 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001161}
1162
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001163status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001164 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001165 Vector<ColorMode> modes;
1166 getDisplayColorModes(displayToken, &modes);
1167 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1168 if (mode < ColorMode::NATIVE || !exists) {
1169 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1170 decodeColorMode(mode).c_str(), mode, displayToken.get());
1171 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001172 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001173 const auto display = getDisplayDevice(displayToken);
1174 if (!display) {
1175 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1176 decodeColorMode(mode).c_str(), mode, displayToken.get());
1177 } else if (display->isVirtual()) {
1178 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1179 decodeColorMode(mode).c_str(), mode);
1180 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001181 display->getCompositionDisplay()->setColorProfile(
1182 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1183 RenderIntent::COLORIMETRIC,
1184 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001185 }
1186 }));
1187
Michael Wright28f24d02016-07-12 13:30:53 -07001188 return NO_ERROR;
1189}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001190
Galia Peycheva5492cb52019-10-30 14:13:16 +01001191status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1192 bool* outSupport) const {
1193 Mutex::Autolock _l(mStateLock);
1194
1195 if (!displayToken) {
1196 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1197 return BAD_VALUE;
1198 }
1199 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1200 if (!displayId) {
1201 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1202 displayToken.get());
1203 return NAME_NOT_FOUND;
1204 }
1205 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1206 HWC2::DisplayCapability::AutoLowLatencyMode);
1207 return NO_ERROR;
1208}
1209
1210void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1211 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1212}
1213
1214void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1215 if (!displayToken) {
1216 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1217 return;
1218 }
1219 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1220 if (!displayId) {
1221 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1222 displayToken.get());
1223 return;
1224 }
1225
1226 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1227}
1228
1229status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1230 bool* outSupport) const {
1231 Mutex::Autolock _l(mStateLock);
1232
1233 if (!displayToken) {
1234 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1235 return BAD_VALUE;
1236 }
1237 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1238 if (!displayId) {
1239 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1240 displayToken.get());
1241 return NAME_NOT_FOUND;
1242 }
1243
1244 std::vector<HWC2::ContentType> outSupportedContentTypes;
1245 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1246 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1247 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1248 return NO_ERROR;
1249}
1250
1251void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1252 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1253}
1254
1255void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1256 if (!displayToken) {
1257 ALOGE("setGameContentType() failed. Missing display token.");
1258 return;
1259 }
1260 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1261 if (!displayId) {
1262 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1263 displayToken.get());
1264 return;
1265 }
1266
1267 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1268 getHwComposer().setContentType(*displayId, type);
1269}
1270
Svetoslavd85084b2014-03-20 10:28:31 -07001271status_t SurfaceFlinger::clearAnimationFrameStats() {
1272 Mutex::Autolock _l(mStateLock);
1273 mAnimFrameTracker.clearStats();
1274 return NO_ERROR;
1275}
1276
1277status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1278 Mutex::Autolock _l(mStateLock);
1279 mAnimFrameTracker.getStats(outStats);
1280 return NO_ERROR;
1281}
1282
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001283status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1284 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001285 Mutex::Autolock _l(mStateLock);
1286
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001287 const auto display = getDisplayDeviceLocked(displayToken);
1288 if (!display) {
1289 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001290 return BAD_VALUE;
1291 }
1292
Peiyong Linfb069302018-04-25 14:34:31 -07001293 // At this point the DisplayDeivce should already be set up,
1294 // meaning the luminance information is already queried from
1295 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001296 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001297 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1298 capabilities.getDesiredMaxLuminance(),
1299 capabilities.getDesiredMaxAverageLuminance(),
1300 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001301
1302 return NO_ERROR;
1303}
1304
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001305std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1306 const DisplayDevice& display) const {
1307 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1308 // avoid repetitive HAL IPC and EDID parsing.
1309 const auto displayId = display.getId();
1310 LOG_FATAL_IF(!displayId);
1311
1312 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1313 LOG_FATAL_IF(!hwcDisplayId);
1314
1315 uint8_t port;
1316 DisplayIdentificationData data;
1317 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1318 ALOGV("%s: No identification data.", __FUNCTION__);
1319 return {};
1320 }
1321
1322 const auto info = parseDisplayIdentificationData(port, data);
1323 if (!info) {
1324 return {};
1325 }
1326 return info->deviceProductInfo;
1327}
1328
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001329status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1330 ui::PixelFormat* outFormat,
1331 ui::Dataspace* outDataspace,
1332 uint8_t* outComponentMask) const {
1333 if (!outFormat || !outDataspace || !outComponentMask) {
1334 return BAD_VALUE;
1335 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001336 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001337 if (!display || !display->getId()) {
1338 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1339 return BAD_VALUE;
1340 }
1341 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1342 outDataspace, outComponentMask);
1343}
1344
Kevin DuBois74e53772018-11-19 10:52:38 -08001345status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1346 bool enable, uint8_t componentMask,
1347 uint64_t maxFrames) const {
1348 const auto display = getDisplayDevice(displayToken);
1349 if (!display || !display->getId()) {
1350 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1351 return BAD_VALUE;
1352 }
1353
1354 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1355 componentMask, maxFrames);
1356}
1357
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001358status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1359 uint64_t maxFrames, uint64_t timestamp,
1360 DisplayedFrameStats* outStats) const {
1361 const auto display = getDisplayDevice(displayToken);
1362 if (!display || !display->getId()) {
1363 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1364 return BAD_VALUE;
1365 }
1366
1367 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1368 outStats);
1369}
1370
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001371status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1372 if (!outSupported) {
1373 return BAD_VALUE;
1374 }
1375 *outSupported = getRenderEngine().supportsProtectedContent();
1376 return NO_ERROR;
1377}
1378
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001379status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1380 bool* outIsWideColorDisplay) const {
1381 if (!displayToken || !outIsWideColorDisplay) {
1382 return BAD_VALUE;
1383 }
1384 Mutex::Autolock _l(mStateLock);
1385 const auto display = getDisplayDeviceLocked(displayToken);
1386 if (!display) {
1387 return BAD_VALUE;
1388 }
Peiyong Linff84a152019-05-17 18:36:19 -07001389
1390 // Use hasWideColorDisplay to override built-in display.
1391 const auto displayId = display->getId();
1392 if (displayId && displayId == getInternalDisplayIdLocked()) {
1393 *outIsWideColorDisplay = hasWideColorDisplay;
1394 return NO_ERROR;
1395 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001396 *outIsWideColorDisplay = display->hasWideColorGamut();
1397 return NO_ERROR;
1398}
1399
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001400status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001401 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001402 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001403
Dominik Laskowski6505f792019-09-18 11:10:05 -07001404 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1405 mEventQueue->setEventConnection(
1406 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001407 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001408 }));
1409
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001410 return NO_ERROR;
1411}
1412
1413status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001414 Mutex::Autolock lock(mStateLock);
1415 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001416}
1417
Lloyd Pique755e3192018-01-31 16:46:15 -08001418status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1419 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001420 // Try to acquire a lock for 1s, fail gracefully
1421 const status_t err = mStateLock.timedLock(s2ns(1));
1422 const bool locked = (err == NO_ERROR);
1423 if (!locked) {
1424 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1425 return TIMED_OUT;
1426 }
1427
1428 outLayers->clear();
1429 mCurrentState.traverseInZOrder([&](Layer* layer) {
1430 outLayers->push_back(layer->getLayerDebugInfo());
1431 });
1432
1433 mStateLock.unlock();
1434 return NO_ERROR;
1435}
1436
Peiyong Linc6780972018-10-28 15:24:08 -07001437status_t SurfaceFlinger::getCompositionPreference(
1438 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1439 Dataspace* outWideColorGamutDataspace,
1440 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001441 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001442 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001443 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001444 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001445 return NO_ERROR;
1446}
1447
Dan Stozaec460082018-12-17 15:35:09 -08001448status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1449 const sp<IBinder>& stopLayerHandle,
1450 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001451 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001452 return BAD_VALUE;
1453 }
1454 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001455 return NO_ERROR;
1456}
1457
Dan Stozaec460082018-12-17 15:35:09 -08001458status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001459 if (!listener) {
1460 return BAD_VALUE;
1461 }
Dan Stozaec460082018-12-17 15:35:09 -08001462 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001463 return NO_ERROR;
1464}
Dan Gittik57e63c52019-01-18 16:37:54 +00001465
1466status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1467 bool* outSupport) const {
1468 if (!displayToken || !outSupport) {
1469 return BAD_VALUE;
1470 }
1471 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1472 if (!displayId) {
1473 return NAME_NOT_FOUND;
1474 }
1475 *outSupport =
1476 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1477 return NO_ERROR;
1478}
1479
1480status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1481 float brightness) const {
1482 if (!displayToken) {
1483 return BAD_VALUE;
1484 }
1485 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1486 if (!displayId) {
1487 return NAME_NOT_FOUND;
1488 }
1489 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1490}
1491
Ady Abraham8532d012019-05-08 14:50:56 -07001492status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1493 PowerHint powerHint = static_cast<PowerHint>(hintId);
1494
1495 if (powerHint == PowerHint::INTERACTION) {
1496 mScheduler->notifyTouchEvent();
1497 }
1498
1499 return NO_ERROR;
1500}
1501
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001502// ----------------------------------------------------------------------------
1503
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001504sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001505 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001506 const auto& handle =
1507 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001508
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001509 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001510}
1511
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001512// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001513
1514void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001515 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001516}
1517
1518void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001519 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001520 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001521 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001522}
1523
1524void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001525 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001526 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001527 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001528}
1529
1530void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001531 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001532 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001533}
1534
1535status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001536 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001537 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001538}
1539
1540status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001541 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001542 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001543 if (res == NO_ERROR) {
1544 msg->wait();
1545 }
1546 return res;
1547}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001548
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001549void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001550 do {
1551 waitForEvent();
1552 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001553}
1554
Dominik Laskowski83b88212018-12-11 13:34:06 -08001555nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001556 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001557 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1558 return 0;
1559 }
1560
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001561 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001562}
1563
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001564void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001565 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001566 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001567 ATRACE_NAME("SF onVsync");
1568
Steven Thomas3cfac282017-02-06 12:29:30 -08001569 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001570 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001571 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001572 return;
1573 }
1574
Dominik Laskowski075d3172018-05-24 15:50:06 -07001575 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001576 return;
1577 }
1578
Dominik Laskowski075d3172018-05-24 15:50:06 -07001579 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001580 // For now, we don't do anything with external display vsyncs.
1581 return;
1582 }
1583
Alec Mourif8e689c2019-05-20 18:32:22 -07001584 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001585 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001586 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001587 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001588 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001589}
1590
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001591void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001592 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1593 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001594}
1595
Ady Abraham2139f732019-11-13 18:56:40 -08001596bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001597 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001598}
1599
Ady Abraham2139f732019-11-13 18:56:40 -08001600void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1601 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001602 const auto display = getDefaultDisplayDeviceLocked();
1603 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001604 return;
1605 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001606 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001607
Ana Krulec7d1d6832018-12-27 11:10:09 -08001608 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001609 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1610 ALOGV("Skipping config %d as it is not part of allowed configs",
1611 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001612 return;
1613 }
1614
Ady Abraham2139f732019-11-13 18:56:40 -08001615 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001616}
1617
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001618void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001619 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001620 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001621 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001622
Lloyd Piqueba04e622017-12-14 17:11:26 -08001623 // Ignore events that do not have the right sequenceId.
1624 if (sequenceId != getBE().mComposerSequenceId) {
1625 return;
1626 }
1627
Steven Thomasb02664d2017-07-26 18:48:28 -07001628 // Only lock if we're not on the main thread. This function is normally
1629 // called on a hwbinder thread, but for the primary display it's called on
1630 // the main thread with the state lock already held, so don't attempt to
1631 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001632 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001633
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001634 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001635
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001636 if (std::this_thread::get_id() == mMainThreadId) {
1637 // Process all pending hot plug events immediately if we are on the main thread.
1638 processDisplayHotplugEventsLocked();
1639 }
1640
Lloyd Piqueba04e622017-12-14 17:11:26 -08001641 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001642}
1643
Ady Abraham7159f572019-10-11 11:10:18 -07001644void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001645 int32_t sequenceId, hwc2_display_t /*display*/,
1646 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1647 Mutex::Autolock lock(mStateLock);
1648 if (sequenceId != getBE().mComposerSequenceId) {
1649 return;
1650 }
1651 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001652}
1653
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001654void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1655 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1656 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1657}
1658
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001659void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001660 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001661 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001662 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001663 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001664 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001665}
1666
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001667void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001668 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001669
1670 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1671 // display power state.
1672 postMessageAsync(new LambdaMessage(
1673 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1674}
1675
1676void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1677 ATRACE_CALL();
1678
Ady Abraham27c70212019-06-11 10:52:26 -07001679 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1680
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001681 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001682 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1683 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001684 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001685 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001686 }
Mathias Agopian86303202012-07-24 22:46:10 -07001687}
1688
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001689// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001690void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001691 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001692 // Clear the drawing state so that the logic inside of
1693 // handleTransactionLocked will fire. It will determine the delta between
1694 // mCurrentState and mDrawingState and re-apply all changes when we make the
1695 // transition.
1696 mDrawingState.displays.clear();
1697 mDisplays.clear();
1698}
1699
Steven Thomas050b2c82017-03-06 11:45:16 -08001700void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001701 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001702 if (!mVrFlinger)
1703 return;
1704 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001705 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001706 return;
1707 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001708
Lloyd Pique441d5042018-10-18 16:49:51 -07001709 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001710 ALOGE("Vr flinger is only supported for remote hardware composer"
1711 " service connections. Ignoring request to transition to vr"
1712 " flinger.");
1713 mVrFlingerRequestsDisplay = false;
1714 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001715 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001716
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001717 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001718
Steven Thomas0123ac62018-07-12 11:32:34 -07001719 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001720 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001721
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001722 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001723
1724 // Clear out all the output layers from the composition engine for all
1725 // displays before destroying the hardware composer interface. This ensures
1726 // any HWC layers are destroyed through that interface before it becomes
1727 // invalid.
1728 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001729 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001730 }
1731
Steven Thomas0123ac62018-07-12 11:32:34 -07001732 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1733 // called below. Clear the reference now so we don't accidentally use it
1734 // later.
1735 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001736
Steven Thomasb02664d2017-07-26 18:48:28 -07001737 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001738 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001739 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001740
Steven Thomasb02664d2017-07-26 18:48:28 -07001741 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001742 // Delete the current instance before creating the new one
1743 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1744 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1745 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001746 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001747
Lloyd Pique441d5042018-10-18 16:49:51 -07001748 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001749 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001750
1751 if (vrFlingerRequestsDisplay) {
1752 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001753 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001754
1755 mVisibleRegionsDirty = true;
1756 invalidateHwcGeometry();
1757
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001758 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001759 display = getDefaultDisplayDeviceLocked();
1760 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001761 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001762
Steven Thomasb02664d2017-07-26 18:48:28 -07001763 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001764 const nsecs_t vsyncPeriod = getVsyncPeriod();
1765 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001766
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001767 // The present fences returned from vr_hwc are not an accurate
1768 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001769 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001770
Steven Thomasb02664d2017-07-26 18:48:28 -07001771 // Use phase of 0 since phase is not known.
1772 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001773 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001774 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001775
Ana Krulecc2870422019-01-29 19:00:58 -08001776 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001777
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001778 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001779 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001780}
1781
Ady Abraham11579302019-09-19 12:35:58 -07001782bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1783 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001784 // We are storing the last 2 present fences. If sf's phase offset is to be
1785 // woken up before the actual vsync but targeting the next vsync, we need to check
1786 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001787 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1788 : mPreviousPresentFences[1];
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
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001801void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001802 DisplayStatInfo stats;
1803 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001804 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001805 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001806 mExpectedPresentTime.store(
1807 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001808}
1809
Dominik Laskowski22488f62019-03-28 09:53:04 -07001810void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001811 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001812 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001813 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001814 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001815 // calculate the expected present time once and use the cached
1816 // value throughout this frame to make sure all layers are
1817 // seeing this same value.
1818 populateExpectedPresentTime();
1819
Ady Abraham11579302019-09-19 12:35:58 -07001820 // When Backpressure propagation is enabled we want to give a small grace period
1821 // for the present fence to fire instead of just giving up on this frame to handle cases
1822 // where present fence is just about to get signaled.
1823 const int graceTimeForPresentFenceMs =
1824 (mPropagateBackpressure &&
1825 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1826 ? 1
1827 : 0;
1828 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1829 previousFrameMissed(
1830 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001831 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1832 mHadDeviceComposition && frameMissed};
1833 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1834 mHadClientComposition && frameMissed};
1835
Alec Mouricc0fc602019-02-26 21:45:19 -08001836 if (frameMissed) {
1837 mFrameMissedCount++;
1838 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001839 if (mMissedFrameJankCount == 0) {
1840 mMissedFrameJankStart = systemTime();
1841 }
1842 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001843 }
1844
Alec Mouri40189b02019-03-05 15:07:54 -08001845 if (hwcFrameMissed) {
1846 mHwcFrameMissedCount++;
1847 }
1848
1849 if (gpuFrameMissed) {
1850 mGpuFrameMissedCount++;
1851 }
1852
Ady Abrahamadb9a992019-09-19 21:21:55 +00001853 if (frameMissed && mPropagateBackpressure) {
1854 if ((hwcFrameMissed && !gpuFrameMissed) ||
1855 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001856 signalLayerUpdate();
1857 break;
1858 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001859 }
Dan Stoza50182882016-07-08 12:02:20 -07001860
Alec Mouri989ddbe2020-02-06 09:26:19 -08001861 // Our jank window is always at least 100ms since we missed a
1862 // frame...
1863 static constexpr nsecs_t kMinJankyDuration =
1864 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1865 // ...but if it's larger than 1s then we missed the trace cutoff.
1866 static constexpr nsecs_t kMaxJankyDuration =
1867 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1868 // If we're in a user build then don't push any atoms
1869 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1870 const auto displayDevice = getDefaultDisplayDeviceLocked();
1871 // Only report jank when the display is on, as displays in DOZE
1872 // power mode may operate at a different frame rate than is
1873 // reported in their config, which causes noticeable (but less
1874 // severe) jank.
1875 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1876 const nsecs_t currentTime = systemTime();
1877 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1878 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1879 ATRACE_NAME("Jank detected");
1880 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1881 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1882 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1883 jankyDurationMillis, mMissedFrameJankCount);
1884 }
1885
1886 // We either reported a jank event or we missed the trace
1887 // window, so clear counters here.
1888 if (jankDuration > kMinJankyDuration) {
1889 mMissedFrameJankCount = 0;
1890 mMissedFrameJankStart = 0;
1891 }
1892 }
1893 }
1894
Steven Thomas050b2c82017-03-06 11:45:16 -08001895 // Now that we're going to make it to the handleMessageTransaction()
1896 // call below it's safe to call updateVrFlinger(), which will
1897 // potentially trigger a display handoff.
1898 updateVrFlinger();
1899
Dan Stoza6b9454d2014-11-07 16:00:59 -08001900 bool refreshNeeded = handleMessageTransaction();
1901 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001902
Ana Krulecc84d09b2019-11-02 23:10:29 +01001903 // Layers need to get updated (in the previous line) before we can use them for
1904 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001905 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1906 // and may eventually call to ~Layer() if it holds the last reference
1907 {
1908 Mutex::Autolock _l(mStateLock);
1909 mScheduler->chooseRefreshRateForContent();
1910 }
1911
Ana Krulecc84d09b2019-11-02 23:10:29 +01001912 if (performSetActiveConfig()) {
1913 break;
1914 }
1915
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001916 updateCursorAsync();
1917 updateInputFlinger();
1918
Dan Stoza58784442014-12-02 16:58:17 -08001919 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001920 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001921 // Signal a refresh if a transaction modified the window state,
1922 // a new buffer was latched, or if HWC has requested a full
1923 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001924 if (mFrameStartTime <= 0) {
1925 // We should only use the time of the first invalidate
1926 // message that signals a refresh as the beginning of the
1927 // frame. Otherwise the real frame time will be
1928 // underestimated.
1929 mFrameStartTime = frameStart;
1930 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001931 signalRefresh();
1932 }
1933 break;
1934 }
1935 case MessageQueue::REFRESH: {
1936 handleMessageRefresh();
1937 break;
1938 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001939 }
1940}
1941
Dan Stoza6b9454d2014-11-07 16:00:59 -08001942bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001943 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001944 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001945
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001946 bool flushedATransaction = flushTransactionQueues();
1947
1948 bool runHandleTransaction = transactionFlags &&
1949 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1950
1951 if (runHandleTransaction) {
1952 handleTransaction(eTransactionMask);
1953 } else {
1954 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001955 }
1956
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001957 if (transactionFlushNeeded()) {
1958 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001959 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001960
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001961 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001962}
1963
Mathias Agopian4fec8732012-06-29 14:12:52 -07001964void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001965 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001966
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001967 mRefreshPending = false;
1968
Lloyd Piqueab039b52019-02-13 14:22:42 -08001969 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001970 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001971 for (const auto& [_, display] : mDisplays) {
1972 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1973 }
1974 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001975 if (auto layerFE = layer->getCompositionEngineLayerFE())
1976 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001977 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001978 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1979 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001980 if (auto layerFE = layer->getCompositionEngineLayerFE())
1981 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001982 }
1983
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001984 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001985 refreshArgs.outputColorSetting = useColorManagement
1986 ? mDisplayColorSetting
1987 : compositionengine::OutputColorSetting::kUnmanaged;
1988 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1989 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001990
1991 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1992 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001993 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001994
1995 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1996 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1997 mDrawingState.colorMatrixChanged = false;
1998 }
1999
2000 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2001
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002002 if (mDebugRegion != 0) {
2003 refreshArgs.devOptFlashDirtyRegionsDelay =
2004 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2005 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002006
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002007 mGeometryInvalid = false;
2008
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002009 // Store the present time just before calling to the composition engine so we could notify
2010 // the scheduler.
2011 const auto presentTime = systemTime();
2012
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002013 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002014 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2015 // Reset the frame start time now that we've recorded this frame.
2016 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002017
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002018 mScheduler->onDisplayRefreshed(presentTime);
2019
David Sodmanfa9b2af2017-12-24 13:28:59 -08002020 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002021 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002022
Lloyd Pique66d68602019-02-13 14:23:31 -08002023 mHadClientComposition =
2024 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2025 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002026 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2027 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002028 });
2029 mHadDeviceComposition =
2030 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2031 auto& displayDevice = tokenDisplayPair.second;
2032 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2033 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002034 mReusedClientComposition =
2035 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2036 auto& displayDevice = tokenDisplayPair.second;
2037 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2038 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002039
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002040 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002041
David Sodman7e4ae112018-02-09 15:02:28 -08002042 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002043 if (mVisibleRegionsDirty) {
2044 mVisibleRegionsDirty = false;
2045 if (mTracingEnabled) {
2046 mTracing.notify("visibleRegionsDirty");
2047 }
2048 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002049
2050 if (mCompositionEngine->needsAnotherUpdate()) {
2051 signalLayerUpdate();
2052 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002053}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002054
David Sodmanfa9b2af2017-12-24 13:28:59 -08002055
2056bool SurfaceFlinger::handleMessageInvalidate() {
2057 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002058 bool refreshNeeded = handlePageFlip();
2059
Vishnu Nair4351ad52019-02-11 14:13:02 -08002060 if (mVisibleRegionsDirty) {
2061 computeLayerBounds();
2062 }
2063
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002064 for (auto& layer : mLayersPendingRefresh) {
2065 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002066 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002067 invalidateLayerStack(layer, visibleReg);
2068 }
2069 mLayersPendingRefresh.clear();
2070 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002071}
2072
Ana Krulece588e312018-09-18 12:32:24 -07002073void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2074 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002075 // Update queue of past composite+present times and determine the
2076 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002077 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002078 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002079 while (!getBE().mCompositePresentTimes.empty()) {
2080 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002081 // Cached values should have been updated before calling this method,
2082 // which helps avoid duplicate syscalls.
2083 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2084 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2085 break;
2086 }
2087 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002088 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002089 }
2090
2091 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002092 while (getBE().mCompositePresentTimes.size() > 16) {
2093 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002094 }
2095
Ana Krulece588e312018-09-18 12:32:24 -07002096 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002097}
2098
Ana Krulece588e312018-09-18 12:32:24 -07002099void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2100 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002101 // Integer division and modulo round toward 0 not -inf, so we need to
2102 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002103 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2104 ? (stats.vsyncPeriod -
2105 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2106 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002107
Ady Abraham9e16a482019-12-03 17:19:41 -08002108 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002109 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002110 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002111 }
2112
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002113 // Snap the latency to a value that removes scheduling jitter from the
2114 // composition and present times, which often have >1ms of jitter.
2115 // Reducing jitter is important if an app attempts to extrapolate
2116 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002117 // Snapping also allows an app to precisely calculate
2118 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002119 nsecs_t bias = stats.vsyncPeriod / 2;
2120 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2121 nsecs_t snappedCompositeToPresentLatency =
2122 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002123
David Sodman99974d22017-11-28 12:04:33 -08002124 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002125 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2126 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002127 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002128}
2129
David Sodman2b406362017-12-15 13:33:47 -08002130void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002131{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002132 ATRACE_CALL();
2133 ALOGV("postComposition");
2134
Brian Andersonf6386862016-10-31 16:34:13 -07002135 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002136 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002137 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002138 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002139 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002140 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002141
David Sodman73beded2017-11-15 11:56:06 -08002142 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002143 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002144 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002145 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002146 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2147 ->getRenderSurface()
2148 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002149 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002150 } else {
2151 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2152 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002153
David Sodman73beded2017-11-15 11:56:06 -08002154 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002155 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2156 mPreviousPresentFences[0] = displayDevice
2157 ? getHwComposer().getPresentFence(*displayDevice->getId())
2158 : Fence::NO_FENCE;
2159 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002160 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002161
Ana Krulece588e312018-09-18 12:32:24 -07002162 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002163 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002164
Lloyd Piqueab039b52019-02-13 14:22:42 -08002165 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2166 // be sampled a little later than when we started doing work for this frame,
2167 // but that should be okay since updateCompositorTiming has snapping logic.
2168 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2169 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002170 CompositorTiming compositorTiming;
2171 {
David Sodman99974d22017-11-28 12:04:33 -08002172 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2173 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002174 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002175
Edgar Arriaga844fa672020-01-16 14:21:42 -08002176 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002177 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2178 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002179 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002180 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002181 }
Robert Carr2047fae2016-11-28 14:09:09 -08002182 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002183
Ady Abraham92fa2f42020-02-11 15:33:56 -08002184 if (displayDevice && displayDevice->isPrimary() &&
2185 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002186 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002187 }
2188
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002189 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002190 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2191 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002192 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002193 }
2194 }
2195
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002196 if (mAnimCompositionPending) {
2197 mAnimCompositionPending = false;
2198
Brian Anderson4e606e32017-03-16 15:34:57 -07002199 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002200 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002201 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002202 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002203 // The HWC doesn't support present fences, so use the refresh
2204 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002205 const nsecs_t presentTime =
2206 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002207 mAnimFrameTracker.setActualPresentTime(presentTime);
2208 }
2209 mAnimFrameTracker.advanceFrame();
2210 }
Dan Stozab90cf072015-03-05 11:05:59 -08002211
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002212 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002213 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002214 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002215 }
2216
Vishnu Nair9b079a22020-01-21 14:36:08 -08002217 if (mReusedClientComposition) {
2218 mTimeStats->incrementClientCompositionReusedFrames();
2219 }
2220
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002221 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002222
Alec Mouri717bcb62020-02-10 17:07:19 -08002223 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2224 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2225 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2226
Lloyd Pique32cbe282018-10-19 13:09:22 -07002227 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2228 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002229 return;
2230 }
2231
2232 nsecs_t currentTime = systemTime();
2233 if (mHasPoweredOff) {
2234 mHasPoweredOff = false;
2235 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002236 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002237 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002238 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2239 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002240 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002241 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002242 }
David Sodman4a36e932017-11-07 14:29:47 -08002243 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002244 }
David Sodman4a36e932017-11-07 14:29:47 -08002245 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002246
2247 {
2248 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002249 if (mTexturePool.size() < mTexturePoolSize) {
2250 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002251 const size_t offset = mTexturePool.size();
2252 mTexturePool.resize(mTexturePoolSize);
2253 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2254 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002255 } else if (mTexturePool.size() > mTexturePoolSize) {
2256 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2257 const size_t offset = mTexturePoolSize;
2258 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2259 mTexturePool.resize(mTexturePoolSize);
2260 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002261 }
2262 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002263
Ady Abrahambe0f9482019-04-24 15:41:53 -07002264 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002265 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002266
Kevin DuBois413287f2019-02-25 08:46:47 -08002267 if (mLumaSampling && mRegionSamplingThread) {
2268 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002269 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002270
2271 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2272 // side-effect of getTotalSize(), so we check that again here
2273 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002274 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002275 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2276 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002277}
2278
Vishnu Nair4351ad52019-02-11 14:13:02 -08002279void SurfaceFlinger::computeLayerBounds() {
2280 for (const auto& pair : mDisplays) {
2281 const auto& displayDevice = pair.second;
2282 const auto display = displayDevice->getCompositionDisplay();
2283 for (const auto& layer : mDrawingState.layersSortedByZ) {
2284 // only consider the layers on the given layer stack
2285 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002286 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002287 }
2288
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002289 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2290 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002291 }
2292 }
2293}
2294
David Sodmanfa9b2af2017-12-24 13:28:59 -08002295void SurfaceFlinger::postFrame()
2296{
2297 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002298 const auto display = getDefaultDisplayDeviceLocked();
2299 if (display && getHwComposer().isConnected(*display->getId())) {
2300 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002301 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2302 logFrameStats();
2303 }
2304 }
2305}
2306
Mathias Agopian87baae12012-07-31 12:38:26 -07002307void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002308{
Mathias Agopian841cde52012-03-01 15:44:37 -08002309 ATRACE_CALL();
2310
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002311 // here we keep a copy of the drawing state (that is the state that's
2312 // going to be overwritten by handleTransactionLocked()) outside of
2313 // mStateLock so that the side-effects of the State assignment
2314 // don't happen with mStateLock held (which can cause deadlocks).
2315 State drawingState(mDrawingState);
2316
Mathias Agopianca4d3602011-05-19 15:38:14 -07002317 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002318 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002319
Mathias Agopianca4d3602011-05-19 15:38:14 -07002320 // Here we're guaranteed that some transaction flags are set
2321 // so we can call handleTransactionLocked() unconditionally.
2322 // We call getTransactionFlags(), which will also clear the flags,
2323 // with mStateLock held to guarantee that mCurrentState won't change
2324 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002325
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002326 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002327 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002328 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002329
Mathias Agopianca4d3602011-05-19 15:38:14 -07002330 mDebugInTransaction = 0;
2331 invalidateHwcGeometry();
2332 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002333}
2334
Lloyd Piqueba04e622017-12-14 17:11:26 -08002335void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2336 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002337 const std::optional<DisplayIdentificationInfo> info =
2338 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002339
Dominik Laskowski075d3172018-05-24 15:50:06 -07002340 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002341 continue;
2342 }
2343
Dominik Laskowski55c85402020-01-21 16:25:47 -08002344 const DisplayId displayId = info->id;
2345 const auto it = mPhysicalDisplayTokens.find(displayId);
2346
Lloyd Piqueba04e622017-12-14 17:11:26 -08002347 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002348 if (it == mPhysicalDisplayTokens.end()) {
2349 ALOGV("Creating display %s", to_string(displayId).c_str());
2350
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002351 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002352 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002353 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002354
Dominik Laskowski075d3172018-05-24 15:50:06 -07002355 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002356 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002357 state.isSecure = true; // All physical displays are currently considered secure.
2358 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002359
2360 sp<IBinder> token = new BBinder();
2361 mCurrentState.displays.add(token, state);
2362 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2363
Dominik Laskowski075d3172018-05-24 15:50:06 -07002364 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002365 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002366 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002367 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002368
Dominik Laskowski55c85402020-01-21 16:25:47 -08002369 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002370 if (index >= 0) {
2371 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2372 mInterceptor->saveDisplayDeletion(state.sequenceId);
2373 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002374 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002375 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002376 }
2377
2378 processDisplayChangesLocked();
2379 }
2380
2381 mPendingHotplugEvents.clear();
2382}
2383
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002384void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002385 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2386 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002387}
2388
Lloyd Pique99d3da52018-01-22 17:48:03 -08002389sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002390 const wp<IBinder>& displayToken,
2391 std::shared_ptr<compositionengine::Display> compositionDisplay,
Lloyd Pique542307f2018-10-19 13:24:08 -07002392 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002393 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002394 auto displayId = compositionDisplay->getDisplayId();
2395 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002396 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002397 creationArgs.isSecure = state.isSecure;
2398 creationArgs.displaySurface = dispSurface;
2399 creationArgs.hasWideColorGamut = false;
2400 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002401
Dominik Laskowski55c85402020-01-21 16:25:47 -08002402 if (const auto& physical = state.physical) {
2403 creationArgs.connectionType = physical->type;
2404 }
2405
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002406 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002407 creationArgs.isPrimary = isInternalDisplay;
2408
2409 if (useColorManagement && displayId) {
2410 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002411 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002412 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002413 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002414 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002415
Dominik Laskowski7e045462018-05-30 13:02:02 -07002416 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002417 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002418 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002419 }
tangrobin6753a022018-08-10 10:58:54 +08002420 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002421
Dominik Laskowski075d3172018-05-24 15:50:06 -07002422 if (displayId) {
2423 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002424 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002425 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002426 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002427
Lloyd Pique90c115d2018-09-18 21:39:42 -07002428 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002429 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002430 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002431
Lloyd Pique99d3da52018-01-22 17:48:03 -08002432 // Make sure that composition can never be stalled by a virtual display
2433 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002434 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002435 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002436 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2437 }
2438
Dominik Laskowski718f9602019-11-09 20:01:35 -08002439 creationArgs.physicalOrientation =
2440 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002441
Lloyd Pique99d3da52018-01-22 17:48:03 -08002442 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002443 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002444
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002445 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002446
2447 if (maxFrameBufferAcquiredBuffers >= 3) {
2448 nativeWindowSurface->preallocateBuffers();
2449 }
2450
2451 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002452 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002453 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002454 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002455 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002456 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002457 display->getCompositionDisplay()->setColorProfile(
2458 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2459 RenderIntent::COLORIMETRIC,
2460 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002461 if (!state.isVirtual()) {
2462 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002463 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2464 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002465 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002466
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002467 display->setLayerStack(state.layerStack);
2468 display->setProjection(state.orientation, state.viewport, state.frame);
2469 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002470
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002471 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002472}
2473
Lloyd Pique347200f2017-12-14 17:00:15 -08002474void SurfaceFlinger::processDisplayChangesLocked() {
2475 // here we take advantage of Vector's copy-on-write semantics to
2476 // improve performance by skipping the transaction entirely when
2477 // know that the lists are identical
2478 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2479 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2480 if (!curr.isIdenticalTo(draw)) {
2481 mVisibleRegionsDirty = true;
2482 const size_t cc = curr.size();
2483 size_t dc = draw.size();
2484
2485 // find the displays that were removed
2486 // (ie: in drawing state but not in current state)
2487 // also handle displays that changed
2488 // (ie: displays that are in both lists)
2489 for (size_t i = 0; i < dc;) {
2490 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2491 if (j < 0) {
2492 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002493 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002494 // Save display ID before disconnecting.
2495 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002496 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002497
2498 if (!display->isVirtual()) {
2499 LOG_ALWAYS_FATAL_IF(!displayId);
2500 dispatchDisplayHotplugEvent(displayId->value, false);
2501 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002502 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002503
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002504 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002505 } else {
2506 // this display is in both lists. see if something changed.
2507 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002508 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002509 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2510 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2511 if (state_binder != draw_binder) {
2512 // changing the surface is like destroying and
2513 // recreating the DisplayDevice, so we just remove it
2514 // from the drawing state, so that it get re-added
2515 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002516 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002517 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002518 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002519 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002520 mDrawingState.displays.removeItemsAt(i);
2521 dc--;
2522 // at this point we must loop to the next item
2523 continue;
2524 }
2525
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002526 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002527 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002528 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002529 }
2530 if ((state.orientation != draw[i].orientation) ||
2531 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002532 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002533 }
2534 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002535 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002536 if (display->isPrimary()) {
2537 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2538 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002539 }
2540 }
2541 }
2542 ++i;
2543 }
2544
2545 // find displays that were added
2546 // (ie: in current state but not in drawing state)
2547 for (size_t i = 0; i < cc; i++) {
2548 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2549 const DisplayDeviceState& state(curr[i]);
2550
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002551 int width = 0;
2552 int height = 0;
2553 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2554 if (state.physical) {
2555 const auto& activeConfig =
2556 getCompositionEngine().getHwComposer().getActiveConfig(
2557 state.physical->id);
2558 width = activeConfig->getWidth();
2559 height = activeConfig->getHeight();
2560 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2561 } else if (state.surface != nullptr) {
2562 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2563 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2564 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2565 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2566 int intPixelFormat;
2567 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2568 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2569 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2570 } else {
2571 // Virtual displays without a surface are dormant:
2572 // they have external state (layer stack, projection,
2573 // etc.) but no internal state (i.e. a DisplayDevice).
2574 continue;
2575 }
2576
2577 compositionengine::DisplayCreationArgsBuilder builder;
2578 if (const auto& physical = state.physical) {
2579 builder.setPhysical({physical->id, physical->type});
2580 }
2581 builder.setPixels(ui::Size(width, height));
2582 builder.setPixelFormat(pixelFormat);
2583 builder.setIsSecure(state.isSecure);
2584 builder.setLayerStackId(state.layerStack);
2585 builder.setPowerAdvisor(&mPowerAdvisor);
2586 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays ||
2587 getHwComposer().isUsingVrComposer());
2588 builder.setName(state.displayName);
2589 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2590
Lloyd Pique542307f2018-10-19 13:24:08 -07002591 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002592 sp<IGraphicBufferProducer> producer;
2593 sp<IGraphicBufferProducer> bqProducer;
2594 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002595 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002596
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002597 std::optional<DisplayId> displayId = compositionDisplay->getId();
2598
Dominik Laskowski663bd282018-04-19 15:26:54 -07002599 if (state.isVirtual()) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002600 sp<VirtualDisplaySurface> vds =
2601 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
2602 bqProducer, bqConsumer, state.displayName);
Lloyd Pique347200f2017-12-14 17:00:15 -08002603
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002604 dispSurface = vds;
2605 producer = vds;
Lloyd Pique347200f2017-12-14 17:00:15 -08002606 } else {
2607 ALOGE_IF(state.surface != nullptr,
2608 "adding a supported display, but rendering "
2609 "surface is provided (%p), ignoring it",
2610 state.surface.get());
2611
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002612 LOG_ALWAYS_FATAL_IF(!displayId);
Brian Lindahla13f2d52020-03-05 11:54:17 +01002613 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2614 maxGraphicsWidth, maxGraphicsHeight);
Lloyd Pique347200f2017-12-14 17:00:15 -08002615 producer = bqProducer;
2616 }
2617
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002618 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002619 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002620 mDisplays.emplace(displayToken,
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002621 setupNewDisplayDeviceInternal(displayToken,
2622 compositionDisplay, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002623 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002624 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002625 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002626 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002627 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002628
2629 const auto displayDevice = mDisplays[displayToken];
2630 if (displayDevice->isPrimary()) {
2631 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2632 displayDevice->getHeight());
2633 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002634 }
2635 }
2636 }
2637 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002638
2639 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002640}
2641
Mathias Agopian87baae12012-07-31 12:38:26 -07002642void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002643{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002644 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2645
Dan Stoza7dde5992015-05-22 09:51:44 -07002646 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002647 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002648 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002649 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002650
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002651 /*
2652 * Traversal of the children
2653 * (perform the transaction for each of them if needed)
2654 */
2655
Marissa Wall06255332019-03-27 13:48:27 -07002656 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002657 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002659 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002660
2661 const uint32_t flags = layer->doTransaction(0);
2662 if (flags & Layer::eVisibleRegion)
2663 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002664
2665 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002666 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002667 }
Robert Carr2047fae2016-11-28 14:09:09 -08002668 });
Marissa Wall06255332019-03-27 13:48:27 -07002669 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002670 }
2671
2672 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002673 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002674 */
2675
Mathias Agopiane57f2922012-08-09 16:29:12 -07002676 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002677 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002678 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002679 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002680
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002681 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002682 // The transform hint might have changed for some layers
2683 // (either because a display has changed, or because a layer
2684 // as changed).
2685 //
2686 // Walk through all the layers in currentLayers,
2687 // and update their transform hint.
2688 //
2689 // If a layer is visible only on a single display, then that
2690 // display is used to calculate the hint, otherwise we use the
2691 // default display.
2692 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002693 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002694 // the hint is set before we acquire a buffer from the surface texture.
2695 //
2696 // NOTE: layer transactions have taken place already, so we use their
2697 // drawing state. However, SurfaceFlinger's own transaction has not
2698 // happened yet, so we must use the current state layer list
2699 // (soon to become the drawing state list).
2700 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002701 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002702 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002703 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002704 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002705 // NOTE: we rely on the fact that layers are sorted by
2706 // layerStack first (so we don't have to traverse the list
2707 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002708 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002709 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002710 currentlayerStack = layerStack;
2711 // figure out if this layerstack is mirrored
2712 // (more than one display) if so, pick the default display,
2713 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002714 hintDisplay = nullptr;
2715 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002716 if (display->getCompositionDisplay()
2717 ->belongsInOutput(layer->getLayerStack(),
2718 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002719 if (hintDisplay) {
2720 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002721 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002722 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002723 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002724 }
2725 }
2726 }
2727 }
Chet Haase91d25932013-04-11 15:24:55 -07002728
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002729 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002730 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2731 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002732
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002733 // could be null when this layer is using a layerStack
2734 // that is not visible on any display. Also can occur at
2735 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002736 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002737 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002738
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002739 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002740 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002741 if (hintDisplay) {
2742 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002743 }
Robert Carr2047fae2016-11-28 14:09:09 -08002744
2745 first = false;
2746 });
Mathias Agopian84300952012-11-21 16:02:13 -08002747 }
2748
2749
Mathias Agopian3559b072012-08-15 13:46:03 -07002750 /*
2751 * Perform our own transaction if needed
2752 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002753
2754 if (mLayersAdded) {
2755 mLayersAdded = false;
2756 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002757 mVisibleRegionsDirty = true;
2758 }
2759
2760 // some layers might have been removed, so
2761 // we need to update the regions they're exposing.
2762 if (mLayersRemoved) {
2763 mLayersRemoved = false;
2764 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002765 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002766 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002767 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002768 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002769 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002770 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002771 }
Robert Carr2047fae2016-11-28 14:09:09 -08002772 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002773 }
2774
Vishnu Nairec0ab382019-02-13 15:32:56 -08002775 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002776 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002777}
2778
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002779void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002780 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002781 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002782 return;
2783 }
2784
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002785 if (mVisibleRegionsDirty || mInputInfoChanged) {
2786 mInputInfoChanged = false;
2787 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002788 } else if (mInputWindowCommands.syncInputWindows) {
2789 // If the caller requested to sync input windows, but there are no
2790 // changes to input windows, notify immediately.
2791 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002792 }
2793
Arthur Hung6cbb9752019-09-05 16:38:18 +08002794 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002795}
2796
2797void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002798 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002799
Robert Carra1257842020-01-31 13:48:28 -08002800 // We use a simple caching algorithm here. mInputDirty begins as true,
2801 // after we call setInputWindows we set it to false, so
2802 // in the future we wont call it again.. We set input dirty to true again
2803 // when any layer that hasInput() has a transaction performed on it
2804 // or when any parent or relative parent of such a layer has a transaction
2805 // performed on it. Not all of these transactions will really result in
2806 // input changes but all input changes will spring from these transactions
2807 // so the cache is safe but not optimal. It seems like it might be annoyingly
2808 // costly to cache and comapre the actual InputWindowHandle vector though.
2809 if (!mInputDirty) {
2810 return;
2811 }
2812
Robert Carr720e5062018-07-30 17:45:14 -07002813 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2814 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002815 // When calculating the screen bounds we ignore the transparent region since it may
2816 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002817 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002818 }
2819 });
chaviw291d88a2019-02-14 10:33:58 -08002820
2821 mInputFlinger->setInputWindows(inputHandles,
2822 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2823 : nullptr);
Robert Carra1257842020-01-31 13:48:28 -08002824
2825 mInputDirty = false;
Robert Carr720e5062018-07-30 17:45:14 -07002826}
2827
Vishnu Nairec0ab382019-02-13 15:32:56 -08002828void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002829 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002830 mPendingInputWindowCommands.clear();
2831}
2832
Riley Andrews03414a12014-07-01 14:22:59 -07002833void SurfaceFlinger::updateCursorAsync()
2834{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002835 compositionengine::CompositionRefreshArgs refreshArgs;
2836 for (const auto& [_, display] : mDisplays) {
2837 if (display->getId()) {
2838 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002839 }
2840 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002841
2842 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002843}
2844
Ady Abraham2139f732019-11-13 18:56:40 -08002845void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002846 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2847 // If this is called from the main thread mStateLock must be locked before
2848 // Currently the only way to call this function from the main thread is from
2849 // Sheduler::chooseRefreshRateForContent
2850
2851 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002852 changeRefreshRateLocked(refreshRate, event);
2853}
2854
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002855void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2856 if (mScheduler) {
2857 // In practice it's not allowed to hotplug in/out the primary display once it's been
2858 // connected during startup, but some tests do it, so just warn and return.
2859 ALOGW("Can't re-init scheduler");
2860 return;
2861 }
2862
Ady Abraham2139f732019-11-13 18:56:40 -08002863 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002864 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002865 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002866 primaryDisplayId),
2867 currentConfig);
2868 mRefreshRateStats =
2869 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2870 currentConfig, HWC_POWER_MODE_OFF);
2871 mRefreshRateStats->setConfigMode(currentConfig);
2872
Ady Abraham9e16a482019-12-03 17:19:41 -08002873 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2874
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002875 // start the EventThread
2876 mScheduler =
2877 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002878 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002879 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002880 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002881 impl::EventThread::InterceptVSyncsCallback());
2882 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002883 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002884 [this](nsecs_t timestamp) {
2885 mInterceptor->saveVSyncEvent(timestamp);
2886 });
2887
2888 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2889 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002890 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002891
2892 mRegionSamplingThread =
2893 new RegionSamplingThread(*this, *mScheduler,
2894 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002895 // Dispatch a config change request for the primary display on scheduler
2896 // initialization, so that the EventThreads always contain a reference to a
2897 // prior configuration.
2898 //
2899 // This is a bit hacky, but this avoids a back-pointer into the main SF
2900 // classes from EventThread, and there should be no run-time binder cost
2901 // anyway since there are no connected apps at this point.
2902 const nsecs_t vsyncPeriod =
2903 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2904 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2905 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002906}
2907
Mathias Agopian4fec8732012-06-29 14:12:52 -07002908void SurfaceFlinger::commitTransaction()
2909{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002910 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002911
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002912 mTransactionPending = false;
2913 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002914 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002915}
2916
Lloyd Pique58e24a32019-08-01 15:50:14 -07002917void SurfaceFlinger::commitTransactionLocked() {
2918 if (!mLayersPendingRemoval.isEmpty()) {
2919 // Notify removed layers now that they can't be drawn from
2920 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002921 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002922
2923 // Ensure any buffers set to display on any children are released.
2924 if (l->isRemovedFromCurrentState()) {
2925 l->latchAndReleaseBuffer();
2926 }
2927
2928 // If the layer has been removed and has no parent, then it will not be reachable
2929 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2930 // ensure we can copy its current to drawing state.
2931 if (!l->getParent()) {
2932 mOffscreenLayers.emplace(l.get());
2933 }
2934 }
2935 mLayersPendingRemoval.clear();
2936 }
2937
2938 // If this transaction is part of a window animation then the next frame
2939 // we composite should be considered an animation as well.
2940 mAnimCompositionPending = mAnimTransactionPending;
2941
2942 mDrawingState = mCurrentState;
2943 // clear the "changed" flags in current state
2944 mCurrentState.colorMatrixChanged = false;
2945
Edgar Arriaga844fa672020-01-16 14:21:42 -08002946 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002947 layer->commitChildList();
2948
2949 // If the layer can be reached when traversing mDrawingState, then the layer is no
2950 // longer offscreen. Remove the layer from the offscreenLayer set.
2951 if (mOffscreenLayers.count(layer)) {
2952 mOffscreenLayers.erase(layer);
2953 }
2954 });
2955
2956 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002957 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002958}
2959
Nataniel Borges2b796da2019-02-15 13:32:18 -08002960void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2961 if (mTracingEnabledChanged) {
2962 mTracingEnabled = mTracing.isEnabled();
2963 mTracingEnabledChanged = false;
2964 }
2965
2966 // Synchronize with Tracing thread
2967 std::unique_lock<std::mutex> lock;
2968 if (mTracingEnabled) {
2969 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2970 }
2971
2972 lockedOperation();
2973
2974 // Synchronize with Tracing thread
2975 if (mTracingEnabled) {
2976 lock.unlock();
2977 }
2978}
2979
chaviw74d90ad2019-04-26 14:45:26 -07002980void SurfaceFlinger::commitOffscreenLayers() {
2981 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002982 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002983 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2984 if (!trFlags) return;
2985
2986 layer->doTransaction(0);
2987 layer->commitChildList();
2988 });
2989 }
2990}
2991
Chia-I Wuab0c3192017-08-01 11:29:00 -07002992void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002993 for (const auto& [token, displayDevice] : mDisplays) {
2994 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002995 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002996 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002997 }
2998 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002999}
3000
Dan Stoza6b9454d2014-11-07 16:00:59 -08003001bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003002{
Ady Abraham09bd3922019-04-08 10:44:56 -07003003 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003004 ALOGV("handlePageFlip");
3005
Brian Andersond6927fb2016-07-23 23:37:30 -07003006 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003007
Mathias Agopian4fec8732012-06-29 14:12:52 -07003008 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003009 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003010 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003011
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003012 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3013
Eric Penner51c59cd2014-07-28 19:51:58 -07003014 // Store the set of layers that need updates. This set must not change as
3015 // buffers are being latched, as this could result in a deadlock.
3016 // Example: Two producers share the same command stream and:
3017 // 1.) Layer 0 is latched
3018 // 2.) Layer 0 gets a new frame
3019 // 2.) Layer 1 gets a new frame
3020 // 3.) Layer 1 is latched.
3021 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3022 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003023 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003024 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003025 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003026 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003027 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003028 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003029 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003030 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003031 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003032 } else {
3033 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003034 }
Robert Carr2047fae2016-11-28 14:09:09 -08003035 });
3036
chaviw49a108c2019-08-12 11:23:06 -07003037 // The client can continue submitting buffers for offscreen layers, but they will not
3038 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3039 // layers to ensure dequeueBuffer doesn't block indefinitely.
3040 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003041 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003042 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3043 }
3044
Lloyd Piquef2c79392018-12-20 16:23:33 -08003045 if (!mLayersWithQueuedFrames.empty()) {
3046 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3047 // writes to Layer current state. See also b/119481871
3048 Mutex::Autolock lock(mStateLock);
3049
3050 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003051 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003052 mLayersPendingRefresh.push_back(layer);
3053 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003054 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003055 if (layer->isBufferLatched()) {
3056 newDataLatched = true;
3057 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003058 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003059 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003060
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003061 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003062
3063 // If we will need to wake up at some time in the future to deal with a
3064 // queued frame that shouldn't be displayed during this vsync period, wake
3065 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003066 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003067 signalLayerUpdate();
3068 }
3069
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003070 // enter boot animation on first buffer latch
3071 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3072 ALOGI("Enter boot animation");
3073 mBootStage = BootStage::BOOTANIMATION;
3074 }
3075
Edgar Arriaga844fa672020-01-16 14:21:42 -08003076 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003077
Dan Stoza6b9454d2014-11-07 16:00:59 -08003078 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003079 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003080}
3081
Mathias Agopianad456f92011-01-13 17:53:01 -08003082void SurfaceFlinger::invalidateHwcGeometry()
3083{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003084 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003085}
3086
Robert Carrc0df3122019-04-11 13:18:21 -07003087status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3088 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3089 const sp<IBinder>& parentHandle,
3090 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003091 // add this layer to the current state list
3092 {
3093 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003094 sp<Layer> parent;
3095 if (parentHandle != nullptr) {
3096 parent = fromHandle(parentHandle);
3097 if (parent == nullptr) {
3098 return NAME_NOT_FOUND;
3099 }
3100 } else {
3101 parent = parentLayer;
3102 }
3103
Ady Abraham0a525092020-03-03 12:51:24 -08003104 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003105 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003106 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003107 return NO_MEMORY;
3108 }
Robert Carrc0df3122019-04-11 13:18:21 -07003109
3110 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3111
Robert Carrb89ea9d2018-12-10 13:01:14 -08003112 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003113 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003114 } else if (parent == nullptr) {
3115 lbc->onRemovedFromCurrentState();
3116 } else if (parent->isRemovedFromCurrentState()) {
3117 parent->addChild(lbc);
3118 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003119 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003120 parent->addChild(lbc);
3121 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003122
Yiwei Zhang243b3782018-05-15 17:40:04 -07003123 if (gbc != nullptr) {
3124 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3125 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3126 mMaxGraphicBufferProducerListSize,
3127 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3128 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003129 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003130 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003131 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003132 }
3133
Mathias Agopian96f08192010-06-02 23:28:45 -07003134 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003135 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003136
Dan Stoza7d89d062015-04-30 13:29:25 -07003137 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003138}
3139
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003140uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003141 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003142}
3143
Mathias Agopian3f844832013-08-07 21:24:32 -07003144uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003145 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003146}
3147
Mathias Agopian3f844832013-08-07 21:24:32 -07003148uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003149 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003150}
3151
3152uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003153 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003154 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003155 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003156 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003157 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003158 }
3159 return old;
3160}
3161
Marissa Wall713b63f2018-10-17 15:42:43 -07003162bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003163 // to prevent onHandleDestroyed from being called while the lock is held,
3164 // we must keep a copy of the transactions (specifically the composer
3165 // states) around outside the scope of the lock
3166 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003167 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003168 {
3169 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003170
Valerie Haufce31b82019-04-30 16:41:14 -07003171 auto it = mTransactionQueues.begin();
3172 while (it != mTransactionQueues.end()) {
3173 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003174
Valerie Haufce31b82019-04-30 16:41:14 -07003175 while (!transactionQueue.empty()) {
3176 const auto& transaction = transactionQueue.front();
3177 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003178 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003179 transaction.states)) {
3180 setTransactionFlags(eTransactionFlushNeeded);
3181 break;
3182 }
3183 transactions.push_back(transaction);
3184 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3185 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003186 transaction.buffer, transaction.postTime,
3187 transaction.privileged, transaction.hasListenerCallbacks,
3188 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003189 transactionQueue.pop();
3190 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003191 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003192
Valerie Haufce31b82019-04-30 16:41:14 -07003193 if (transactionQueue.empty()) {
3194 it = mTransactionQueues.erase(it);
3195 mTransactionCV.broadcast();
3196 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003197 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003198 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003199 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003200 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003201 return flushedATransaction;
3202}
3203
3204bool SurfaceFlinger::transactionFlushNeeded() {
3205 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003206}
3207
chaviwca27f252018-02-06 16:46:39 -08003208
Marissa Wall17b4e452018-12-26 16:32:34 -08003209bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003210 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003211 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003212 if (!useCachedExpectedPresentTime)
3213 populateExpectedPresentTime();
3214
3215 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003216 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3217 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3218 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3219 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3220 return false;
3221 }
3222
Marissa Wall713b63f2018-10-17 15:42:43 -07003223 for (const ComposerState& state : states) {
3224 const layer_state_t& s = state.state;
3225 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3226 continue;
3227 }
3228 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003229 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003230 }
3231 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003232 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003233}
3234
Valerie Hau9dab9732019-08-20 09:29:25 -07003235void SurfaceFlinger::setTransactionState(
3236 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3237 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3238 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3239 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003240 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003241
Valerie Haubc6ddb12019-03-08 11:10:15 -08003242 const int64_t postTime = systemTime();
3243
Robert Carr14167e02019-02-13 13:50:55 -08003244 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3245
Mathias Agopian698c0872011-06-28 19:09:31 -07003246 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003247
Marissa Wall713b63f2018-10-17 15:42:43 -07003248 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003249 auto itr = mTransactionQueues.find(applyToken);
3250 // if this is an animation frame, wait until prior animation frame has
3251 // been applied by SF
3252 if (flags & eAnimation) {
3253 while (itr != mTransactionQueues.end()) {
3254 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3255 if (CC_UNLIKELY(err != NO_ERROR)) {
3256 ALOGW_IF(err == TIMED_OUT,
3257 "setTransactionState timed out "
3258 "waiting for animation frame to apply");
3259 break;
3260 }
3261 itr = mTransactionQueues.find(applyToken);
3262 }
3263 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003264
3265 // Expected present time is computed and cached on invalidate, so it may be stale.
3266 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3267 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003268 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003269 uncacheBuffer, postTime, privileged,
3270 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003271 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003272 return;
3273 }
3274
Valerie Haubc6ddb12019-03-08 11:10:15 -08003275 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003276 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3277 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003278}
3279
Valerie Hau9dab9732019-08-20 09:29:25 -07003280void SurfaceFlinger::applyTransactionState(
3281 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3282 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3283 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3284 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3285 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003286 uint32_t transactionFlags = 0;
3287
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003288 if (flags & eAnimation) {
3289 // For window updates that are part of an animation we must wait for
3290 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003291 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003292 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003293 if (CC_UNLIKELY(err != NO_ERROR)) {
3294 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003295 // caller after a few seconds.
3296 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3297 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003298 mAnimTransactionPending = false;
3299 break;
3300 }
3301 }
3302 }
3303
chaviwca27f252018-02-06 16:46:39 -08003304 for (const DisplayState& display : displays) {
3305 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003306 }
3307
Valerie Hau9dab9732019-08-20 09:29:25 -07003308 // start and end registration for listeners w/ no surface so they can get their callback. Note
3309 // that listeners with SurfaceControls will start registration during setClientStateLocked
3310 // below.
3311 for (const auto& listener : listenerCallbacks) {
3312 mTransactionCompletedThread.startRegistration(listener);
3313 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003314 }
3315
Valerie Hau9dab9732019-08-20 09:29:25 -07003316 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003317 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003318 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003319 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3320 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003321 }
3322
Valerie Hau9dab9732019-08-20 09:29:25 -07003323 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003324 mTransactionCompletedThread.endRegistration(listenerCallback);
3325 }
3326
Marissa Walle2ffb422018-10-12 11:33:52 -07003327 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003328 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003329 mTransactionCompletedThread.sendCallbacks();
3330 }
3331 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003332
chaviw273171b2018-12-26 11:46:30 -08003333 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3334
Marissa Wall947d34e2019-03-29 14:03:53 -07003335 if (uncacheBuffer.isValid()) {
3336 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003337 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003338 }
3339
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003340 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3341 // anyway. This can be used as a flush mechanism for previous async transactions.
3342 // Empty animation transaction can be used to simulate back-pressure, so also force a
3343 // transaction for empty animation transactions.
3344 if (transactionFlags == 0 &&
3345 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003346 transactionFlags = eTransactionNeeded;
3347 }
3348
Marissa Wall06255332019-03-27 13:48:27 -07003349 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3350 // so we don't have to wake up again next frame to preform an uneeded traversal.
3351 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3352 transactionFlags = transactionFlags & (~eTraversalNeeded);
3353 mTraversalNeededMainThread = true;
3354 }
3355
Mathias Agopian386aa982011-11-07 21:58:03 -08003356 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003357 if (mInterceptor->isEnabled()) {
3358 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003359 }
Irvel468051e2016-06-13 16:44:44 -07003360
Mathias Agopian386aa982011-11-07 21:58:03 -08003361 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003362 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3363 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003364 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003365
3366 // if this is a synchronous transaction, wait for it to take effect
3367 // before returning.
3368 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003369 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003370 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003371 if (flags & eAnimation) {
3372 mAnimTransactionPending = true;
3373 }
chaviw4fe36852019-04-15 16:25:49 -07003374 if (mPendingInputWindowCommands.syncInputWindows) {
3375 mPendingSyncInputWindows = true;
3376 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003377
3378 // applyTransactionState can be called by either the main SF thread or by
3379 // another process through setTransactionState. While a given process may wish
3380 // to wait on synchronous transactions, the main SF thread should never
3381 // be blocked. Therefore, we only wait if isMainThread is false.
3382 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003383 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3384 if (CC_UNLIKELY(err != NO_ERROR)) {
3385 // just in case something goes wrong in SF, return to the
3386 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003387 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3388 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003389 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003390 break;
3391 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003392 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003393 }
3394}
3395
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003396uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3397 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3398 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003399
Mathias Agopiane57f2922012-08-09 16:29:12 -07003400 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003401 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3402
3403 const uint32_t what = s.what;
3404 if (what & DisplayState::eSurfaceChanged) {
3405 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3406 state.surface = s.surface;
3407 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003408 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003409 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003410 if (what & DisplayState::eLayerStackChanged) {
3411 if (state.layerStack != s.layerStack) {
3412 state.layerStack = s.layerStack;
3413 flags |= eDisplayTransactionNeeded;
3414 }
3415 }
3416 if (what & DisplayState::eDisplayProjectionChanged) {
3417 if (state.orientation != s.orientation) {
3418 state.orientation = s.orientation;
3419 flags |= eDisplayTransactionNeeded;
3420 }
3421 if (state.frame != s.frame) {
3422 state.frame = s.frame;
3423 flags |= eDisplayTransactionNeeded;
3424 }
3425 if (state.viewport != s.viewport) {
3426 state.viewport = s.viewport;
3427 flags |= eDisplayTransactionNeeded;
3428 }
3429 }
3430 if (what & DisplayState::eDisplaySizeChanged) {
3431 if (state.width != s.width) {
3432 state.width = s.width;
3433 flags |= eDisplayTransactionNeeded;
3434 }
3435 if (state.height != s.height) {
3436 state.height = s.height;
3437 flags |= eDisplayTransactionNeeded;
3438 }
3439 }
3440
Mathias Agopiane57f2922012-08-09 16:29:12 -07003441 return flags;
3442}
3443
Robert Carr14167e02019-02-13 13:50:55 -08003444bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003445 IPCThreadState* ipc = IPCThreadState::self();
3446 const int pid = ipc->getCallingPid();
3447 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003448 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003449 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003450 return false;
3451 }
3452 return true;
3453}
3454
Marissa Wall3dad52d2019-03-22 14:03:19 -07003455uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003456 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3457 bool privileged,
3458 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003459 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003460
Valerie Hau9dab9732019-08-20 09:29:25 -07003461 for (auto& listener : s.listeners) {
3462 // note that startRegistration will not re-register if the listener has
3463 // already be registered for a prior surface control
3464 mTransactionCompletedThread.startRegistration(listener);
3465 listenerCallbacks.insert(listener);
3466 }
3467
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003468 sp<Layer> layer = nullptr;
3469 if (s.surface) {
3470 layer = fromHandle(s.surface);
3471 } else {
3472 // The client may provide us a null handle. Treat it as if the layer was removed.
3473 ALOGW("Attempt to set client state with a null layer handle");
3474 }
chaviw8b3871a2017-11-01 17:41:01 -07003475 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003476 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003477 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003478 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003479 }
chaviw8b3871a2017-11-01 17:41:01 -07003480 return 0;
3481 }
3482
chaviw8b3871a2017-11-01 17:41:01 -07003483 uint32_t flags = 0;
3484
Garfield Tan8a3083e2018-12-03 13:21:07 -08003485 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003486
3487 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3488 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003489 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003490 layer->pushPendingState();
3491 }
3492
Valerie Hau871d6352020-01-29 08:44:02 -08003493 // Only set by BLAST adapter layers
3494 if (what & layer_state_t::eProducerDisconnect) {
3495 layer->onDisconnect();
3496 }
3497
chaviw8b3871a2017-11-01 17:41:01 -07003498 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003499 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003500 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003501 }
chaviw8b3871a2017-11-01 17:41:01 -07003502 }
3503 if (what & layer_state_t::eLayerChanged) {
3504 // NOTE: index needs to be calculated before we update the state
3505 const auto& p = layer->getParent();
3506 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003507 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003508 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003509 mCurrentState.layersSortedByZ.removeAt(idx);
3510 mCurrentState.layersSortedByZ.add(layer);
3511 // we need traversal (state changed)
3512 // AND transaction (list changed)
3513 flags |= eTransactionNeeded|eTraversalNeeded;
3514 }
chaviw8b3871a2017-11-01 17:41:01 -07003515 } else {
3516 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003517 flags |= eTransactionNeeded|eTraversalNeeded;
3518 }
3519 }
chaviw8b3871a2017-11-01 17:41:01 -07003520 }
3521 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003522 // NOTE: index needs to be calculated before we update the state
3523 const auto& p = layer->getParent();
3524 if (p == nullptr) {
3525 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3526 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3527 mCurrentState.layersSortedByZ.removeAt(idx);
3528 mCurrentState.layersSortedByZ.add(layer);
3529 // we need traversal (state changed)
3530 // AND transaction (list changed)
3531 flags |= eTransactionNeeded|eTraversalNeeded;
3532 }
3533 } else {
3534 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3535 flags |= eTransactionNeeded|eTraversalNeeded;
3536 }
chaviw8b3871a2017-11-01 17:41:01 -07003537 }
3538 }
3539 if (what & layer_state_t::eSizeChanged) {
3540 if (layer->setSize(s.w, s.h)) {
3541 flags |= eTraversalNeeded;
3542 }
3543 }
3544 if (what & layer_state_t::eAlphaChanged) {
3545 if (layer->setAlpha(s.alpha))
3546 flags |= eTraversalNeeded;
3547 }
3548 if (what & layer_state_t::eColorChanged) {
3549 if (layer->setColor(s.color))
3550 flags |= eTraversalNeeded;
3551 }
Peiyong Lind3788632018-09-18 16:01:31 -07003552 if (what & layer_state_t::eColorTransformChanged) {
3553 if (layer->setColorTransform(s.colorTransform)) {
3554 flags |= eTraversalNeeded;
3555 }
3556 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003557 if (what & layer_state_t::eBackgroundColorChanged) {
3558 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3559 flags |= eTraversalNeeded;
3560 }
3561 }
chaviw8b3871a2017-11-01 17:41:01 -07003562 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003563 // TODO: b/109894387
3564 //
3565 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3566 // rotation. To see the problem observe that if we have a square parent, and a child
3567 // of the same size, then we rotate the child 45 degrees around it's center, the child
3568 // must now be cropped to a non rectangular 8 sided region.
3569 //
3570 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3571 // private API, and the WindowManager only uses rotation in one case, which is on a top
3572 // level layer in which cropping is not an issue.
3573 //
3574 // However given that abuse of rotation matrices could lead to surfaces extending outside
3575 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3576 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3577 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003578 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003579 flags |= eTraversalNeeded;
3580 }
3581 if (what & layer_state_t::eTransparentRegionChanged) {
3582 if (layer->setTransparentRegionHint(s.transparentRegion))
3583 flags |= eTraversalNeeded;
3584 }
3585 if (what & layer_state_t::eFlagsChanged) {
3586 if (layer->setFlags(s.flags, s.mask))
3587 flags |= eTraversalNeeded;
3588 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003589 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003590 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003591 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003592 if (what & layer_state_t::eCornerRadiusChanged) {
3593 if (layer->setCornerRadius(s.cornerRadius))
3594 flags |= eTraversalNeeded;
3595 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003596 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3597 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3598 }
chaviw8b3871a2017-11-01 17:41:01 -07003599 if (what & layer_state_t::eLayerStackChanged) {
3600 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3601 // We only allow setting layer stacks for top level layers,
3602 // everything else inherits layer stack from its parent.
3603 if (layer->hasParent()) {
3604 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003605 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003606 } else if (idx < 0) {
3607 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003608 "that also does not appear in the top level layer list. Something"
3609 " has gone wrong.",
3610 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003611 } else if (layer->setLayerStack(s.layerStack)) {
3612 mCurrentState.layersSortedByZ.removeAt(idx);
3613 mCurrentState.layersSortedByZ.add(layer);
3614 // we need traversal (state changed)
3615 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003616 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003617 }
3618 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003619 if (what & layer_state_t::eDeferTransaction_legacy) {
3620 if (s.barrierHandle_legacy != nullptr) {
3621 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3622 } else if (s.barrierGbp_legacy != nullptr) {
3623 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003624 if (authenticateSurfaceTextureLocked(gbp)) {
3625 const auto& otherLayer =
3626 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003627 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003628 } else {
3629 ALOGE("Attempt to defer transaction to to an"
3630 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003631 }
3632 }
chaviw8b3871a2017-11-01 17:41:01 -07003633 // We don't trigger a traversal here because if no other state is
3634 // changed, we don't want this to cause any more work
3635 }
chaviw8b3871a2017-11-01 17:41:01 -07003636 if (what & layer_state_t::eReparentChildren) {
3637 if (layer->reparentChildren(s.reparentHandle)) {
3638 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003639 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003640 }
chaviw8b3871a2017-11-01 17:41:01 -07003641 if (what & layer_state_t::eDetachChildren) {
3642 layer->detachChildren();
3643 }
3644 if (what & layer_state_t::eOverrideScalingModeChanged) {
3645 layer->setOverrideScalingMode(s.overrideScalingMode);
3646 // We don't trigger a traversal here because if no other state is
3647 // changed, we don't want this to cause any more work
3648 }
Marissa Wall61c58622018-07-18 10:12:20 -07003649 if (what & layer_state_t::eTransformChanged) {
3650 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3651 }
3652 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3653 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3654 flags |= eTraversalNeeded;
3655 }
3656 if (what & layer_state_t::eCropChanged) {
3657 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3658 }
Marissa Wall861616d2018-10-22 12:52:23 -07003659 if (what & layer_state_t::eFrameChanged) {
3660 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3661 }
Marissa Wall61c58622018-07-18 10:12:20 -07003662 if (what & layer_state_t::eAcquireFenceChanged) {
3663 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3664 }
3665 if (what & layer_state_t::eDataspaceChanged) {
3666 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3667 }
3668 if (what & layer_state_t::eHdrMetadataChanged) {
3669 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3670 }
3671 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3672 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3673 }
3674 if (what & layer_state_t::eApiChanged) {
3675 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3676 }
3677 if (what & layer_state_t::eSidebandStreamChanged) {
3678 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3679 }
Robert Carr720e5062018-07-30 17:45:14 -07003680 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003681 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003682 layer->setInputInfo(s.inputInfo);
3683 flags |= eTraversalNeeded;
3684 } else {
3685 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3686 }
Robert Carr720e5062018-07-30 17:45:14 -07003687 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003688 if (what & layer_state_t::eMetadataChanged) {
3689 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3690 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003691 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3692 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3693 flags |= eTraversalNeeded;
3694 }
3695 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003696 if (what & layer_state_t::eShadowRadiusChanged) {
3697 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3698 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003699 if (what & layer_state_t::eFrameRateSelectionPriority) {
3700 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3701 flags |= eTraversalNeeded;
3702 }
3703 }
Steven Thomas3172e202020-01-06 19:25:30 -08003704 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003705 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3706 "SurfaceFlinger::setClientStateLocked") &&
3707 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3708 Layer::FrameRate::convertCompatibility(
3709 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003710 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003711 }
Steven Thomas3172e202020-01-06 19:25:30 -08003712 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003713 // This has to happen after we reparent children because when we reparent to null we remove
3714 // child layers from current state and remove its relative z. If the children are reparented in
3715 // the same transaction, then we have to make sure we reparent the children first so we do not
3716 // lose its relative z order.
3717 if (what & layer_state_t::eReparent) {
3718 bool hadParent = layer->hasParent();
3719 if (layer->reparent(s.parentHandleForChild)) {
3720 if (!hadParent) {
3721 mCurrentState.layersSortedByZ.remove(layer);
3722 }
3723 flags |= eTransactionNeeded | eTraversalNeeded;
3724 }
3725 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003726 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003727 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3728 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003729 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3730 }
3731 }
Marissa Wall78b72202019-03-15 14:58:34 -07003732 bool bufferChanged = what & layer_state_t::eBufferChanged;
3733 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3734 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003735 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003736 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003737 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3738 if (success) {
3739 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3740 success = ClientCache::getInstance()
3741 .registerErasedRecipient(s.cachedBuffer,
3742 wp<ClientCache::ErasedRecipient>(this));
3743 if (!success) {
3744 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3745 }
3746 }
Marissa Wall78b72202019-03-15 14:58:34 -07003747 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003748 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003749 } else if (bufferChanged) {
3750 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003751 }
Marissa Wall78b72202019-03-15 14:58:34 -07003752 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003753 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3754 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003755 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003756 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003757 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003758 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3759 // Do not put anything that updates layer state or modifies flags after
3760 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003761 return flags;
3762}
3763
chaviw273171b2018-12-26 11:46:30 -08003764uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3765 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003766 if (inputWindowCommands.syncInputWindows) {
3767 flags |= eTraversalNeeded;
3768 }
3769
Vishnu Nairec0ab382019-02-13 15:32:56 -08003770 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003771 return flags;
3772}
3773
chaviwfe94a222019-08-21 13:52:59 -07003774status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3775 sp<IBinder>* outHandle) {
3776 if (!mirrorFromHandle) {
3777 return NAME_NOT_FOUND;
3778 }
3779
3780 sp<Layer> mirrorLayer;
3781 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003782 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003783
3784 {
3785 Mutex::Autolock _l(mStateLock);
3786 mirrorFrom = fromHandle(mirrorFromHandle);
3787 if (!mirrorFrom) {
3788 return NAME_NOT_FOUND;
3789 }
3790
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003791 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3792 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003793 if (result != NO_ERROR) {
3794 return result;
3795 }
3796
3797 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3798 }
3799
3800 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3801}
3802
Marissa Wall2d814fb2019-04-09 18:52:57 +00003803status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3804 uint32_t h, PixelFormat format, uint32_t flags,
3805 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003806 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003807 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3808 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003809 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003810 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003811 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003812 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003813 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003814
Robert Carrc0df3122019-04-11 13:18:21 -07003815 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3816 "Expected only one of parentLayer or parentHandle to be non-null. "
3817 "Programmer error?");
3818
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003819 status_t result = NO_ERROR;
3820
3821 sp<Layer> layer;
3822
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003823 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003824
Evan Roskya1f1e152019-01-24 16:17:46 -08003825 bool primaryDisplayOnly = false;
3826
3827 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3828 // TODO b/64227542
3829 if (metadata.has(METADATA_WINDOW_TYPE)) {
3830 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3831 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003832 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003833 primaryDisplayOnly = true;
3834 }
3835 }
3836
Mathias Agopian3165cc22012-08-08 19:42:09 -07003837 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003838 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003839 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3840 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003841
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003842 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003843 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003844 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003845 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003846 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003847 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003848 // check if buffer size is set for color layer.
3849 if (w > 0 || h > 0) {
3850 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3851 int(w), int(h));
3852 return BAD_VALUE;
3853 }
3854
Vishnu Nairfa247b12020-02-11 08:58:26 -08003855 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3856 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003857 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003858 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003859 // check if buffer size is set for container layer.
3860 if (w > 0 || h > 0) {
3861 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3862 int(w), int(h));
3863 return BAD_VALUE;
3864 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003865 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3866 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003867 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003868 default:
3869 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003870 break;
3871 }
3872
Dan Stoza7d89d062015-04-30 13:29:25 -07003873 if (result != NO_ERROR) {
3874 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003875 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003876
Evan Roskya1f1e152019-01-24 16:17:46 -08003877 if (primaryDisplayOnly) {
3878 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003879 }
3880
Robert Carrb89ea9d2018-12-10 13:01:14 -08003881 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003882 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3883 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003884 if (result != NO_ERROR) {
3885 return result;
3886 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003887 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003888
3889 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003890 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003891}
3892
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003893std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3894 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003895
3896 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003897 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003898
Dan Stoza436ccf32018-06-21 12:10:12 -07003899 // Grab the state lock since we're accessing mCurrentState
3900 Mutex::Autolock lock(mStateLock);
3901
Cody Northropbc755282017-03-31 12:00:08 -06003902 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003903 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003904 while (matchFound) {
3905 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003906 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003907 if (layer->getName() == uniqueName) {
3908 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003909 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003910 }
3911 });
3912 }
3913
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003914 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003915 return uniqueName;
3916}
3917
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003918status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003919 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003920 LayerMetadata metadata, PixelFormat& format,
3921 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003922 sp<IGraphicBufferProducer>* gbp,
3923 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003924 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003925 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003926 case PIXEL_FORMAT_TRANSPARENT:
3927 case PIXEL_FORMAT_TRANSLUCENT:
3928 format = PIXEL_FORMAT_RGBA_8888;
3929 break;
3930 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003931 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932 break;
3933 }
3934
chaviwb4c6e582019-08-16 14:35:07 -07003935 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003936 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003937 args.textureName = getNewTexture();
3938 {
3939 // Grab the SF state lock during this since it's the only safe way to access
3940 // RenderEngine when creating a BufferLayerConsumer
3941 // TODO: Check if this lock is still needed here
3942 Mutex::Autolock lock(mStateLock);
3943 layer = getFactory().createBufferQueueLayer(args);
3944 }
3945
Marissa Wallfd668622018-05-10 10:21:13 -07003946 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003947 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003948 *handle = layer->getHandle();
3949 *gbp = layer->getProducer();
3950 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003951 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003952
Marissa Wallfd668622018-05-10 10:21:13 -07003953 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003954 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003955}
3956
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003957status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003958 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003959 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003960 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003961 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003962 args.displayDevice = getDefaultDisplayDevice();
3963 args.textureName = getNewTexture();
3964 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003965 if (outTransformHint) {
3966 *outTransformHint = layer->getTransformHint();
3967 }
Marissa Wall61c58622018-07-18 10:12:20 -07003968 *handle = layer->getHandle();
3969 *outLayer = layer;
3970
3971 return NO_ERROR;
3972}
3973
Vishnu Nairfa247b12020-02-11 08:58:26 -08003974status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3975 uint32_t h, uint32_t flags, LayerMetadata metadata,
3976 sp<IBinder>* handle, sp<Layer>* outLayer) {
3977 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003978 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003979 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003980 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003981}
3982
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003983status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003984 uint32_t w, uint32_t h, uint32_t flags,
3985 LayerMetadata metadata, sp<IBinder>* handle,
3986 sp<Layer>* outLayer) {
3987 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003988 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003989 *handle = (*outLayer)->getHandle();
3990 return NO_ERROR;
3991}
3992
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003993void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003994 mLayersPendingRemoval.add(layer);
3995 mLayersRemoved = true;
3996 setTransactionFlags(eTransactionNeeded);
3997}
3998
Robert Carr695d5282018-12-18 15:27:58 -08003999void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004000{
Robert Carr2e102c92018-10-23 12:11:15 -07004001 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004002 // If a layer has a parent, we allow it to out-live it's handle
4003 // with the idea that the parent holds a reference and will eventually
4004 // be cleaned up. However no one cleans up the top-level so we do so
4005 // here.
4006 if (layer->getParent() == nullptr) {
4007 mCurrentState.layersSortedByZ.remove(layer);
4008 }
4009 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004010
4011 auto it = mLayersByLocalBinderToken.begin();
4012 while (it != mLayersByLocalBinderToken.end()) {
4013 if (it->second == layer) {
4014 it = mLayersByLocalBinderToken.erase(it);
4015 } else {
4016 it++;
4017 }
4018 }
4019
Robert Carr695d5282018-12-18 15:27:58 -08004020 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004021}
4022
Mathias Agopianb60314a2012-04-10 22:09:54 -07004023// ---------------------------------------------------------------------------
4024
Andy McFadden13a082e2012-08-24 10:16:42 -07004025void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004026 const auto display = getDefaultDisplayDeviceLocked();
4027 if (!display) return;
4028
4029 const sp<IBinder> token = display->getDisplayToken().promote();
4030 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004031
Jesse Hall01e29052013-02-19 16:13:35 -08004032 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004033 Vector<ComposerState> state;
4034 Vector<DisplayState> displays;
4035 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004036 d.what = DisplayState::eDisplayProjectionChanged |
4037 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004038 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004039 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004040 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004041 d.frame.makeInvalid();
4042 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004043 d.width = 0;
4044 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004045 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004046 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4047 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004048
Dominik Laskowskie9774092018-12-11 10:04:24 -08004049 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004050
Dominik Laskowski83b88212018-12-11 13:34:06 -08004051 const nsecs_t vsyncPeriod = getVsyncPeriod();
4052 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004053
Brian Andersond0010582017-03-07 13:20:31 -08004054 // Use phase of 0 since phase is not known.
4055 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004056 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004057 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004058}
4059
4060void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004061 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004062 postMessageAsync(
4063 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004064}
4065
Ady Abraham27c70212019-06-11 10:52:26 -07004066void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4067 if (mHWCVsyncState != enabled) {
4068 getHwComposer().setVsyncEnabled(displayId, enabled);
4069 mHWCVsyncState = enabled;
4070 }
4071}
4072
Dominik Laskowskie9774092018-12-11 10:04:24 -08004073void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004074 if (display->isVirtual()) {
4075 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004076 return;
4077 }
4078
Dominik Laskowski075d3172018-05-24 15:50:06 -07004079 const auto displayId = display->getId();
4080 LOG_ALWAYS_FATAL_IF(!displayId);
4081
Dominik Laskowski34157762018-10-31 13:07:19 -07004082 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004083
4084 int currentMode = display->getPowerMode();
4085 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004086 return;
4087 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004088
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004089 display->setPowerMode(mode);
4090
Lloyd Pique4dccc412018-01-22 17:21:36 -08004091 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004092 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004093 }
4094
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004095 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004096 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004097 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004098 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004099 mScheduler->onScreenAcquired(mAppConnectionHandle);
4100 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004101 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004102
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004103 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004104 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004105 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004106
4107 struct sched_param param = {0};
4108 param.sched_priority = 1;
4109 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4110 ALOGW("Couldn't set SCHED_FIFO on display on");
4111 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004112 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004113 // Turn off the display
4114 struct sched_param param = {0};
4115 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4116 ALOGW("Couldn't set SCHED_OTHER on display off");
4117 }
4118
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004119 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004120 mScheduler->disableHardwareVsync(true);
4121 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004122 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004123
Ady Abraham27c70212019-06-11 10:52:26 -07004124 // Make sure HWVsync is disabled before turning off the display
4125 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4126
Dominik Laskowski075d3172018-05-24 15:50:06 -07004127 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004128 mVisibleRegionsDirty = true;
4129 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004130 } else if (mode == HWC_POWER_MODE_DOZE ||
4131 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004132 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004133 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004134 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004135 mScheduler->onScreenAcquired(mAppConnectionHandle);
4136 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004137 }
4138 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4139 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004140 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004141 mScheduler->disableHardwareVsync(true);
4142 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004143 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004144 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004145 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004146 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004147 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004148 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004149
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004150 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004151 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004152 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004153 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004154 }
4155
Dominik Laskowski34157762018-10-31 13:07:19 -07004156 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004157}
4158
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004159void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004160 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004161 const auto display = getDisplayDevice(displayToken);
4162 if (!display) {
4163 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4164 displayToken.get());
4165 } else if (display->isVirtual()) {
4166 ALOGW("Attempt to set power mode %d for virtual display", mode);
4167 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004168 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004169 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004170 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004171}
4172
4173// ---------------------------------------------------------------------------
4174
Dominik Laskowskic2867142019-01-21 11:33:38 -08004175status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4176 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004177 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004178
Mathias Agopianbd115332013-04-18 16:41:04 -07004179 IPCThreadState* ipc = IPCThreadState::self();
4180 const int pid = ipc->getCallingPid();
4181 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004182
Mathias Agopianbd115332013-04-18 16:41:04 -07004183 if ((uid != AID_SHELL) &&
4184 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004185 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4186 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004187 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004188 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004189 // (this would indicate SF is stuck, but we want to be able to
4190 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004191 status_t err = mStateLock.timedLock(s2ns(1));
4192 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004193 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004194 StringAppendF(&result,
4195 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4196 "(no locks held)\n",
4197 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004198 }
4199
Dominik Laskowskic2867142019-01-21 11:33:38 -08004200 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004201 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004202 {"--dispsync"s,
4203 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004204 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004205 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4206 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4207 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4208 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4209 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4210 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004211 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004212 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4213 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004214
Dominik Laskowskic2867142019-01-21 11:33:38 -08004215 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004216
Dominik Laskowski46470112019-08-02 13:13:11 -07004217 const auto it = dumpers.find(flag);
4218 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004219 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004220 } else if (!asProto) {
4221 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004222 }
4223
Mathias Agopian9795c422009-08-26 16:36:26 -07004224 if (locked) {
4225 mStateLock.unlock();
4226 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004227
Dominik Laskowski46470112019-08-02 13:13:11 -07004228 if (it == dumpers.end()) {
4229 const LayersProto layersProto = dumpProtoFromMainThread();
4230 if (asProto) {
4231 result.append(layersProto.SerializeAsString());
4232 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004233 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004234 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4235 result.append(LayerProtoParser::layerTreeToString(layerTree));
4236 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004237 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004238 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004239 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004240 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004241 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004242 return NO_ERROR;
4243}
4244
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004245status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4246 if (asProto && mTracing.isEnabled()) {
4247 mTracing.writeToFileAsync();
4248 }
4249
4250 return doDump(fd, DumpArgs(), asProto);
4251}
4252
Dominik Laskowskic2867142019-01-21 11:33:38 -08004253void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004254 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004255 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004256}
4257
Dominik Laskowskic2867142019-01-21 11:33:38 -08004258void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004259 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004260
Dominik Laskowskic2867142019-01-21 11:33:38 -08004261 if (args.size() > 1) {
4262 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004263 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004264 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004265 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004266 }
Robert Carr2047fae2016-11-28 14:09:09 -08004267 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004268 } else {
4269 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004270 }
4271}
4272
Dominik Laskowskic2867142019-01-21 11:33:38 -08004273void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004274 const bool clearAll = args.size() < 2;
4275 const auto name = clearAll ? String8() : String8(args[1]);
4276
Edgar Arriaga844fa672020-01-16 14:21:42 -08004277 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004278 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004279 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004280 }
Robert Carr2047fae2016-11-28 14:09:09 -08004281 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004282
Svetoslavd85084b2014-03-20 10:28:31 -07004283 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004284}
4285
Dominik Laskowskic2867142019-01-21 11:33:38 -08004286void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4287 mTimeStats->parseArgs(asProto, args, result);
4288}
4289
Jamie Gennis6547ff42013-07-16 20:12:42 -07004290// This should only be called from the main thread. Otherwise it would need
4291// the lock and should use mCurrentState rather than mDrawingState.
4292void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004293 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004294 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004295 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004296
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004297 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004298}
4299
Yiwei Zhang5434a782018-12-05 18:06:32 -08004300void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004301 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004302
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004303 if (isLayerTripleBufferingDisabled())
4304 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004305
Yiwei Zhang5434a782018-12-05 18:06:32 -08004306 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4307 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4308 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4309 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4310 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4311 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004312 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004313}
4314
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004315void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004316 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004317
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004318 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004319 result.append("\n");
4320
Ady Abraham9e16a482019-12-03 17:19:41 -08004321 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004322 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004323 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004324 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004325
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004326 HwcConfigIndexType defaultConfig;
4327 float minFps, maxFps;
4328 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004329 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004330 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004331 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004332 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004333 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4334 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004335
Ana Krulecc2870422019-01-29 19:00:58 -08004336 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004337}
4338
Yiwei Zhang5434a782018-12-05 18:06:32 -08004339void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4340 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004341 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4342 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004343 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004344 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004345 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004346 }
David Sodman4a36e932017-11-07 14:29:47 -08004347 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004348 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004349 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004350 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4351 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004352}
4353
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004354void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4355 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004356 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4357 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004358 for (const auto& segment : history) {
4359 if (!segment.usedThirdBuffer) {
4360 stats.twoBufferTime += segment.totalTime;
4361 }
4362 if (segment.occupancyAverage < 1.0f) {
4363 stats.doubleBufferedTime += segment.totalTime;
4364 } else if (segment.occupancyAverage < 2.0f) {
4365 stats.tripleBufferedTime += segment.totalTime;
4366 }
4367 ++stats.numSegments;
4368 stats.totalTime += segment.totalTime;
4369 }
4370}
4371
Yiwei Zhang5434a782018-12-05 18:06:32 -08004372void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4373 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004374
4375 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4376 const size_t count = currentLayers.size();
4377 for (size_t i=0 ; i<count ; i++) {
4378 currentLayers[i]->dumpFrameEvents(result);
4379 }
4380}
4381
Yiwei Zhang5434a782018-12-05 18:06:32 -08004382void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004383 result.append("Buffering stats:\n");
4384 result.append(" [Layer name] <Active time> <Two buffer> "
4385 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004386 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004387 typedef std::tuple<std::string, float, float, float> BufferTuple;
4388 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004389 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004390 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004391 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004392 if (stats.numSegments == 0) {
4393 continue;
4394 }
4395 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4396 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4397 stats.totalTime;
4398 float doubleBufferRatio = static_cast<float>(
4399 stats.doubleBufferedTime) / stats.totalTime;
4400 float tripleBufferRatio = static_cast<float>(
4401 stats.tripleBufferedTime) / stats.totalTime;
4402 sorted.insert({activeTime, {name, twoBufferRatio,
4403 doubleBufferRatio, tripleBufferRatio}});
4404 }
4405 for (const auto& sortedPair : sorted) {
4406 float activeTime = sortedPair.first;
4407 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004408 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4409 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004410 }
4411 result.append("\n");
4412}
4413
Yiwei Zhang5434a782018-12-05 18:06:32 -08004414void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004415 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004416 const auto displayId = display->getId();
4417 if (!displayId) {
4418 continue;
4419 }
4420 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004421 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004422 continue;
4423 }
4424
Yiwei Zhang5434a782018-12-05 18:06:32 -08004425 StringAppendF(&result,
4426 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4427 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004428 uint8_t port;
4429 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004430 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004431 result.append("no identification data\n");
4432 continue;
4433 }
4434
4435 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004436 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004437 continue;
4438 }
4439
4440 const auto edid = parseEdid(data);
4441 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004442 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004443 continue;
4444 }
4445
Yiwei Zhang5434a782018-12-05 18:06:32 -08004446 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004447 result.append(edid->displayName.data(), edid->displayName.length());
4448 result.append("\"\n");
4449 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004450}
4451
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004452void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4453 std::string& result) const {
4454 hwc2_display_t hwcDisplayId;
4455 uint8_t port;
4456 DisplayIdentificationData data;
4457
4458 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4459 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4460 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4461 }
4462}
4463
Yiwei Zhang5434a782018-12-05 18:06:32 -08004464void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004465 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004466 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4467 StringAppendF(&result, "DisplayColorSetting: %s\n",
4468 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004469
4470 // TODO: print out if wide-color mode is active or not
4471
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004472 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004473 const auto displayId = display->getId();
4474 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004475 continue;
4476 }
4477
Yiwei Zhang5434a782018-12-05 18:06:32 -08004478 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004479 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004480 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004481 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004482 }
4483
Lloyd Pique32cbe282018-10-19 13:09:22 -07004484 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004485 StringAppendF(&result, " Current color mode: %s (%d)\n",
4486 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004487 }
4488 result.append("\n");
4489}
4490
Vishnu Nair8406fd72019-07-30 11:29:31 -07004491LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -08004492 Mutex::Autolock _l(mStateLock);
4493 const auto device = getDefaultDisplayDeviceLocked();
chaviw1d044282017-09-27 12:19:28 -07004494 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004495 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Alec Mouri6b9e9912020-01-21 10:50:24 -08004496 layer->writeToProto(layersProto, traceFlags, device);
chaviw08f3cb22020-01-13 13:17:21 -08004497 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004498
chaviw1d044282017-09-27 12:19:28 -07004499 return layersProto;
4500}
4501
Alec Mouri6b9e9912020-01-21 10:50:24 -08004502void SurfaceFlinger::dumpHwc(std::string& result) const {
4503 getHwComposer().dump(result);
4504}
4505
Vishnu Nair0f085c62019-08-30 08:49:12 -07004506void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4507 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4508 // it.
4509 LayerProto* rootProto = layersProto.add_layers();
4510 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4511 rootProto->set_id(offscreenRootLayerId);
4512 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004513 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004514
4515 for (Layer* offscreenLayer : mOffscreenLayers) {
4516 // Add layer as child of the fake root
4517 rootProto->add_children(offscreenLayer->sequence);
4518
4519 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004520 LayerProto* layerProto =
4521 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004522 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004523 }
4524}
4525
Vishnu Nair8406fd72019-07-30 11:29:31 -07004526LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4527 LayersProto layersProto;
4528 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4529 return layersProto;
4530}
4531
Vishnu Nair0f085c62019-08-30 08:49:12 -07004532void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4533 result.append("Offscreen Layers:\n");
4534 postMessageSync(new LambdaMessage([&]() {
4535 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004536 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004537 layer->dumpCallingUidPid(result);
4538 });
4539 }
4540 }));
4541}
4542
Dominik Laskowskic2867142019-01-21 11:33:38 -08004543void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4544 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004545 Colorizer colorizer(colorize);
4546
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004547 // figure out if we're stuck somewhere
4548 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004549 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004550 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4551
4552 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004553 * Dump library configuration.
4554 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004555
4556 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004557 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004558 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004559 appendSfConfigString(result);
4560 appendUiConfigString(result);
4561 appendGuiConfigString(result);
4562 result.append("\n");
4563
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004564 result.append("\nDisplay identification data:\n");
4565 dumpDisplayIdentificationData(result);
4566
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004567 result.append("\nWide-Color information:\n");
4568 dumpWideColorInfo(result);
4569
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004570 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004571 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004572 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004573 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004574 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004575
Andy McFadden41d67d72014-04-25 16:58:34 -07004576 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004577 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004578 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004579 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004580 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004581
Dan Stozab90cf072015-03-05 11:05:59 -08004582 dumpStaticScreenStats(result);
4583 result.append("\n");
4584
Alec Mouri40189b02019-03-05 15:07:54 -08004585 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4586 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4587 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004588
Dan Stozae77c7662016-05-13 11:37:28 -07004589 dumpBufferingStats(result);
4590
Andy McFadden4803b742012-09-24 19:07:20 -07004591 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004592 * Dump the visible layer list
4593 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004594 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004595 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004596 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4597 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004598 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004599
Chia-I Wu2f884132018-09-13 15:17:58 -07004600 {
Lloyd Pique207def92019-02-28 16:09:52 -08004601 StringAppendF(&result, "Composition layers\n");
4602 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004603 auto* compositionState = layer->getCompositionState();
4604 if (!compositionState) return;
4605
4606 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4607 layer->getDebugName() ? layer->getDebugName()
4608 : "<unknown>");
4609 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004610 });
4611 }
4612
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004613 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004614 * Dump Display state
4615 */
4616
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004617 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004618 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004619 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004620 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004621 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004622 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004623 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004624
4625 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004626 * Dump CompositionEngine state
4627 */
4628
4629 mCompositionEngine->dump(result);
4630
4631 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004632 * Dump SurfaceFlinger global state
4633 */
4634
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004635 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004636 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004637 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004638
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004639 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004640
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004641 DebugEGLImageTracker::getInstance()->dump(result);
4642
Dominik Laskowski075d3172018-05-24 15:50:06 -07004643 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004644 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4645 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004646 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4647 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004648 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004649 StringAppendF(&result,
4650 " transaction-flags : %08x\n"
4651 " gpu_to_cpu_unsupported : %d\n",
4652 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004653
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004654 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004655 displayId && getHwComposer().isConnected(*displayId)) {
4656 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004657 StringAppendF(&result,
4658 " refresh-rate : %f fps\n"
4659 " x-dpi : %f\n"
4660 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004661 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4662 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004663 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004664
Yiwei Zhang5434a782018-12-05 18:06:32 -08004665 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004666
Dan Stozae22aec72016-08-01 13:20:59 -07004667 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004668 * Tracing state
4669 */
4670 mTracing.dump(result);
4671 result.append("\n");
4672
4673 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004674 * HWC layer minidump
4675 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004676 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004677 const auto displayId = display->getId();
4678 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004679 continue;
4680 }
4681
Yiwei Zhang5434a782018-12-05 18:06:32 -08004682 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004683 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004684 const sp<DisplayDevice> displayDevice = display;
4685 mCurrentState.traverseInZOrder(
4686 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004687 result.append("\n");
4688 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004689
4690 /*
4691 * Dump HWComposer state
4692 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004693 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004694 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004695 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004696 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004697 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004698 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004699
4700 /*
4701 * Dump gralloc state
4702 */
4703 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4704 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004705
4706 /*
4707 * Dump VrFlinger state if in use.
4708 */
4709 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4710 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004711 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004712 result.append("\n");
4713 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004714
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004715 result.append(mTimeStats->miniDump());
4716 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004717}
4718
Chia-I Wu28f320b2018-05-03 11:02:56 -07004719void SurfaceFlinger::updateColorMatrixLocked() {
4720 mat4 colorMatrix;
4721 if (mGlobalSaturationFactor != 1.0f) {
4722 // Rec.709 luma coefficients
4723 float3 luminance{0.213f, 0.715f, 0.072f};
4724 luminance *= 1.0f - mGlobalSaturationFactor;
4725 mat4 saturationMatrix = mat4(
4726 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4727 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4728 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4729 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4730 );
4731 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4732 } else {
4733 colorMatrix = mClientColorMatrix * mDaltonizer();
4734 }
4735
4736 if (mCurrentState.colorMatrix != colorMatrix) {
4737 mCurrentState.colorMatrix = colorMatrix;
4738 mCurrentState.colorMatrixChanged = true;
4739 setTransactionFlags(eTransactionNeeded);
4740 }
4741}
4742
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004743status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004744#pragma clang diagnostic push
4745#pragma clang diagnostic error "-Wswitch-enum"
4746 switch (static_cast<ISurfaceComposerTag>(code)) {
4747 // These methods should at minimum make sure that the client requested
4748 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004749 case BOOT_FINISHED:
4750 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004751 case CREATE_DISPLAY:
4752 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004753 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004754 case GET_ANIMATION_FRAME_STATS:
4755 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004756 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004757 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004758 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004759 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4760 case SET_AUTO_LOW_LATENCY_MODE:
4761 case GET_GAME_CONTENT_TYPE_SUPPORT:
4762 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004763 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004764 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004765 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004766 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004767 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004768 case NOTIFY_POWER_HINT:
4769 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004770 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4771 IPCThreadState* ipc = IPCThreadState::self();
4772 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4773 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004774 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004775 }
Robert Carr1db73f62016-12-21 12:58:51 -08004776 return OK;
4777 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004778 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004779 IPCThreadState* ipc = IPCThreadState::self();
4780 const int pid = ipc->getCallingPid();
4781 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004782 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4783 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004784 return PERMISSION_DENIED;
4785 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004786 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004787 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004788 // Used by apps to hook Choreographer to SurfaceFlinger.
4789 case CREATE_DISPLAY_EVENT_CONNECTION:
4790 // The following calls are currently used by clients that do not
4791 // request necessary permissions. However, they do not expose any secret
4792 // information, so it is OK to pass them.
4793 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004794 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004795 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004796 case GET_PHYSICAL_DISPLAY_IDS:
4797 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004798 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004799 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004800 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004801 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004802 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004803 case GET_DISPLAY_STATS:
4804 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4805 // Calling setTransactionState is safe, because you need to have been
4806 // granted a reference to Client* and Handle* to do anything with it.
4807 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004808 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004809 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004810 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004811 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004812 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004813 // setFrameRate() is deliberately available for apps to call without any
4814 // special permissions.
4815 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004816 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4817 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004818 return OK;
4819 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004820 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004821 case CAPTURE_SCREEN:
4822 case ADD_REGION_SAMPLING_LISTENER:
4823 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004824 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004825 IPCThreadState* ipc = IPCThreadState::self();
4826 const int pid = ipc->getCallingPid();
4827 const int uid = ipc->getCallingUid();
4828 if ((uid != AID_GRAPHICS) &&
4829 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4830 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4831 return PERMISSION_DENIED;
4832 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004833 return OK;
4834 }
chaviw93df2ea2019-04-30 16:45:12 -07004835 case CAPTURE_SCREEN_BY_ID: {
4836 IPCThreadState* ipc = IPCThreadState::self();
4837 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004838 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004839 return OK;
4840 }
4841 return PERMISSION_DENIED;
4842 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004843 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004844
4845 // These codes are used for the IBinder protocol to either interrogate the recipient
4846 // side of the transaction for its canonical interface descriptor or to dump its state.
4847 // We let them pass by default.
4848 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4849 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4850 code == IBinder::SYSPROPS_TRANSACTION) {
4851 return OK;
4852 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004853 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004854 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004855 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004856 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4857 return OK;
4858 }
4859 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4860 return PERMISSION_DENIED;
4861#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004862}
4863
Ana Krulec13be8ad2018-08-21 02:43:56 +00004864status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4865 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004866 status_t credentialCheck = CheckTransactCodeCredentials(code);
4867 if (credentialCheck != OK) {
4868 return credentialCheck;
4869 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004870
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004871 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4872 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004873 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004874 IPCThreadState* ipc = IPCThreadState::self();
4875 const int uid = ipc->getCallingUid();
4876 if (CC_UNLIKELY(uid != AID_SYSTEM
4877 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004878 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004879 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004880 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004881 return PERMISSION_DENIED;
4882 }
4883 int n;
4884 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004885 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004886 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004887 return NO_ERROR;
4888 case 1002: // SHOW_UPDATES
4889 n = data.readInt32();
4890 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004891 invalidateHwcGeometry();
4892 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004893 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004894 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004895 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004896 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004897 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004898 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004899 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004900 setTransactionFlags(
4901 eTransactionNeeded|
4902 eDisplayTransactionNeeded|
4903 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004904 return NO_ERROR;
4905 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004906 case 1006:{ // send empty update
4907 signalRefresh();
4908 return NO_ERROR;
4909 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004910 case 1008: // toggle use of hw composer
4911 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004912 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004913 invalidateHwcGeometry();
4914 repaintEverything();
4915 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004916 case 1009: // toggle use of transform hint
4917 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004918 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004919 invalidateHwcGeometry();
4920 repaintEverything();
4921 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004922 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004923 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004924 reply->writeInt32(0);
4925 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004926 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004927 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004928 return NO_ERROR;
4929 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004930 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004931 if (!display) {
4932 return NAME_NOT_FOUND;
4933 }
4934
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004935 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004936 return NO_ERROR;
4937 }
4938 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004939 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004940 // daltonize
4941 n = data.readInt32();
4942 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004943 case 1:
4944 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4945 break;
4946 case 2:
4947 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4948 break;
4949 case 3:
4950 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4951 break;
4952 default:
4953 mDaltonizer.setType(ColorBlindnessType::None);
4954 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004955 }
4956 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004957 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004958 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004959 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004960 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004961
4962 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004963 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004964 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004965 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004966 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004967 // apply a color matrix
4968 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004969 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004970 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004971 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004972 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004973 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004974 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004975 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004976 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004977 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004978 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004979
4980 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4981 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004982 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004983 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4984 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4985 }
4986
Chia-I Wu28f320b2018-05-03 11:02:56 -07004987 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004988 return NO_ERROR;
4989 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004990 case 1016: { // Unused.
4991 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004992 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004993 case 1017: {
4994 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004995 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004996 return NO_ERROR;
4997 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004998 case 1018: { // Modify Choreographer's phase offset
4999 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005000 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005001 return NO_ERROR;
5002 }
5003 case 1019: { // Modify SurfaceFlinger's phase offset
5004 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005005 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005006 return NO_ERROR;
5007 }
Irvel468051e2016-06-13 16:44:44 -07005008 case 1020: { // Layer updates interceptor
5009 n = data.readInt32();
5010 if (n) {
5011 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005012 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005013 }
5014 else{
5015 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005016 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005017 }
5018 return NO_ERROR;
5019 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005020 case 1021: { // Disable HWC virtual displays
5021 n = data.readInt32();
5022 mUseHwcVirtualDisplays = !n;
5023 return NO_ERROR;
5024 }
Romain Guy0147a172017-06-01 13:53:56 -07005025 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005026 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005027 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005028
Chia-I Wu28f320b2018-05-03 11:02:56 -07005029 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005030 return NO_ERROR;
5031 }
Romain Guy54f154a2017-10-24 21:40:32 +01005032 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005033 int32_t colorMode;
5034
Chia-I Wu0d711262018-05-21 15:19:35 -07005035 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005036 if (data.readInt32(&colorMode) == NO_ERROR) {
5037 mForceColorMode = static_cast<ColorMode>(colorMode);
5038 }
Romain Guy54f154a2017-10-24 21:40:32 +01005039 invalidateHwcGeometry();
5040 repaintEverything();
5041 return NO_ERROR;
5042 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005043 // Deprecate, use 1030 to check whether the device is color managed.
5044 case 1024: {
5045 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005046 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005047 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005048 n = data.readInt32();
5049 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005050 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005051 Mutex::Autolock lock(mStateLock);
5052 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005053 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005054 reply->writeInt32(NO_ERROR);
5055 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005056 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005057 bool writeFile = false;
5058 {
5059 Mutex::Autolock lock(mStateLock);
5060 mTracingEnabledChanged = true;
5061 writeFile = mTracing.disable();
5062 }
5063
5064 if (writeFile) {
5065 reply->writeInt32(mTracing.writeToFile());
5066 } else {
5067 reply->writeInt32(NO_ERROR);
5068 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005069 }
5070 return NO_ERROR;
5071 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005072 case 1026: { // Get layer tracing status
5073 reply->writeBool(mTracing.isEnabled());
5074 return NO_ERROR;
5075 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005076 // Is a DisplayColorSetting supported?
5077 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005078 const auto display = getDefaultDisplayDevice();
5079 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005080 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005081 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005082
5083 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5084 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005085 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005086 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005087 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005088 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005089 reply->writeBool(true);
5090 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005091 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005092 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005093 break;
5094 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005095 reply->writeBool(
5096 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005097 break;
5098 }
5099 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005100 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005101 // Is VrFlinger active?
5102 case 1028: {
5103 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005104 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005105 return NO_ERROR;
5106 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005107 // Set buffer size for SF tracing (value in KB)
5108 case 1029: {
5109 n = data.readInt32();
5110 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5111 ALOGW("Invalid buffer size: %d KB", n);
5112 reply->writeInt32(BAD_VALUE);
5113 return BAD_VALUE;
5114 }
5115
5116 ALOGD("Updating trace buffer to %d KB", n);
5117 mTracing.setBufferSize(n * 1024);
5118 reply->writeInt32(NO_ERROR);
5119 return NO_ERROR;
5120 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005121 // Is device color managed?
5122 case 1030: {
5123 reply->writeBool(useColorManagement);
5124 return NO_ERROR;
5125 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005126 // Override default composition data space
5127 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5128 // && adb shell stop zygote && adb shell start zygote
5129 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5130 // adb shell stop zygote && adb shell start zygote
5131 case 1031: {
5132 Mutex::Autolock _l(mStateLock);
5133 n = data.readInt32();
5134 if (n) {
5135 n = data.readInt32();
5136 if (n) {
5137 Dataspace dataspace = static_cast<Dataspace>(n);
5138 if (!validateCompositionDataspace(dataspace)) {
5139 return BAD_VALUE;
5140 }
5141 mDefaultCompositionDataspace = dataspace;
5142 }
5143 n = data.readInt32();
5144 if (n) {
5145 Dataspace dataspace = static_cast<Dataspace>(n);
5146 if (!validateCompositionDataspace(dataspace)) {
5147 return BAD_VALUE;
5148 }
5149 mWideColorGamutCompositionDataspace = dataspace;
5150 }
5151 } else {
5152 // restore composition data space.
5153 mDefaultCompositionDataspace = defaultCompositionDataspace;
5154 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5155 }
5156 return NO_ERROR;
5157 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005158 // Set trace flags
5159 case 1033: {
5160 n = data.readUint32();
5161 ALOGD("Updating trace flags to 0x%x", n);
5162 mTracing.setTraceFlags(n);
5163 reply->writeInt32(NO_ERROR);
5164 return NO_ERROR;
5165 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005166 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005167 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005168 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005169 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005170 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005171 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005172 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005173 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005174 } else {
5175 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005176 }
5177 return NO_ERROR;
5178 }
Ady Abraham34392f72019-04-10 11:29:27 -07005179 case 1035: {
5180 n = data.readInt32();
5181 mDebugDisplayConfigSetByBackdoor = false;
5182 if (n >= 0) {
5183 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005184 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005185 if (result != NO_ERROR) {
5186 return result;
5187 }
5188 mDebugDisplayConfigSetByBackdoor = true;
5189 }
5190 return NO_ERROR;
5191 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005192 }
5193 }
5194 return err;
5195}
5196
Steven Thomas6d8110b2017-08-31 18:24:21 -07005197void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005198 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005199 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005200}
5201
Ana Krulec7d1d6832018-12-27 11:10:09 -08005202void SurfaceFlinger::repaintEverythingForHWC() {
5203 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005204 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005205 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005206}
5207
Ady Abrahama09852a2020-02-20 14:23:42 -08005208void SurfaceFlinger::kernelTimerChanged(bool expired) {
5209 static bool updateOverlay =
5210 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5211 if (!updateOverlay || !mRefreshRateOverlay) return;
5212
5213 // Update the overlay on the main thread to avoid race conditions with
5214 // mRefreshRateConfigs->getCurrentRefreshRate()
5215 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5216 if (mRefreshRateOverlay) {
5217 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5218 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005219 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005220 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5221 if (mDesiredActiveConfigChanged) {
5222 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5223 mDesiredActiveConfig.configId);
5224 }
5225
5226 return mRefreshRateConfigs->getCurrentRefreshRate();
5227 }();
5228 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5229
5230 if (current != min) {
5231 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5232 mEventQueue->invalidate();
5233 }
5234 }
5235 }));
5236}
5237
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005238// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5239class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005240public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005241 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5242 ~WindowDisconnector() {
5243 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005244 }
5245
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005246private:
5247 ANativeWindow* mWindow;
5248 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005249};
5250
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005251status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005252 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005253 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5254 const Rect& sourceCrop, uint32_t reqWidth,
5255 uint32_t reqHeight, bool useIdentityTransform,
5256 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005257 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005258
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005259 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005260
Dominik Laskowski718f9602019-11-09 20:01:35 -08005261 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5262 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5263 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5264 renderAreaRotation = ui::Transform::ROT_0;
5265 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005266
Chia-I Wu20261cb2018-08-23 12:55:44 -07005267 sp<DisplayDevice> display;
5268 {
5269 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005270
Chia-I Wu20261cb2018-08-23 12:55:44 -07005271 display = getDisplayDeviceLocked(displayToken);
5272 if (!display) return BAD_VALUE;
5273
Chia-I Wucb023152018-08-28 12:57:23 -07005274 // set the requested width/height to the logical display viewport size
5275 // by default
5276 if (reqWidth == 0 || reqHeight == 0) {
5277 reqWidth = uint32_t(display->getViewport().width());
5278 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005279 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005280 }
5281
Peiyong Lin0e003c92018-09-17 11:09:51 -07005282 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005283 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005284
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005285 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5286 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005287 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005288 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005289}
5290
chaviw93df2ea2019-04-30 16:45:12 -07005291static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5292 switch (colorMode) {
5293 case ColorMode::DISPLAY_P3:
5294 case ColorMode::BT2100_PQ:
5295 case ColorMode::BT2100_HLG:
5296 case ColorMode::DISPLAY_BT2020:
5297 return Dataspace::DISPLAY_P3;
5298 default:
5299 return Dataspace::V0_SRGB;
5300 }
5301}
5302
5303const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5304 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5305 if (displayToken) {
5306 return getDisplayDeviceLocked(displayToken);
5307 }
5308 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5309 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005310 return getDisplayByLayerStack(displayOrLayerStack);
5311}
5312
5313const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005314 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005315 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005316 return display;
5317 }
5318 }
5319 return nullptr;
5320}
5321
5322status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5323 sp<GraphicBuffer>* outBuffer) {
5324 sp<DisplayDevice> display;
5325 uint32_t width;
5326 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005327 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005328 {
5329 Mutex::Autolock _l(mStateLock);
5330 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5331 if (!display) {
5332 return BAD_VALUE;
5333 }
5334
5335 width = uint32_t(display->getViewport().width());
5336 height = uint32_t(display->getViewport().height());
5337
Dominik Laskowski718f9602019-11-09 20:01:35 -08005338 const auto orientation = display->getOrientation();
5339 captureOrientation = ui::Transform::toRotationFlags(orientation);
5340
5341 switch (captureOrientation) {
5342 case ui::Transform::ROT_90:
5343 captureOrientation = ui::Transform::ROT_270;
5344 break;
5345
5346 case ui::Transform::ROT_270:
5347 captureOrientation = ui::Transform::ROT_90;
5348 break;
5349
5350 case ui::Transform::ROT_INVALID:
5351 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5352 captureOrientation = ui::Transform::ROT_0;
5353 break;
5354
5355 default:
5356 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005357 }
chaviw93df2ea2019-04-30 16:45:12 -07005358 *outDataspace =
5359 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5360 }
5361
5362 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5363 false /* captureSecureLayers */);
5364
5365 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5366 std::placeholders::_1);
5367 bool ignored = false;
5368 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5369 false /* useIdentityTransform */,
5370 ignored /* outCapturedSecureLayers */);
5371}
5372
Robert Carr866455f2019-04-02 16:28:26 -07005373status_t SurfaceFlinger::captureLayers(
5374 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5375 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5376 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5377 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005378 ATRACE_CALL();
5379
5380 class LayerRenderArea : public RenderArea {
5381 public:
Robert Carr578038f2018-03-09 12:25:24 -08005382 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005383 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005384 bool childrenOnly, const Rect& displayViewport)
5385 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005386 mLayer(layer),
5387 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005388 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005389 mFlinger(flinger),
5390 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005391 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005392 Rect getBounds() const override {
5393 const Layer::State& layerState(mLayer->getDrawingState());
5394 return mLayer->getBufferSize(layerState);
5395 }
Marissa Wall61c58622018-07-18 10:12:20 -07005396 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005397 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005398 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005399 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005400 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005401 }
chaviwa76b2712017-09-20 12:02:26 -07005402 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005403 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005404 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005405 Rect getSourceCrop() const override {
5406 if (mCrop.isEmpty()) {
5407 return getBounds();
5408 } else {
5409 return mCrop;
5410 }
5411 }
Robert Carr578038f2018-03-09 12:25:24 -08005412 class ReparentForDrawing {
5413 public:
5414 const sp<Layer>& oldParent;
5415 const sp<Layer>& newParent;
5416
Vishnu Nair4351ad52019-02-11 14:13:02 -08005417 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5418 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005419 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005420 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005421 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5422 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005423 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005424 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005425 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005426 };
5427
5428 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005429 const Rect sourceCrop = getSourceCrop();
5430 // no need to check rotation because there is none
5431 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5432 sourceCrop.height() != getReqHeight();
5433
Robert Carr578038f2018-03-09 12:25:24 -08005434 if (!mChildrenOnly) {
5435 mTransform = mLayer->getTransform().inverse();
5436 drawLayers();
5437 } else {
5438 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005439 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5440 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005441 // In the "childrenOnly" case we reparent the children to a screenshot
5442 // layer which has no properties set and which does not draw.
5443 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005444 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5445 "Screenshot Parent"s, w, h, 0,
5446 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005447
Vishnu Nair4351ad52019-02-11 14:13:02 -08005448 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005449 drawLayers();
5450 }
5451 }
chaviwa76b2712017-09-20 12:02:26 -07005452
chaviwa76b2712017-09-20 12:02:26 -07005453 private:
chaviw7206d492017-11-10 16:16:12 -08005454 const sp<Layer> mLayer;
5455 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005456
Peiyong Linefefaac2018-08-17 12:27:51 -07005457 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005458 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005459
5460 SurfaceFlinger* mFlinger;
5461 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005462 };
5463
Robert Carrc0df3122019-04-11 13:18:21 -07005464 int reqWidth = 0;
5465 int reqHeight = 0;
5466 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005467 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005468 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005469 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005470 {
5471 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005472
Robert Carrc0df3122019-04-11 13:18:21 -07005473 parent = fromHandle(layerHandleBinder);
5474 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5475 ALOGE("captureLayers called with an invalid or removed parent");
5476 return NAME_NOT_FOUND;
5477 }
5478
5479 const int uid = IPCThreadState::self()->getCallingUid();
5480 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5481 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5482 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5483 return PERMISSION_DENIED;
5484 }
5485
Vishnu Nairefc42e22019-12-03 17:36:12 -08005486 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005487 if (sourceCrop.width() <= 0) {
5488 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005489 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005490 }
5491
5492 if (sourceCrop.height() <= 0) {
5493 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005494 crop.bottom = parentSourceBounds.getHeight();
5495 }
5496
5497 if (crop.isEmpty() || frameScale <= 0.0f) {
5498 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5499 // crop was not specified, or an invalid frame scale was provided.
5500 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005501 }
5502 reqWidth = crop.width() * frameScale;
5503 reqHeight = crop.height() * frameScale;
5504
5505 for (const auto& handle : excludeHandles) {
5506 sp<Layer> excludeLayer = fromHandle(handle);
5507 if (excludeLayer != nullptr) {
5508 excludeLayers.emplace(excludeLayer);
5509 } else {
5510 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5511 return NAME_NOT_FOUND;
5512 }
5513 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005514
5515 auto display = getDisplayByLayerStack(parent->getLayerStack());
5516 if (!display) {
5517 return BAD_VALUE;
5518 }
5519
5520 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005521 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005522
Chia-I Wu20261cb2018-08-23 12:55:44 -07005523 // really small crop or frameScale
5524 if (reqWidth <= 0) {
5525 reqWidth = 1;
5526 }
5527 if (reqHeight <= 0) {
5528 reqHeight = 1;
5529 }
5530
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005531 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5532 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005533 auto traverseLayers = [parent, childrenOnly,
5534 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005535 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5536 if (!layer->isVisible()) {
5537 return;
Robert Carr578038f2018-03-09 12:25:24 -08005538 } else if (childrenOnly && layer == parent.get()) {
5539 return;
chaviwa76b2712017-09-20 12:02:26 -07005540 }
Robert Carr866455f2019-04-02 16:28:26 -07005541
5542 sp<Layer> p = layer;
5543 while (p != nullptr) {
5544 if (excludeLayers.count(p) != 0) {
5545 return;
5546 }
5547 p = p->getParent();
5548 }
5549
chaviwa76b2712017-09-20 12:02:26 -07005550 visitor(layer);
5551 });
5552 };
Robert Carr108b2c72019-04-02 16:32:58 -07005553
5554 bool outCapturedSecureLayers = false;
5555 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5556 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005557}
5558
5559status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5560 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005561 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005562 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005563 bool useIdentityTransform,
5564 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005565 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005566
Peiyong Lin0e003c92018-09-17 11:09:51 -07005567 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005568 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5569 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005570 *outBuffer =
5571 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5572 static_cast<android_pixel_format>(reqPixelFormat), 1,
5573 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005574
Robert Carr108b2c72019-04-02 16:32:58 -07005575 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5576 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005577}
5578
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005579status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5580 TraverseLayersFunction traverseLayers,
5581 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005582 bool useIdentityTransform,
5583 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005584 // This mutex protects syncFd and captureResult for communication of the return values from the
5585 // main thread back to this Binder thread
5586 std::mutex captureMutex;
5587 std::condition_variable captureCondition;
5588 std::unique_lock<std::mutex> captureLock(captureMutex);
5589 int syncFd = -1;
5590 std::optional<status_t> captureResult;
5591
Robert Carr03480e22018-01-04 16:02:06 -08005592 const int uid = IPCThreadState::self()->getCallingUid();
5593 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5594
Dominik Laskowski8c001672018-05-30 16:52:06 -07005595 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005596 // If there is a refresh pending, bug out early and tell the binder thread to try again
5597 // after the refresh.
5598 if (mRefreshPending) {
5599 ATRACE_NAME("Skipping screenshot for now");
5600 std::unique_lock<std::mutex> captureLock(captureMutex);
5601 captureResult = std::make_optional<status_t>(EAGAIN);
5602 captureCondition.notify_one();
5603 return;
5604 }
5605
5606 status_t result = NO_ERROR;
5607 int fd = -1;
5608 {
5609 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005610 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005611 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005612 useIdentityTransform, forSystem, &fd,
5613 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005614 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005615 }
5616
5617 {
5618 std::unique_lock<std::mutex> captureLock(captureMutex);
5619 syncFd = fd;
5620 captureResult = std::make_optional<status_t>(result);
5621 captureCondition.notify_one();
5622 }
5623 });
5624
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005625 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005626 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005627 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005628 while (*captureResult == EAGAIN) {
5629 captureResult.reset();
5630 result = postMessageAsync(message);
5631 if (result != NO_ERROR) {
5632 return result;
5633 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005634 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005635 }
5636 result = *captureResult;
5637 }
5638
5639 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005640 sync_wait(syncFd, -1);
5641 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005642 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005643
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005644 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005645}
5646
chaviwa76b2712017-09-20 12:02:26 -07005647void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005648 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005649 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5650 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005651 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005652
chaviwa76b2712017-09-20 12:02:26 -07005653 const auto reqWidth = renderArea.getReqWidth();
5654 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005655 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005656 const auto transform = renderArea.getTransform();
5657 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005658 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005659
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005660 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005661 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005662
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005663 // assume that bounds are never offset, and that they are the same as the
5664 // buffer bounds.
5665 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005666 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005667 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005668
5669 // Now take into account the rotation flag. We append a transform that
5670 // rotates the layer stack about the origin, then translate by buffer
5671 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005672 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005673 int displacementX = 0;
5674 int displacementY = 0;
5675 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5676 switch (rotation) {
5677 case ui::Transform::ROT_90:
5678 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005679 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005680 break;
5681 case ui::Transform::ROT_180:
5682 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005683 displacementY = renderArea.getBounds().getWidth();
5684 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005685 break;
5686 case ui::Transform::ROT_270:
5687 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005688 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005689 break;
5690 default:
5691 break;
5692 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005693
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005694 // We need to transform the clipping window into the right spot.
5695 // First, rotate the clipping rectangle by the rotation hint to get the
5696 // right orientation
5697 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5698 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5699 const vec4 rotClipTL = rotMatrix * clipTL;
5700 const vec4 rotClipBR = rotMatrix * clipBR;
5701 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5702 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5703 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5704 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5705
5706 // Now reposition the clipping rectangle with the displacement vector
5707 // computed above.
5708 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005709 clientCompositionDisplay.clip =
5710 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5711 newClipRight + displacementX, newClipBottom + displacementY);
5712
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005713 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005714 clientCompositionDisplay.globalTransform =
5715 clipTransform * clientCompositionDisplay.globalTransform;
5716
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005717 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5718 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005719
chaviw50da5042018-04-09 13:49:37 -07005720 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005721
Vishnu Nair9b079a22020-01-21 14:36:08 -08005722 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005723 fillLayer.source.buffer.buffer = nullptr;
5724 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5725 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5726 fillLayer.alpha = half(alpha);
5727 clientCompositionLayers.push_back(fillLayer);
5728
5729 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005730 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005731 const bool supportProtectedContent = false;
5732 Region clip(renderArea.getBounds());
5733 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5734 clip,
5735 useIdentityTransform,
5736 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5737 renderArea.isSecure(),
5738 supportProtectedContent,
5739 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005740 displayViewport,
5741 clientCompositionDisplay.outputDataspace,
5742 true, /* realContentIsVisible */
5743 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005744 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005745 std::vector<compositionengine::LayerFE::LayerSettings> results =
5746 layer->prepareClientCompositionList(targetSettings);
5747 clientCompositionLayers.insert(clientCompositionLayers.end(),
5748 std::make_move_iterator(results.begin()),
5749 std::make_move_iterator(results.end()));
5750 results.clear();
5751
chaviwa76b2712017-09-20 12:02:26 -07005752 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005753
Vishnu Nair9b079a22020-01-21 14:36:08 -08005754 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5755 clientCompositionLayers.reserve(clientCompositionLayers.size());
5756 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5757 std::back_inserter(clientCompositionLayerPointers),
5758 [](compositionengine::LayerFE::LayerSettings& settings)
5759 -> renderengine::LayerSettings* { return &settings; });
5760
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005761 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005762 // Use an empty fence for the buffer fence, since we just created the buffer so
5763 // there is no need for synchronization with the GPU.
5764 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005765 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005766 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005767 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005768 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005769
5770 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005771}
5772
chaviwa76b2712017-09-20 12:02:26 -07005773status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5774 TraverseLayersFunction traverseLayers,
5775 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005776 bool useIdentityTransform, bool forSystem,
5777 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005778 ATRACE_CALL();
5779
chaviwa76b2712017-09-20 12:02:26 -07005780 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005781 outCapturedSecureLayers =
5782 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005783 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005784
Robert Carr03480e22018-01-04 16:02:06 -08005785 // We allow the system server to take screenshots of secure layers for
5786 // use in situations like the Screen-rotation animation and place
5787 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005788 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005789 ALOGW("FB is protected: PERMISSION_DENIED");
5790 return PERMISSION_DENIED;
5791 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005792 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005793 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005794}
5795
chaviw95ef3c42019-02-14 10:55:09 -08005796void SurfaceFlinger::setInputWindowsFinished() {
5797 Mutex::Autolock _l(mStateLock);
5798
5799 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005800
chaviw95ef3c42019-02-14 10:55:09 -08005801 mTransactionCV.broadcast();
5802}
chaviw5f21a5e2019-02-14 10:00:34 -08005803
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005804// ---------------------------------------------------------------------------
5805
Edgar Arriaga844fa672020-01-16 14:21:42 -08005806void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5807 layersSortedByZ.traverse(visitor);
5808}
5809
Dan Stoza412903f2017-04-27 13:42:17 -07005810void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5811 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005812}
5813
Dan Stoza412903f2017-04-27 13:42:17 -07005814void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5815 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005816}
5817
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005818void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005819 const LayerVector::Visitor& visitor) {
5820 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005821 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005822 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005823 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005824 continue;
5825 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005826 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005827 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005828 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005829 return;
5830 }
chaviwa76b2712017-09-20 12:02:26 -07005831 if (!layer->isVisible()) {
5832 return;
5833 }
5834 visitor(layer);
5835 });
5836 }
5837}
5838
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005839status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5840 HwcConfigIndexType defaultConfig,
5841 float minRefreshRate,
5842 float maxRefreshRate) {
5843 Mutex::Autolock lock(mStateLock);
5844
Dominik Laskowski22488f62019-03-28 09:53:04 -07005845 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005846 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5847 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5848 // it should go thru setDesiredActiveConfig, similar to primary display.
5849 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5850 const auto displayId = display->getId();
5851 LOG_ALWAYS_FATAL_IF(!displayId);
5852
5853 HWC2::VsyncPeriodChangeConstraints constraints;
5854 constraints.desiredTimeNanos = systemTime();
5855 constraints.seamlessRequired = false;
5856
5857 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005858 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5859 constraints, &timeline) < 0) {
5860 return BAD_VALUE;
5861 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005862 if (timeline.refreshRequired) {
5863 repaintEverythingForHWC();
5864 }
5865
Ady Abrahamdfa37362020-01-21 18:02:39 -08005866 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005867 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005868 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5869 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005870 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005871 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005872 }
5873
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005874 if (mDebugDisplayConfigSetByBackdoor) {
5875 // ignore this request as config is overridden by backdoor
5876 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005877 }
5878
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005879 bool policyChanged;
5880 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5881 &policyChanged) < 0) {
5882 return BAD_VALUE;
5883 }
5884 if (!policyChanged) {
5885 return NO_ERROR;
5886 }
5887
5888 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5889 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005890
5891 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5892 // that listeners that care about a change in allowed configs can get the notification.
5893 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005894 const nsecs_t vsyncPeriod =
5895 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005896 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005897 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005898
Ana Krulec3f6a2062020-01-23 15:48:01 -08005899 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005900 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005901 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5902 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5903 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5904 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5905 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5906
5907 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5908 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5909 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005910 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005911 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005912 }
5913
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005914 return NO_ERROR;
5915}
5916
Ana Krulec0782b882019-10-15 17:34:54 -07005917status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005918 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005919 float maxRefreshRate) {
5920 ATRACE_CALL();
5921
5922 if (!displayToken) {
5923 return BAD_VALUE;
5924 }
5925
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005926 status_t result = NO_ERROR;
5927
Ana Krulec234bb162019-11-10 22:55:55 +01005928 postMessageSync(new LambdaMessage([&]() {
5929 const auto display = getDisplayDeviceLocked(displayToken);
5930 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005931 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005932 ALOGE("Attempt to set desired display configs for invalid display token %p",
5933 displayToken.get());
5934 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005935 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005936 ALOGW("Attempt to set desired display configs for virtual display");
5937 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005938 result =
5939 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5940 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005941 }
5942 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005943
5944 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005945}
5946
5947status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005948 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005949 float* outMinRefreshRate,
5950 float* outMaxRefreshRate) {
5951 ATRACE_CALL();
5952
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005953 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005954 return BAD_VALUE;
5955 }
5956
5957 Mutex::Autolock lock(mStateLock);
5958 const auto display = getDisplayDeviceLocked(displayToken);
5959 if (!display) {
5960 return NAME_NOT_FOUND;
5961 }
5962
5963 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005964 HwcConfigIndexType defaultConfig;
5965 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5966 *outDefaultConfig = defaultConfig.value();
5967 return NO_ERROR;
5968 } else if (display->isVirtual()) {
5969 return BAD_VALUE;
5970 } else {
5971 const auto displayId = display->getId();
5972 if (!displayId) {
5973 return BAD_VALUE;
5974 }
5975 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5976 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5977 *outMinRefreshRate = 1e9f / vsyncPeriod;
5978 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5979 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005980 }
Ana Krulec0782b882019-10-15 17:34:54 -07005981}
5982
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005983void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005984 mFlinger->setInputWindowsFinished();
5985}
5986
Robert Carrc0df3122019-04-11 13:18:21 -07005987sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005988 BBinder* b = nullptr;
5989 if (handle) {
5990 b = handle->localBinder();
5991 }
Robert Carrc0df3122019-04-11 13:18:21 -07005992 if (b == nullptr) {
5993 return nullptr;
5994 }
5995 auto it = mLayersByLocalBinderToken.find(b);
5996 if (it != mLayersByLocalBinderToken.end()) {
5997 return it->second.promote();
5998 }
5999 return nullptr;
6000}
6001
Dominik Laskowski75848362019-11-11 17:57:20 -08006002void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006003 mNumLayers++;
6004 mScheduler->registerLayer(layer);
6005}
6006
6007void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6008 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006009 removeFromOffscreenLayers(layer);
6010}
6011
6012// WARNING: ONLY CALL THIS FROM LAYER DTOR
6013// Here we add children in the current state to offscreen layers and remove the
6014// layer itself from the offscreen layer list. Since
6015// this is the dtor, it is safe to access the current state. This keeps us
6016// from dangling children layers such that they are not reachable from the
6017// Drawing state nor the offscreen layer list
6018// See b/141111965
6019void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6020 for (auto& child : layer->getCurrentChildren()) {
6021 mOffscreenLayers.emplace(child.get());
6022 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006023 mOffscreenLayers.erase(layer);
6024}
6025
Alec Mouri4545a8a2019-08-08 20:05:32 -07006026void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6027 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6028}
6029
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006030status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6031 float lightPosY, float lightPosZ,
6032 float lightRadius) {
6033 Mutex::Autolock _l(mStateLock);
6034 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6035 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6036 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6037 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6038 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6039
6040 // these values are overridden when calculating the shadow settings for a layer.
6041 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6042 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006043 return NO_ERROR;
6044}
6045
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006046const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6047 const {
6048 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6049 // on the work to remove the table in that bug rather than adding more to
6050 // it.
6051 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6052 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6053 // supported, and exposed via the
6054 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6055 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6056 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6057 };
6058 return genericLayerMetadataKeyMap;
6059}
6060
Steven Thomas62a4cf82020-01-31 12:04:03 -08006061status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6062 int8_t compatibility) {
6063 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6064 return BAD_VALUE;
6065 }
6066
6067 Mutex::Autolock lock(mStateLock);
6068 if (authenticateSurfaceTextureLocked(surface)) {
6069 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6070 if (layer->setFrameRate(
6071 Layer::FrameRate(frameRate,
6072 Layer::FrameRate::convertCompatibility(compatibility)))) {
6073 setTransactionFlags(eTraversalNeeded);
6074 }
6075 } else {
6076 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6077 return BAD_VALUE;
6078 }
6079 return NO_ERROR;
6080}
6081
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006082} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006083
Mathias Agopian3f844832013-08-07 21:24:32 -07006084#if defined(__gl_h_)
6085#error "don't include gl/gl.h in this file"
6086#endif
6087
6088#if defined(__gl2_h_)
6089#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006090#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006091
6092// TODO(b/129481165): remove the #pragma below and fix conversion issues
6093#pragma clang diagnostic pop // ignored "-Wconversion"