blob: c69e1060873da5a57fec019a48fac102b9cbd67d [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri5f487d42020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri5f487d42020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Pique9370a482019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri5f487d42020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri5f487d42020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800104#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
111#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700114#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/EventControlThread.h"
116#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700117#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700118#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700119#include "Scheduler/Scheduler.h"
Alec Mouri5f487d42020-02-06 09:26:19 -0800120#include "StartPropertySetThread.h"
121#include "SurfaceFlingerProperties.h"
122#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800123#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700124#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800125#include "android-base/stringprintf.h"
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Steven Thomasb02664d2017-07-26 18:48:28 -0700143namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700144
145#pragma clang diagnostic push
146#pragma clang diagnostic error "-Wswitch-enum"
147
148bool isWideColorMode(const ColorMode colorMode) {
149 switch (colorMode) {
150 case ColorMode::DISPLAY_P3:
151 case ColorMode::ADOBE_RGB:
152 case ColorMode::DCI_P3:
153 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700154 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700155 case ColorMode::BT2100_PQ:
156 case ColorMode::BT2100_HLG:
157 return true;
158 case ColorMode::NATIVE:
159 case ColorMode::STANDARD_BT601_625:
160 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
161 case ColorMode::STANDARD_BT601_525:
162 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
163 case ColorMode::STANDARD_BT709:
164 case ColorMode::SRGB:
165 return false;
166 }
167 return false;
168}
169
170#pragma clang diagnostic pop
171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172class ConditionalLock {
173public:
174 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
175 if (lock) {
176 mMutex.lock();
177 }
178 }
179 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
180private:
181 Mutex& mMutex;
182 bool mLocked;
183};
Peiyong Linfca547f2018-07-09 13:03:33 -0700184
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800185// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
186constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
187
188float getDensityFromProperty(const char* property, bool required) {
189 char value[PROPERTY_VALUE_MAX];
190 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
191 if (!density && required) {
192 ALOGE("%s must be defined as a build property", property);
193 return FALLBACK_DENSITY;
194 }
195 return density / 160.f;
196}
197
Peiyong Lin9d846a52018-11-05 13:18:20 -0800198// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
199bool validateCompositionDataspace(Dataspace dataspace) {
200 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
201}
202
Steven 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 Mouri5f487d42020-02-06 09:26:19 -0800335 property_get("ro.build.type", value, "user");
336 mIsUserBuild = strcmp(value, "user") == 0;
337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 property_get("debug.sf.showupdates", value, "0");
339 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700340
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700341 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000342
343 // DDMS debugging deprecated (b/120782499)
344 property_get("debug.sf.ddms", value, "0");
345 int debugDdms = atoi(value);
346 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700347
348 property_get("debug.sf.disable_backpressure", value, "0");
349 mPropagateBackpressure = !atoi(value);
350 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700351
Ady Abrahamadb9a992019-09-19 21:21:55 +0000352 property_get("debug.sf.enable_gl_backpressure", value, "0");
353 mPropagateBackpressureClientComposition = atoi(value);
354 ALOGI_IF(mPropagateBackpressureClientComposition,
355 "Enabling backpressure propagation for Client Composition");
356
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800357 property_get("debug.sf.enable_hwc_vds", value, "0");
358 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800359 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800360
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800361 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800362 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800363 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700364
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800365 property_get("ro.surface_flinger.supports_background_blur", value, "0");
366 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700367 mSupportsBlur = supportsBlurs;
368 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800369 property_get("ro.sf.blurs_are_expensive", value, "0");
370 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800371
Ady Abrahamb89ca7d2020-03-04 11:19:37 -0800372 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700373 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
374 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
Alec Mouri601393f2020-02-21 13:26:52 -0800375 mGraphicBufferProducerListSizeLogThreshold =
376 std::max(static_cast<int>(0.95 *
377 static_cast<double>(mMaxGraphicBufferProducerListSize)),
378 1);
Dan Stoza0a0158c2018-03-16 13:38:54 -0700379
Dan Stozaec460082018-12-17 15:35:09 -0800380 property_get("debug.sf.luma_sampling", value, "1");
381 mLumaSampling = atoi(value);
382
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800383 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800384 mDisableClientCompositionCache = atoi(value);
385
Romain Guy11d63f42017-07-20 12:47:14 -0700386 // We should be reading 'persist.sys.sf.color_saturation' here
387 // but since /data may be encrypted, we need to wait until after vold
388 // comes online to attempt to read the property. The property is
389 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800390
391 if (useTrebleTestingOverride()) {
392 // Without the override SurfaceFlinger cannot connect to HIDL
393 // services that are not listed in the manifests. Considered
394 // deriving the setting from the set service name, but it
395 // would be brittle if the name that's not 'default' is used
396 // for production purposes later on.
397 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
398 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800399
400 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800401}
402
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800403void SurfaceFlinger::onFirstRef()
404{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800405 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800406}
407
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700408SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800409
Dan Stozac7014012014-02-14 15:03:43 -0800410void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411{
412 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700413 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800414
Andy McFadden13a082e2012-08-24 10:16:42 -0700415 // restore initial conditions (default device unblank, etc)
416 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800417
418 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700419 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800420}
421
Robert Carr1db73f62016-12-21 12:58:51 -0800422static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700423 status_t err = client->initCheck();
424 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800425 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800426 }
Robert Carr1db73f62016-12-21 12:58:51 -0800427 return nullptr;
428}
429
430sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
431 return initClient(new Client(this));
432}
433
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700434sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
435 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700436{
437 class DisplayToken : public BBinder {
438 sp<SurfaceFlinger> flinger;
439 virtual ~DisplayToken() {
440 // no more references, this display must be terminated
441 Mutex::Autolock _l(flinger->mStateLock);
442 flinger->mCurrentState.displays.removeItem(this);
443 flinger->setTransactionFlags(eDisplayTransactionNeeded);
444 }
445 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700446 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700447 : flinger(flinger) {
448 }
449 };
450
451 sp<BBinder> token = new DisplayToken(this);
452
453 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700454 // Display ID is assigned when virtual display is allocated by HWC.
455 DisplayDeviceState state;
456 state.isSecure = secure;
457 state.displayName = displayName;
458 mCurrentState.displays.add(token, state);
459 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700460 return token;
461}
462
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700463void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700464 Mutex::Autolock _l(mStateLock);
465
Dominik Laskowski075d3172018-05-24 15:50:06 -0700466 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
467 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700468 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700469 return;
470 }
471
Dominik Laskowski075d3172018-05-24 15:50:06 -0700472 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
473 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700474 ALOGE("destroyDisplay called for non-virtual display");
475 return;
476 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 mInterceptor->saveDisplayDeletion(state.sequenceId);
478 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700479 setTransactionFlags(eDisplayTransactionNeeded);
480}
481
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800482std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
483 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700484
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800485 const auto internalDisplayId = getInternalDisplayIdLocked();
486 if (!internalDisplayId) {
487 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700488 }
489
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800490 std::vector<PhysicalDisplayId> displayIds;
491 displayIds.reserve(mPhysicalDisplayTokens.size());
492 displayIds.push_back(internalDisplayId->value);
493
494 for (const auto& [id, token] : mPhysicalDisplayTokens) {
495 if (id != *internalDisplayId) {
496 displayIds.push_back(id.value);
497 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700498 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700499
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800500 return displayIds;
501}
502
503sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
504 Mutex::Autolock lock(mStateLock);
505 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700506}
507
Ady Abraham37965d42018-11-01 13:43:32 -0700508status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
509 if (!outGetColorManagement) {
510 return BAD_VALUE;
511 }
512 *outGetColorManagement = useColorManagement;
513 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700514}
515
Lloyd Pique441d5042018-10-18 16:49:51 -0700516HWComposer& SurfaceFlinger::getHwComposer() const {
517 return mCompositionEngine->getHwComposer();
518}
519
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700520renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
521 return mCompositionEngine->getRenderEngine();
522}
523
Lloyd Pique70d91362018-10-18 16:02:55 -0700524compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
525 return *mCompositionEngine.get();
526}
527
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800528void SurfaceFlinger::bootFinished()
529{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700530 if (mBootFinished == true) {
531 ALOGE("Extra call to bootFinished");
532 return;
533 }
534 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700535 if (mStartPropertySetThread->join() != NO_ERROR) {
536 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800537 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800538 const nsecs_t now = systemTime();
539 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000540 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541
Mikael Pessa90092f42019-08-26 17:22:04 -0700542 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000543 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700544
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700545 // wait patiently for the window manager death
546 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700547 mWindowManager = defaultServiceManager()->getService(name);
548 if (mWindowManager != 0) {
549 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700550 }
Robert Carr720e5062018-07-30 17:45:14 -0700551 sp<IBinder> input(defaultServiceManager()->getService(
552 String16("inputflinger")));
553 if (input == nullptr) {
554 ALOGE("Failed to link to input service");
555 } else {
556 mInputFlinger = interface_cast<IInputFlinger>(input);
557 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700558
Steven Thomas050b2c82017-03-06 11:45:16 -0800559 if (mVrFlinger) {
560 mVrFlinger->OnBootFinished();
561 }
562
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700563 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700564 // formerly we would just kill the process, but we now ask it to exit so it
565 // can choose where to stop the animation.
566 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700567
568 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
569 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
570 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700571
Ana Krulecbd6654b2019-02-15 15:18:15 -0800572 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800573 readPersistentProperties();
574 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800575
Ady Abraham8a82ba62020-01-17 12:43:17 -0800576 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
577 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
578 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
579 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800580 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800581}
582
Dan Stoza436ccf32018-06-21 12:10:12 -0700583uint32_t SurfaceFlinger::getNewTexture() {
584 {
585 std::lock_guard lock(mTexturePoolMutex);
586 if (!mTexturePool.empty()) {
587 uint32_t name = mTexturePool.back();
588 mTexturePool.pop_back();
589 ATRACE_INT("TexturePoolSize", mTexturePool.size());
590 return name;
591 }
592
593 // The pool was too small, so increase it for the future
594 ++mTexturePoolSize;
595 }
596
597 // The pool was empty, so we need to get a new texture name directly using a
598 // blocking call to the main thread
599 uint32_t name = 0;
600 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
601 return name;
602}
603
Mathias Agopian3f844832013-08-07 21:24:32 -0700604void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700605 std::lock_guard lock(mTexturePoolMutex);
606 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
607 // to actually delete this or not based on mTexturePoolSize
608 mTexturePool.push_back(texture);
609 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700610}
611
Wei Wangf9b05ee2017-07-19 20:59:39 -0700612// Do not call property_set on main thread which will be blocked by init
613// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700614void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700615 ALOGI( "SurfaceFlinger's main thread ready to run. "
616 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700617 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800618
Steven Thomasb02664d2017-07-26 18:48:28 -0700619 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700620 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800621 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700622 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
623 renderengine::RenderEngineCreationArgs::Builder()
624 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
625 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
626 .setUseColorManagerment(useColorManagement)
627 .setEnableProtectedContext(enable_protected_contents(false))
628 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700629 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700630 .setContextPriority(useContextPriority
631 ? renderengine::RenderEngine::ContextPriority::HIGH
632 : renderengine::RenderEngine::ContextPriority::MEDIUM)
633 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800634 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700635
636 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
637 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700638 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800639 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800640 // Process any initial hotplug and resulting display changes.
641 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700642 const auto display = getDefaultDisplayDeviceLocked();
643 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700644 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700645 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800646
Steven Thomas050b2c82017-03-06 11:45:16 -0800647 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700648 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700649 // This callback is called from the vr flinger dispatch thread. We
650 // need to call signalTransaction(), which requires holding
651 // mStateLock when we're not on the main thread. Acquiring
652 // mStateLock from the vr flinger dispatch thread might trigger a
653 // deadlock in surface flinger (see b/66916578), so post a message
654 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700655 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700656 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
657 mVrFlingerRequestsDisplay = requestDisplay;
658 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700659 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800660 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700661 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
662 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700663 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700664 .value_or(0),
665 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800666 if (!mVrFlinger) {
667 ALOGE("Failed to start vrflinger");
668 }
669 }
670
Mathias Agopian92a979a2012-08-02 18:32:23 -0700671 // initialize our drawing state
672 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700673
Andy McFadden13a082e2012-08-24 10:16:42 -0700674 // set initial conditions (e.g. unblank default device)
675 initializeDisplays();
676
Steven Thomas137d4bc2019-07-25 16:55:14 -0700677 char primeShaderCache[PROPERTY_VALUE_MAX];
678 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
679 if (atoi(primeShaderCache)) {
680 getRenderEngine().primeCache();
681 }
Dan Stoza4e637772016-07-28 13:31:51 -0700682
Wei Wangf9b05ee2017-07-19 20:59:39 -0700683 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700684
685 const bool presentFenceReliable =
686 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
687 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700688
689 if (mStartPropertySetThread->Start() != NO_ERROR) {
690 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800691 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800692
Dan Stoza9e56aa02015-11-02 13:00:03 -0800693 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700694}
695
Romain Guy11d63f42017-07-20 12:47:14 -0700696void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700697 Mutex::Autolock _l(mStateLock);
698
Romain Guy11d63f42017-07-20 12:47:14 -0700699 char value[PROPERTY_VALUE_MAX];
700
701 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800702 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700703 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800704 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100705
706 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700707 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800708
709 property_get("persist.sys.sf.color_mode", value, "0");
710 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700711
712 property_get("persist.sys.sf.disable_blurs", value, "0");
713 bool disableBlurs = atoi(value);
714 mDisableBlurs = disableBlurs;
715 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700716}
717
Mathias Agopiana67e4182012-06-19 17:26:12 -0700718void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800719 // Start boot animation service by setting a property mailbox
720 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700721 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800722 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700723 if (mStartPropertySetThread->join() != NO_ERROR) {
724 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800725 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700726}
727
Mathias Agopian875d8e12013-06-07 15:35:48 -0700728size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700729 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700730}
731
Mathias Agopian875d8e12013-06-07 15:35:48 -0700732size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700733 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700734}
735
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800736// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800737
Jamie Gennis582270d2011-08-17 18:19:00 -0700738bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800739 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800740 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800741 return authenticateSurfaceTextureLocked(bufferProducer);
742}
743
744bool SurfaceFlinger::authenticateSurfaceTextureLocked(
745 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800746 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800747 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800748}
749
Brian Anderson6b376712017-04-04 10:51:39 -0700750status_t SurfaceFlinger::getSupportedFrameTimestamps(
751 std::vector<FrameEvent>* outSupported) const {
752 *outSupported = {
753 FrameEvent::REQUESTED_PRESENT,
754 FrameEvent::ACQUIRE,
755 FrameEvent::LATCH,
756 FrameEvent::FIRST_REFRESH_START,
757 FrameEvent::LAST_REFRESH_START,
758 FrameEvent::GPU_COMPOSITION_DONE,
759 FrameEvent::DEQUEUE_READY,
760 FrameEvent::RELEASE,
761 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700762 ConditionalLock _l(mStateLock,
763 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700764 if (!getHwComposer().hasCapability(
765 HWC2::Capability::PresentFenceIsNotReliable)) {
766 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
767 }
768 return NO_ERROR;
769}
770
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800771status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
772 if (!displayToken || !state) {
773 return BAD_VALUE;
774 }
775
776 Mutex::Autolock lock(mStateLock);
777
778 const auto display = getDisplayDeviceLocked(displayToken);
779 if (!display) {
780 return NAME_NOT_FOUND;
781 }
782
783 state->layerStack = display->getLayerStack();
784 state->orientation = display->getOrientation();
785
786 const Rect viewport = display->getViewport();
787 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
788
789 return NO_ERROR;
790}
791
792status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
793 if (!displayToken || !info) {
794 return BAD_VALUE;
795 }
796
797 Mutex::Autolock lock(mStateLock);
798
799 const auto display = getDisplayDeviceLocked(displayToken);
800 if (!display) {
801 return NAME_NOT_FOUND;
802 }
803
Dominik Laskowski55c85402020-01-21 16:25:47 -0800804 if (const auto connectionType = display->getConnectionType())
805 info->connectionType = *connectionType;
806 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800807 return INVALID_OPERATION;
808 }
809
810 if (mEmulatedDisplayDensity) {
811 info->density = mEmulatedDisplayDensity;
812 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800813 info->density = info->connectionType == DisplayConnectionType::Internal
814 ? mInternalDisplayDensity
815 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800816 }
817
818 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200819 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800820
821 return NO_ERROR;
822}
823
Dominik Laskowski22488f62019-03-28 09:53:04 -0700824status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800825 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700826 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 return BAD_VALUE;
828 }
829
Dominik Laskowski22488f62019-03-28 09:53:04 -0700830 Mutex::Autolock lock(mStateLock);
831
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800832 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700833 if (!displayId) {
834 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700835 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700836
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800837 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700838
Dan Stoza7f7da322014-05-02 15:26:25 -0700839 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700840
Dominik Laskowski075d3172018-05-24 15:50:06 -0700841 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800842 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700843
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800844 auto width = hwConfig->getWidth();
845 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700846
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800847 auto xDpi = hwConfig->getDpiX();
848 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700849
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800850 if (isInternal &&
851 (internalDisplayOrientation == ui::ROTATION_90 ||
852 internalDisplayOrientation == ui::ROTATION_270)) {
853 std::swap(width, height);
854 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700855 }
856
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800857 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800858
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800859 if (mEmulatedDisplayDensity) {
860 config.xDpi = mEmulatedDisplayDensity;
861 config.yDpi = mEmulatedDisplayDensity;
862 } else {
863 config.xDpi = xDpi;
864 config.yDpi = yDpi;
865 }
866
867 const nsecs_t period = hwConfig->getVsyncPeriod();
868 config.refreshRate = 1e9f / period;
869
870 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
871 config.appVsyncOffset = offsets.late.app;
872 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800873 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800874
Andy McFadden91b2ca82014-06-13 14:04:23 -0700875 // This is how far in advance a buffer must be queued for
876 // presentation at a given time. If you want a buffer to appear
877 // on the screen at time N, you must submit the buffer before
878 // (N - presentationDeadline).
879 //
880 // Normally it's one full refresh period (to give SF a chance to
881 // latch the buffer), but this can be reduced by configuring a
882 // DispSync offset. Any additional delays introduced by the hardware
883 // composer or panel must be accounted for here.
884 //
885 // We add an additional 1ms to allow for processing time and
886 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800887 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700888
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800889 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700890 }
891
Dan Stoza7f7da322014-05-02 15:26:25 -0700892 return NO_ERROR;
893}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700894
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700895status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
896 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700897 return BAD_VALUE;
898 }
899
Ana Krulecc2870422019-01-29 19:00:58 -0800900 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700901 return NO_ERROR;
902}
903
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700904int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
905 const auto display = getDisplayDevice(displayToken);
906 if (!display) {
907 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800908 return BAD_VALUE;
909 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700910
Steven Thomasc9098452019-09-30 17:15:05 -0700911 if (display->isPrimary()) {
912 std::lock_guard<std::mutex> lock(mActiveConfigLock);
913 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800914 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700915 }
Steven Thomasc9098452019-09-30 17:15:05 -0700916 }
Ady Abraham2139f732019-11-13 18:56:40 -0800917
918 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700919}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700920
Ady Abraham03b02dd2019-03-21 15:40:11 -0700921void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800922 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800923 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abraham2139f732019-11-13 18:56:40 -0800924 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800925
Ady Abrahamb838aed2019-02-12 15:30:16 -0800926 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800927 if (mDesiredActiveConfigChanged) {
928 // If a config change is pending, just cache the latest request in
929 // mDesiredActiveConfig
930 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
931 mDesiredActiveConfig = info;
932 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
933 } else {
934 // Check is we are already at the desired config
935 const auto display = getDefaultDisplayDeviceLocked();
936 if (!display || display->getActiveConfig() == refreshRate.configId) {
937 return;
938 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800939
Ady Abraham59db0a32020-03-02 18:04:20 -0800940 // Initiate a config change.
941 mDesiredActiveConfigChanged = true;
942 mDesiredActiveConfig = info;
943
Ady Abrahamb838aed2019-02-12 15:30:16 -0800944 // This will trigger HWC refresh without resetting the idle timer.
945 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700946 // Start receiving vsync samples now, so that we can detect a period
947 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800948 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700949 // As we called to set period, we will call to onRefreshRateChangeCompleted once
950 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700951 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800952
Ady Abraham9e16a482019-12-03 17:19:41 -0800953 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
954 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800955 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700956
957 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800958 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700959 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800960}
961
962status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
963 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800964
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100965 if (!displayToken) {
966 return BAD_VALUE;
967 }
Ady Abraham838de062019-02-04 10:24:03 -0800968
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100969 status_t result = NO_ERROR;
970
971 postMessageSync(new LambdaMessage([&]() {
972 const auto display = getDisplayDeviceLocked(displayToken);
973 if (!display) {
974 ALOGE("Attempt to set allowed display configs for invalid display token %p",
975 displayToken.get());
976 result = BAD_VALUE;
977 } else if (display->isVirtual()) {
978 ALOGW("Attempt to set allowed display configs for virtual display");
979 result = BAD_VALUE;
980 } else {
981 HwcConfigIndexType config(mode);
982 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
983 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
984 refreshRate.fps);
985 }
986 }));
987
988 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989}
990
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800991void SurfaceFlinger::setActiveConfigInternal() {
992 ATRACE_CALL();
993
Dominik Laskowski22488f62019-03-28 09:53:04 -0700994 const auto display = getDefaultDisplayDeviceLocked();
995 if (!display) {
996 return;
997 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800998
Dominik Laskowski22488f62019-03-28 09:53:04 -0700999 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001000 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001001 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001002 display->setActiveConfig(mUpcomingActiveConfig.configId);
1003
Ady Abraham2e1dd892020-03-05 13:48:36 -08001004 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001005 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
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 Mouri5f487d42020-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 Mouri5f487d42020-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;
Marin Shalamanov700e6392020-02-12 20:22:26 +01002356 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2357 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002358 state.isSecure = true; // All physical displays are currently considered secure.
2359 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002360
2361 sp<IBinder> token = new BBinder();
2362 mCurrentState.displays.add(token, state);
2363 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2364
Dominik Laskowski075d3172018-05-24 15:50:06 -07002365 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002366 } else {
2367 ALOGV("Recreating display %s", to_string(displayId).c_str());
2368
2369 const auto token = it->second;
2370 auto& state = mCurrentState.displays.editValueFor(token);
2371 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002372 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002373 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002374 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002375
Dominik Laskowski55c85402020-01-21 16:25:47 -08002376 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002377 if (index >= 0) {
2378 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2379 mInterceptor->saveDisplayDeletion(state.sequenceId);
2380 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002381 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002382 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002383 }
2384
2385 processDisplayChangesLocked();
2386 }
2387
2388 mPendingHotplugEvents.clear();
2389}
2390
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002391void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002392 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2393 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002394}
2395
Lloyd Pique99d3da52018-01-22 17:48:03 -08002396sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Pique9370a482019-10-03 17:58:30 -07002397 const wp<IBinder>& displayToken,
2398 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanovae685592020-02-12 17:12:22 +01002399 const DisplayDeviceState& state,
2400 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002401 const sp<IGraphicBufferProducer>& producer) {
Lloyd Pique9370a482019-10-03 17:58:30 -07002402 auto displayId = compositionDisplay->getDisplayId();
2403 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002404 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002405 creationArgs.isSecure = state.isSecure;
Marin Shalamanovae685592020-02-12 17:12:22 +01002406 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002407 creationArgs.hasWideColorGamut = false;
2408 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002409
Dominik Laskowski55c85402020-01-21 16:25:47 -08002410 if (const auto& physical = state.physical) {
2411 creationArgs.connectionType = physical->type;
2412 }
2413
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002414 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002415 creationArgs.isPrimary = isInternalDisplay;
2416
2417 if (useColorManagement && displayId) {
2418 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002419 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002420 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002421 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002422 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002423
Dominik Laskowski7e045462018-05-30 13:02:02 -07002424 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002425 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002426 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002427 }
tangrobin6753a022018-08-10 10:58:54 +08002428 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002429
Dominik Laskowski075d3172018-05-24 15:50:06 -07002430 if (displayId) {
2431 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002432 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002433 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002434 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002435
Lloyd Pique90c115d2018-09-18 21:39:42 -07002436 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002437 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002438 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002439
Lloyd Pique99d3da52018-01-22 17:48:03 -08002440 // Make sure that composition can never be stalled by a virtual display
2441 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002442 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002443 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002444 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2445 }
2446
Dominik Laskowski718f9602019-11-09 20:01:35 -08002447 creationArgs.physicalOrientation =
2448 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002449
Lloyd Pique99d3da52018-01-22 17:48:03 -08002450 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002451 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002452
Lloyd Pique9370a482019-10-03 17:58:30 -07002453 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002454
2455 if (maxFrameBufferAcquiredBuffers >= 3) {
2456 nativeWindowSurface->preallocateBuffers();
2457 }
2458
2459 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002460 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002461 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002462 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002463 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002464 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002465 display->getCompositionDisplay()->setColorProfile(
2466 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2467 RenderIntent::COLORIMETRIC,
2468 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002469 if (!state.isVirtual()) {
2470 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002471 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2472 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002473 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002474
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002475 display->setLayerStack(state.layerStack);
2476 display->setProjection(state.orientation, state.viewport, state.frame);
2477 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002478
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002479 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002480}
2481
Marin Shalamanovae685592020-02-12 17:12:22 +01002482void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2483 const DisplayDeviceState& state) {
2484 int width = 0;
2485 int height = 0;
2486 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2487 if (state.physical) {
2488 const auto& activeConfig =
2489 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2490 width = activeConfig->getWidth();
2491 height = activeConfig->getHeight();
2492 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2493 } else if (state.surface != nullptr) {
2494 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2495 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2496 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2497 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2498 int intPixelFormat;
2499 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2500 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2501 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2502 } else {
2503 // Virtual displays without a surface are dormant:
2504 // they have external state (layer stack, projection,
2505 // etc.) but no internal state (i.e. a DisplayDevice).
2506 return;
2507 }
2508
2509 compositionengine::DisplayCreationArgsBuilder builder;
2510 if (const auto& physical = state.physical) {
2511 builder.setPhysical({physical->id, physical->type});
2512 }
2513 builder.setPixels(ui::Size(width, height));
2514 builder.setPixelFormat(pixelFormat);
2515 builder.setIsSecure(state.isSecure);
2516 builder.setLayerStackId(state.layerStack);
2517 builder.setPowerAdvisor(&mPowerAdvisor);
2518 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2519 builder.setName(state.displayName);
2520 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2521
2522 sp<compositionengine::DisplaySurface> displaySurface;
2523 sp<IGraphicBufferProducer> producer;
2524 sp<IGraphicBufferProducer> bqProducer;
2525 sp<IGraphicBufferConsumer> bqConsumer;
2526 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2527
2528 std::optional<DisplayId> displayId = compositionDisplay->getId();
2529
2530 if (state.isVirtual()) {
2531 sp<VirtualDisplaySurface> vds =
2532 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2533 bqConsumer, state.displayName);
2534
2535 displaySurface = vds;
2536 producer = vds;
2537 } else {
2538 ALOGE_IF(state.surface != nullptr,
2539 "adding a supported display, but rendering "
2540 "surface is provided (%p), ignoring it",
2541 state.surface.get());
2542
2543 LOG_ALWAYS_FATAL_IF(!displayId);
2544 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2545 maxGraphicsWidth, maxGraphicsHeight);
2546 producer = bqProducer;
2547 }
2548
Marin Shalamanov700e6392020-02-12 20:22:26 +01002549 LOG_FATAL_IF(!displaySurface);
2550 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2551 displaySurface, producer);
2552 mDisplays.emplace(displayToken, display);
2553 if (!state.isVirtual()) {
2554 LOG_FATAL_IF(!displayId);
2555 dispatchDisplayHotplugEvent(displayId->value, true);
2556 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002557
Marin Shalamanov700e6392020-02-12 20:22:26 +01002558 if (display->isPrimary()) {
2559 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanovae685592020-02-12 17:12:22 +01002560 }
2561}
2562
2563void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2564 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2565 // Save display ID before disconnecting.
2566 const auto displayId = display->getId();
2567 display->disconnect();
2568
2569 if (!display->isVirtual()) {
Marin Shalamanov700e6392020-02-12 20:22:26 +01002570 LOG_FATAL_IF(!displayId);
Marin Shalamanovae685592020-02-12 17:12:22 +01002571 dispatchDisplayHotplugEvent(displayId->value, false);
2572 }
2573 }
2574
2575 mDisplays.erase(displayToken);
2576}
2577
2578void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2579 const DisplayDeviceState& currentState,
2580 const DisplayDeviceState& drawingState) {
2581 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2582 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002583 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanovae685592020-02-12 17:12:22 +01002584 // changing the surface is like destroying and recreating the DisplayDevice
2585 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2586 display->disconnect();
2587 }
2588 mDisplays.erase(displayToken);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002589 if (const auto& physical = currentState.physical) {
2590 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2591 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002592 processDisplayAdded(displayToken, currentState);
Marin Shalamanov700e6392020-02-12 20:22:26 +01002593 if (currentState.physical) {
2594 initializeDisplays();
2595 }
Marin Shalamanovae685592020-02-12 17:12:22 +01002596 return;
2597 }
2598
2599 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2600 if (currentState.layerStack != drawingState.layerStack) {
2601 display->setLayerStack(currentState.layerStack);
2602 }
2603 if ((currentState.orientation != drawingState.orientation) ||
2604 (currentState.viewport != drawingState.viewport) ||
2605 (currentState.frame != drawingState.frame)) {
2606 display->setProjection(currentState.orientation, currentState.viewport,
2607 currentState.frame);
2608 }
2609 if (currentState.width != drawingState.width ||
2610 currentState.height != drawingState.height) {
2611 display->setDisplaySize(currentState.width, currentState.height);
2612 if (display->isPrimary()) {
2613 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2614 }
2615 }
2616 }
2617}
2618
Lloyd Pique347200f2017-12-14 17:00:15 -08002619void SurfaceFlinger::processDisplayChangesLocked() {
2620 // here we take advantage of Vector's copy-on-write semantics to
2621 // improve performance by skipping the transaction entirely when
2622 // know that the lists are identical
2623 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2624 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2625 if (!curr.isIdenticalTo(draw)) {
2626 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002627
2628 // find the displays that were removed
2629 // (ie: in drawing state but not in current state)
2630 // also handle displays that changed
2631 // (ie: displays that are in both lists)
Marin Shalamanovae685592020-02-12 17:12:22 +01002632 for (size_t i = 0; i < draw.size(); i++) {
2633 const wp<IBinder>& displayToken = draw.keyAt(i);
2634 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002635 if (j < 0) {
2636 // in drawing state but not in current state
Marin Shalamanovae685592020-02-12 17:12:22 +01002637 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002638 } else {
2639 // this display is in both lists. see if something changed.
Marin Shalamanovae685592020-02-12 17:12:22 +01002640 const DisplayDeviceState& currentState = curr[j];
2641 const DisplayDeviceState& drawingState = draw[i];
2642 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002643 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002644 }
2645
2646 // find displays that were added
2647 // (ie: in current state but not in drawing state)
Marin Shalamanovae685592020-02-12 17:12:22 +01002648 for (size_t i = 0; i < curr.size(); i++) {
2649 const wp<IBinder>& displayToken = curr.keyAt(i);
2650 if (draw.indexOfKey(displayToken) < 0) {
2651 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002652 }
2653 }
2654 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002655
2656 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002657}
2658
Mathias Agopian87baae12012-07-31 12:38:26 -07002659void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002660{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002661 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2662
Dan Stoza7dde5992015-05-22 09:51:44 -07002663 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002664 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002665 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002666 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002667
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668 /*
2669 * Traversal of the children
2670 * (perform the transaction for each of them if needed)
2671 */
2672
Marissa Wall06255332019-03-27 13:48:27 -07002673 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002674 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002675 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002676 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002677
2678 const uint32_t flags = layer->doTransaction(0);
2679 if (flags & Layer::eVisibleRegion)
2680 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002681
2682 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002683 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002684 }
Robert Carr2047fae2016-11-28 14:09:09 -08002685 });
Marissa Wall06255332019-03-27 13:48:27 -07002686 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002687 }
2688
2689 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002690 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002691 */
2692
Mathias Agopiane57f2922012-08-09 16:29:12 -07002693 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002694 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002695 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002696 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002697
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002698 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002699 // The transform hint might have changed for some layers
2700 // (either because a display has changed, or because a layer
2701 // as changed).
2702 //
2703 // Walk through all the layers in currentLayers,
2704 // and update their transform hint.
2705 //
2706 // If a layer is visible only on a single display, then that
2707 // display is used to calculate the hint, otherwise we use the
2708 // default display.
2709 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002710 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002711 // the hint is set before we acquire a buffer from the surface texture.
2712 //
2713 // NOTE: layer transactions have taken place already, so we use their
2714 // drawing state. However, SurfaceFlinger's own transaction has not
2715 // happened yet, so we must use the current state layer list
2716 // (soon to become the drawing state list).
2717 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002718 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002719 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002720 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002721 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002722 // NOTE: we rely on the fact that layers are sorted by
2723 // layerStack first (so we don't have to traverse the list
2724 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002725 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002726 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002727 currentlayerStack = layerStack;
2728 // figure out if this layerstack is mirrored
2729 // (more than one display) if so, pick the default display,
2730 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002731 hintDisplay = nullptr;
2732 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002733 if (display->getCompositionDisplay()
2734 ->belongsInOutput(layer->getLayerStack(),
2735 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002736 if (hintDisplay) {
2737 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002738 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002739 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002740 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002741 }
2742 }
2743 }
2744 }
Chet Haase91d25932013-04-11 15:24:55 -07002745
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002746 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002747 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2748 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002749
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002750 // could be null when this layer is using a layerStack
2751 // that is not visible on any display. Also can occur at
2752 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002753 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002754 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002755
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002756 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002757 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002758 if (hintDisplay) {
2759 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002760 }
Robert Carr2047fae2016-11-28 14:09:09 -08002761
2762 first = false;
2763 });
Mathias Agopian84300952012-11-21 16:02:13 -08002764 }
2765
2766
Mathias Agopian3559b072012-08-15 13:46:03 -07002767 /*
2768 * Perform our own transaction if needed
2769 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002770
2771 if (mLayersAdded) {
2772 mLayersAdded = false;
2773 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002774 mVisibleRegionsDirty = true;
2775 }
2776
2777 // some layers might have been removed, so
2778 // we need to update the regions they're exposing.
2779 if (mLayersRemoved) {
2780 mLayersRemoved = false;
2781 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002782 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002783 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002784 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002785 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002786 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002787 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002788 }
Robert Carr2047fae2016-11-28 14:09:09 -08002789 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002790 }
2791
Vishnu Nairec0ab382019-02-13 15:32:56 -08002792 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002793 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002794}
2795
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002796void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002797 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002798 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002799 return;
2800 }
2801
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002802 if (mVisibleRegionsDirty || mInputInfoChanged) {
2803 mInputInfoChanged = false;
2804 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002805 } else if (mInputWindowCommands.syncInputWindows) {
2806 // If the caller requested to sync input windows, but there are no
2807 // changes to input windows, notify immediately.
2808 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002809 }
2810
Arthur Hung6cbb9752019-09-05 16:38:18 +08002811 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002812}
2813
2814void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002815 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002816
Robert Carra1257842020-01-31 13:48:28 -08002817 // We use a simple caching algorithm here. mInputDirty begins as true,
2818 // after we call setInputWindows we set it to false, so
2819 // in the future we wont call it again.. We set input dirty to true again
2820 // when any layer that hasInput() has a transaction performed on it
2821 // or when any parent or relative parent of such a layer has a transaction
2822 // performed on it. Not all of these transactions will really result in
2823 // input changes but all input changes will spring from these transactions
2824 // so the cache is safe but not optimal. It seems like it might be annoyingly
2825 // costly to cache and comapre the actual InputWindowHandle vector though.
Robert Carr0854b992020-03-11 12:09:42 -07002826 if (!mInputDirty && !mInputWindowCommands.syncInputWindows) {
Robert Carra1257842020-01-31 13:48:28 -08002827 return;
2828 }
2829
Robert Carr720e5062018-07-30 17:45:14 -07002830 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2831 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002832 // When calculating the screen bounds we ignore the transparent region since it may
2833 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002834 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002835 }
2836 });
chaviw291d88a2019-02-14 10:33:58 -08002837
2838 mInputFlinger->setInputWindows(inputHandles,
2839 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2840 : nullptr);
Robert Carra1257842020-01-31 13:48:28 -08002841
2842 mInputDirty = false;
Robert Carr720e5062018-07-30 17:45:14 -07002843}
2844
Vishnu Nairec0ab382019-02-13 15:32:56 -08002845void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002846 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002847 mPendingInputWindowCommands.clear();
2848}
2849
Riley Andrews03414a12014-07-01 14:22:59 -07002850void SurfaceFlinger::updateCursorAsync()
2851{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002852 compositionengine::CompositionRefreshArgs refreshArgs;
2853 for (const auto& [_, display] : mDisplays) {
2854 if (display->getId()) {
2855 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002856 }
2857 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002858
2859 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002860}
2861
Ady Abraham2139f732019-11-13 18:56:40 -08002862void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002863 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2864 // If this is called from the main thread mStateLock must be locked before
2865 // Currently the only way to call this function from the main thread is from
2866 // Sheduler::chooseRefreshRateForContent
2867
2868 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002869 changeRefreshRateLocked(refreshRate, event);
2870}
2871
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002872void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2873 if (mScheduler) {
2874 // In practice it's not allowed to hotplug in/out the primary display once it's been
2875 // connected during startup, but some tests do it, so just warn and return.
2876 ALOGW("Can't re-init scheduler");
2877 return;
2878 }
2879
Ady Abraham2139f732019-11-13 18:56:40 -08002880 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002881 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002882 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002883 primaryDisplayId),
2884 currentConfig);
2885 mRefreshRateStats =
2886 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2887 currentConfig, HWC_POWER_MODE_OFF);
2888 mRefreshRateStats->setConfigMode(currentConfig);
2889
Ady Abraham9e16a482019-12-03 17:19:41 -08002890 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2891
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002892 // start the EventThread
2893 mScheduler =
2894 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002895 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002896 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002897 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002898 impl::EventThread::InterceptVSyncsCallback());
2899 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002900 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002901 [this](nsecs_t timestamp) {
2902 mInterceptor->saveVSyncEvent(timestamp);
2903 });
2904
2905 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2906 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002907 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002908
2909 mRegionSamplingThread =
2910 new RegionSamplingThread(*this, *mScheduler,
2911 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002912 // Dispatch a config change request for the primary display on scheduler
2913 // initialization, so that the EventThreads always contain a reference to a
2914 // prior configuration.
2915 //
2916 // This is a bit hacky, but this avoids a back-pointer into the main SF
2917 // classes from EventThread, and there should be no run-time binder cost
2918 // anyway since there are no connected apps at this point.
2919 const nsecs_t vsyncPeriod =
2920 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2921 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2922 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002923}
2924
Mathias Agopian4fec8732012-06-29 14:12:52 -07002925void SurfaceFlinger::commitTransaction()
2926{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002927 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002928
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002929 mTransactionPending = false;
2930 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002931 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002932}
2933
Lloyd Pique58e24a32019-08-01 15:50:14 -07002934void SurfaceFlinger::commitTransactionLocked() {
2935 if (!mLayersPendingRemoval.isEmpty()) {
2936 // Notify removed layers now that they can't be drawn from
2937 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002938 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002939
2940 // Ensure any buffers set to display on any children are released.
2941 if (l->isRemovedFromCurrentState()) {
2942 l->latchAndReleaseBuffer();
2943 }
2944
2945 // If the layer has been removed and has no parent, then it will not be reachable
2946 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2947 // ensure we can copy its current to drawing state.
2948 if (!l->getParent()) {
2949 mOffscreenLayers.emplace(l.get());
2950 }
2951 }
2952 mLayersPendingRemoval.clear();
2953 }
2954
2955 // If this transaction is part of a window animation then the next frame
2956 // we composite should be considered an animation as well.
2957 mAnimCompositionPending = mAnimTransactionPending;
2958
2959 mDrawingState = mCurrentState;
2960 // clear the "changed" flags in current state
2961 mCurrentState.colorMatrixChanged = false;
2962
Edgar Arriaga844fa672020-01-16 14:21:42 -08002963 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002964 layer->commitChildList();
2965
2966 // If the layer can be reached when traversing mDrawingState, then the layer is no
2967 // longer offscreen. Remove the layer from the offscreenLayer set.
2968 if (mOffscreenLayers.count(layer)) {
2969 mOffscreenLayers.erase(layer);
2970 }
2971 });
2972
2973 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002974 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002975}
2976
Nataniel Borges2b796da2019-02-15 13:32:18 -08002977void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2978 if (mTracingEnabledChanged) {
2979 mTracingEnabled = mTracing.isEnabled();
2980 mTracingEnabledChanged = false;
2981 }
2982
2983 // Synchronize with Tracing thread
2984 std::unique_lock<std::mutex> lock;
2985 if (mTracingEnabled) {
2986 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2987 }
2988
2989 lockedOperation();
2990
2991 // Synchronize with Tracing thread
2992 if (mTracingEnabled) {
2993 lock.unlock();
2994 }
2995}
2996
chaviw74d90ad2019-04-26 14:45:26 -07002997void SurfaceFlinger::commitOffscreenLayers() {
2998 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002999 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003000 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3001 if (!trFlags) return;
3002
3003 layer->doTransaction(0);
3004 layer->commitChildList();
3005 });
3006 }
3007}
3008
Chia-I Wuab0c3192017-08-01 11:29:00 -07003009void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003010 for (const auto& [token, displayDevice] : mDisplays) {
3011 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003012 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003013 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003014 }
3015 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003016}
3017
Dan Stoza6b9454d2014-11-07 16:00:59 -08003018bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003019{
Ady Abraham09bd3922019-04-08 10:44:56 -07003020 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003021 ALOGV("handlePageFlip");
3022
Brian Andersond6927fb2016-07-23 23:37:30 -07003023 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003024
Mathias Agopian4fec8732012-06-29 14:12:52 -07003025 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003026 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003027 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003028
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003029 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3030
Eric Penner51c59cd2014-07-28 19:51:58 -07003031 // Store the set of layers that need updates. This set must not change as
3032 // buffers are being latched, as this could result in a deadlock.
3033 // Example: Two producers share the same command stream and:
3034 // 1.) Layer 0 is latched
3035 // 2.) Layer 0 gets a new frame
3036 // 2.) Layer 1 gets a new frame
3037 // 3.) Layer 1 is latched.
3038 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3039 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003040 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003041 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003042 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003043 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003044 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003045 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003046 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003047 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003048 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003049 } else {
3050 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003051 }
Robert Carr2047fae2016-11-28 14:09:09 -08003052 });
3053
chaviw49a108c2019-08-12 11:23:06 -07003054 // The client can continue submitting buffers for offscreen layers, but they will not
3055 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3056 // layers to ensure dequeueBuffer doesn't block indefinitely.
3057 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003058 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003059 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3060 }
3061
Lloyd Piquef2c79392018-12-20 16:23:33 -08003062 if (!mLayersWithQueuedFrames.empty()) {
3063 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3064 // writes to Layer current state. See also b/119481871
3065 Mutex::Autolock lock(mStateLock);
3066
3067 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003068 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003069 mLayersPendingRefresh.push_back(layer);
3070 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003071 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003072 if (layer->isBufferLatched()) {
3073 newDataLatched = true;
3074 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003075 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003076 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003077
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003078 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003079
3080 // If we will need to wake up at some time in the future to deal with a
3081 // queued frame that shouldn't be displayed during this vsync period, wake
3082 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003083 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003084 signalLayerUpdate();
3085 }
3086
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003087 // enter boot animation on first buffer latch
3088 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3089 ALOGI("Enter boot animation");
3090 mBootStage = BootStage::BOOTANIMATION;
3091 }
3092
Edgar Arriaga844fa672020-01-16 14:21:42 -08003093 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003094
Dan Stoza6b9454d2014-11-07 16:00:59 -08003095 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003096 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003097}
3098
Mathias Agopianad456f92011-01-13 17:53:01 -08003099void SurfaceFlinger::invalidateHwcGeometry()
3100{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003101 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003102}
3103
Robert Carrc0df3122019-04-11 13:18:21 -07003104status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3105 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3106 const sp<IBinder>& parentHandle,
3107 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003108 // add this layer to the current state list
3109 {
3110 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003111 sp<Layer> parent;
3112 if (parentHandle != nullptr) {
3113 parent = fromHandle(parentHandle);
3114 if (parent == nullptr) {
3115 return NAME_NOT_FOUND;
3116 }
3117 } else {
3118 parent = parentLayer;
3119 }
3120
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003121 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003122 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abrahamb89ca7d2020-03-04 11:19:37 -08003123 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003124 return NO_MEMORY;
3125 }
Robert Carrc0df3122019-04-11 13:18:21 -07003126
3127 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3128
Robert Carrb89ea9d2018-12-10 13:01:14 -08003129 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003130 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003131 } else if (parent == nullptr) {
3132 lbc->onRemovedFromCurrentState();
3133 } else if (parent->isRemovedFromCurrentState()) {
3134 parent->addChild(lbc);
3135 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003136 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003137 parent->addChild(lbc);
3138 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003139
Yiwei Zhang243b3782018-05-15 17:40:04 -07003140 if (gbc != nullptr) {
3141 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3142 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3143 mMaxGraphicBufferProducerListSize,
3144 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3145 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003146 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Alec Mouri601393f2020-02-21 13:26:52 -08003147 if (mGraphicBufferProducerList.size() > mGraphicBufferProducerListSizeLogThreshold) {
3148 ALOGW("Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3149 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize,
3150 mNumLayers.load());
3151 }
Yiwei Zhang243b3782018-05-15 17:40:04 -07003152 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003153 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003154 }
3155
Mathias Agopian96f08192010-06-02 23:28:45 -07003156 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003157 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003158
Dan Stoza7d89d062015-04-30 13:29:25 -07003159 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003160}
3161
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003162uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003163 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003164}
3165
Mathias Agopian3f844832013-08-07 21:24:32 -07003166uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003167 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003168}
3169
Mathias Agopian3f844832013-08-07 21:24:32 -07003170uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003171 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003172}
3173
3174uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003175 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003176 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003177 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003178 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003179 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180 }
3181 return old;
3182}
3183
Marissa Wall713b63f2018-10-17 15:42:43 -07003184bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003185 // to prevent onHandleDestroyed from being called while the lock is held,
3186 // we must keep a copy of the transactions (specifically the composer
3187 // states) around outside the scope of the lock
3188 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003189 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003190 {
3191 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003192
Valerie Haufce31b82019-04-30 16:41:14 -07003193 auto it = mTransactionQueues.begin();
3194 while (it != mTransactionQueues.end()) {
3195 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003196
Valerie Haufce31b82019-04-30 16:41:14 -07003197 while (!transactionQueue.empty()) {
3198 const auto& transaction = transactionQueue.front();
3199 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003200 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003201 transaction.states)) {
3202 setTransactionFlags(eTransactionFlushNeeded);
3203 break;
3204 }
3205 transactions.push_back(transaction);
3206 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3207 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003208 transaction.buffer, transaction.postTime,
3209 transaction.privileged, transaction.hasListenerCallbacks,
3210 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003211 transactionQueue.pop();
3212 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003213 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003214
Valerie Haufce31b82019-04-30 16:41:14 -07003215 if (transactionQueue.empty()) {
3216 it = mTransactionQueues.erase(it);
3217 mTransactionCV.broadcast();
3218 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003219 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003220 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003221 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003222 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003223 return flushedATransaction;
3224}
3225
3226bool SurfaceFlinger::transactionFlushNeeded() {
3227 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003228}
3229
chaviwca27f252018-02-06 16:46:39 -08003230
Marissa Wall17b4e452018-12-26 16:32:34 -08003231bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003232 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003233 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003234 if (!useCachedExpectedPresentTime)
3235 populateExpectedPresentTime();
3236
3237 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003238 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3239 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3240 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3241 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3242 return false;
3243 }
3244
Marissa Wall713b63f2018-10-17 15:42:43 -07003245 for (const ComposerState& state : states) {
3246 const layer_state_t& s = state.state;
3247 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3248 continue;
3249 }
3250 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003251 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003252 }
3253 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003254 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003255}
3256
Valerie Hau9dab9732019-08-20 09:29:25 -07003257void SurfaceFlinger::setTransactionState(
3258 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3259 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3260 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3261 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003262 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003263
Valerie Haubc6ddb12019-03-08 11:10:15 -08003264 const int64_t postTime = systemTime();
3265
Robert Carr14167e02019-02-13 13:50:55 -08003266 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3267
Mathias Agopian698c0872011-06-28 19:09:31 -07003268 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003269
Marissa Wall713b63f2018-10-17 15:42:43 -07003270 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003271 auto itr = mTransactionQueues.find(applyToken);
3272 // if this is an animation frame, wait until prior animation frame has
3273 // been applied by SF
3274 if (flags & eAnimation) {
3275 while (itr != mTransactionQueues.end()) {
3276 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3277 if (CC_UNLIKELY(err != NO_ERROR)) {
3278 ALOGW_IF(err == TIMED_OUT,
3279 "setTransactionState timed out "
3280 "waiting for animation frame to apply");
3281 break;
3282 }
3283 itr = mTransactionQueues.find(applyToken);
3284 }
3285 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003286
3287 // Expected present time is computed and cached on invalidate, so it may be stale.
3288 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3289 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003290 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003291 uncacheBuffer, postTime, privileged,
3292 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003293 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003294 return;
3295 }
3296
Valerie Haubc6ddb12019-03-08 11:10:15 -08003297 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003298 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3299 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003300}
3301
Valerie Hau9dab9732019-08-20 09:29:25 -07003302void SurfaceFlinger::applyTransactionState(
3303 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3304 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3305 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3306 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3307 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003308 uint32_t transactionFlags = 0;
3309
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003310 if (flags & eAnimation) {
3311 // For window updates that are part of an animation we must wait for
3312 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003313 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003314 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003315 if (CC_UNLIKELY(err != NO_ERROR)) {
3316 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003317 // caller after a few seconds.
3318 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3319 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003320 mAnimTransactionPending = false;
3321 break;
3322 }
3323 }
3324 }
3325
chaviwca27f252018-02-06 16:46:39 -08003326 for (const DisplayState& display : displays) {
3327 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003328 }
3329
Valerie Hau9dab9732019-08-20 09:29:25 -07003330 // start and end registration for listeners w/ no surface so they can get their callback. Note
3331 // that listeners with SurfaceControls will start registration during setClientStateLocked
3332 // below.
3333 for (const auto& listener : listenerCallbacks) {
3334 mTransactionCompletedThread.startRegistration(listener);
3335 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003336 }
3337
Valerie Hau9dab9732019-08-20 09:29:25 -07003338 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003339 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003340 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003341 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3342 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003343 }
3344
Valerie Hau9dab9732019-08-20 09:29:25 -07003345 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003346 mTransactionCompletedThread.endRegistration(listenerCallback);
3347 }
3348
Marissa Walle2ffb422018-10-12 11:33:52 -07003349 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003350 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003351 mTransactionCompletedThread.sendCallbacks();
3352 }
3353 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003354
chaviw273171b2018-12-26 11:46:30 -08003355 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3356
Marissa Wall947d34e2019-03-29 14:03:53 -07003357 if (uncacheBuffer.isValid()) {
3358 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003359 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003360 }
3361
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003362 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3363 // anyway. This can be used as a flush mechanism for previous async transactions.
3364 // Empty animation transaction can be used to simulate back-pressure, so also force a
3365 // transaction for empty animation transactions.
3366 if (transactionFlags == 0 &&
3367 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003368 transactionFlags = eTransactionNeeded;
3369 }
3370
Marissa Wall06255332019-03-27 13:48:27 -07003371 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3372 // so we don't have to wake up again next frame to preform an uneeded traversal.
3373 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3374 transactionFlags = transactionFlags & (~eTraversalNeeded);
3375 mTraversalNeededMainThread = true;
3376 }
3377
Mathias Agopian386aa982011-11-07 21:58:03 -08003378 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003379 if (mInterceptor->isEnabled()) {
3380 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003381 }
Irvel468051e2016-06-13 16:44:44 -07003382
Mathias Agopian386aa982011-11-07 21:58:03 -08003383 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003384 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3385 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003386 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003387
3388 // if this is a synchronous transaction, wait for it to take effect
3389 // before returning.
3390 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003391 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003392 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003393 if (flags & eAnimation) {
3394 mAnimTransactionPending = true;
3395 }
chaviw4fe36852019-04-15 16:25:49 -07003396 if (mPendingInputWindowCommands.syncInputWindows) {
3397 mPendingSyncInputWindows = true;
3398 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003399
3400 // applyTransactionState can be called by either the main SF thread or by
3401 // another process through setTransactionState. While a given process may wish
3402 // to wait on synchronous transactions, the main SF thread should never
3403 // be blocked. Therefore, we only wait if isMainThread is false.
3404 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003405 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3406 if (CC_UNLIKELY(err != NO_ERROR)) {
3407 // just in case something goes wrong in SF, return to the
3408 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003409 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3410 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003411 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003412 break;
3413 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003414 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003415 }
3416}
3417
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003418uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3419 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3420 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003421
Mathias Agopiane57f2922012-08-09 16:29:12 -07003422 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003423 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3424
3425 const uint32_t what = s.what;
3426 if (what & DisplayState::eSurfaceChanged) {
3427 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3428 state.surface = s.surface;
3429 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003430 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003431 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003432 if (what & DisplayState::eLayerStackChanged) {
3433 if (state.layerStack != s.layerStack) {
3434 state.layerStack = s.layerStack;
3435 flags |= eDisplayTransactionNeeded;
3436 }
3437 }
3438 if (what & DisplayState::eDisplayProjectionChanged) {
3439 if (state.orientation != s.orientation) {
3440 state.orientation = s.orientation;
3441 flags |= eDisplayTransactionNeeded;
3442 }
3443 if (state.frame != s.frame) {
3444 state.frame = s.frame;
3445 flags |= eDisplayTransactionNeeded;
3446 }
3447 if (state.viewport != s.viewport) {
3448 state.viewport = s.viewport;
3449 flags |= eDisplayTransactionNeeded;
3450 }
3451 }
3452 if (what & DisplayState::eDisplaySizeChanged) {
3453 if (state.width != s.width) {
3454 state.width = s.width;
3455 flags |= eDisplayTransactionNeeded;
3456 }
3457 if (state.height != s.height) {
3458 state.height = s.height;
3459 flags |= eDisplayTransactionNeeded;
3460 }
3461 }
3462
Mathias Agopiane57f2922012-08-09 16:29:12 -07003463 return flags;
3464}
3465
Robert Carr14167e02019-02-13 13:50:55 -08003466bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003467 IPCThreadState* ipc = IPCThreadState::self();
3468 const int pid = ipc->getCallingPid();
3469 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003470 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003471 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003472 return false;
3473 }
3474 return true;
3475}
3476
Marissa Wall3dad52d2019-03-22 14:03:19 -07003477uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003478 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3479 bool privileged,
3480 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003481 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003482
Valerie Hau9dab9732019-08-20 09:29:25 -07003483 for (auto& listener : s.listeners) {
3484 // note that startRegistration will not re-register if the listener has
3485 // already be registered for a prior surface control
3486 mTransactionCompletedThread.startRegistration(listener);
3487 listenerCallbacks.insert(listener);
3488 }
3489
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003490 sp<Layer> layer = nullptr;
3491 if (s.surface) {
3492 layer = fromHandle(s.surface);
3493 } else {
3494 // The client may provide us a null handle. Treat it as if the layer was removed.
3495 ALOGW("Attempt to set client state with a null layer handle");
3496 }
chaviw8b3871a2017-11-01 17:41:01 -07003497 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003498 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003499 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003500 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003501 }
chaviw8b3871a2017-11-01 17:41:01 -07003502 return 0;
3503 }
3504
chaviw8b3871a2017-11-01 17:41:01 -07003505 uint32_t flags = 0;
3506
Garfield Tan8a3083e2018-12-03 13:21:07 -08003507 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003508
3509 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3510 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003511 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003512 layer->pushPendingState();
3513 }
3514
Valerie Hau871d6352020-01-29 08:44:02 -08003515 // Only set by BLAST adapter layers
3516 if (what & layer_state_t::eProducerDisconnect) {
3517 layer->onDisconnect();
3518 }
3519
chaviw8b3871a2017-11-01 17:41:01 -07003520 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003521 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003522 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003523 }
chaviw8b3871a2017-11-01 17:41:01 -07003524 }
3525 if (what & layer_state_t::eLayerChanged) {
3526 // NOTE: index needs to be calculated before we update the state
3527 const auto& p = layer->getParent();
3528 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003529 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003530 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003531 mCurrentState.layersSortedByZ.removeAt(idx);
3532 mCurrentState.layersSortedByZ.add(layer);
3533 // we need traversal (state changed)
3534 // AND transaction (list changed)
3535 flags |= eTransactionNeeded|eTraversalNeeded;
3536 }
chaviw8b3871a2017-11-01 17:41:01 -07003537 } else {
3538 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003539 flags |= eTransactionNeeded|eTraversalNeeded;
3540 }
3541 }
chaviw8b3871a2017-11-01 17:41:01 -07003542 }
3543 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003544 // NOTE: index needs to be calculated before we update the state
3545 const auto& p = layer->getParent();
3546 if (p == nullptr) {
3547 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3548 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3549 mCurrentState.layersSortedByZ.removeAt(idx);
3550 mCurrentState.layersSortedByZ.add(layer);
3551 // we need traversal (state changed)
3552 // AND transaction (list changed)
3553 flags |= eTransactionNeeded|eTraversalNeeded;
3554 }
3555 } else {
3556 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3557 flags |= eTransactionNeeded|eTraversalNeeded;
3558 }
chaviw8b3871a2017-11-01 17:41:01 -07003559 }
3560 }
3561 if (what & layer_state_t::eSizeChanged) {
3562 if (layer->setSize(s.w, s.h)) {
3563 flags |= eTraversalNeeded;
3564 }
3565 }
3566 if (what & layer_state_t::eAlphaChanged) {
3567 if (layer->setAlpha(s.alpha))
3568 flags |= eTraversalNeeded;
3569 }
3570 if (what & layer_state_t::eColorChanged) {
3571 if (layer->setColor(s.color))
3572 flags |= eTraversalNeeded;
3573 }
Peiyong Lind3788632018-09-18 16:01:31 -07003574 if (what & layer_state_t::eColorTransformChanged) {
3575 if (layer->setColorTransform(s.colorTransform)) {
3576 flags |= eTraversalNeeded;
3577 }
3578 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003579 if (what & layer_state_t::eBackgroundColorChanged) {
3580 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3581 flags |= eTraversalNeeded;
3582 }
3583 }
chaviw8b3871a2017-11-01 17:41:01 -07003584 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003585 // TODO: b/109894387
3586 //
3587 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3588 // rotation. To see the problem observe that if we have a square parent, and a child
3589 // of the same size, then we rotate the child 45 degrees around it's center, the child
3590 // must now be cropped to a non rectangular 8 sided region.
3591 //
3592 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3593 // private API, and the WindowManager only uses rotation in one case, which is on a top
3594 // level layer in which cropping is not an issue.
3595 //
3596 // However given that abuse of rotation matrices could lead to surfaces extending outside
3597 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3598 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3599 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003600 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003601 flags |= eTraversalNeeded;
3602 }
3603 if (what & layer_state_t::eTransparentRegionChanged) {
3604 if (layer->setTransparentRegionHint(s.transparentRegion))
3605 flags |= eTraversalNeeded;
3606 }
3607 if (what & layer_state_t::eFlagsChanged) {
3608 if (layer->setFlags(s.flags, s.mask))
3609 flags |= eTraversalNeeded;
3610 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003611 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003612 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003613 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003614 if (what & layer_state_t::eCornerRadiusChanged) {
3615 if (layer->setCornerRadius(s.cornerRadius))
3616 flags |= eTraversalNeeded;
3617 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003618 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003619 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3620 }
chaviw8b3871a2017-11-01 17:41:01 -07003621 if (what & layer_state_t::eLayerStackChanged) {
3622 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3623 // We only allow setting layer stacks for top level layers,
3624 // everything else inherits layer stack from its parent.
3625 if (layer->hasParent()) {
3626 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003627 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003628 } else if (idx < 0) {
3629 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003630 "that also does not appear in the top level layer list. Something"
3631 " has gone wrong.",
3632 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003633 } else if (layer->setLayerStack(s.layerStack)) {
3634 mCurrentState.layersSortedByZ.removeAt(idx);
3635 mCurrentState.layersSortedByZ.add(layer);
3636 // we need traversal (state changed)
3637 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003638 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003639 }
3640 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003641 if (what & layer_state_t::eDeferTransaction_legacy) {
3642 if (s.barrierHandle_legacy != nullptr) {
3643 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3644 } else if (s.barrierGbp_legacy != nullptr) {
3645 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003646 if (authenticateSurfaceTextureLocked(gbp)) {
3647 const auto& otherLayer =
3648 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003649 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003650 } else {
3651 ALOGE("Attempt to defer transaction to to an"
3652 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003653 }
3654 }
chaviw8b3871a2017-11-01 17:41:01 -07003655 // We don't trigger a traversal here because if no other state is
3656 // changed, we don't want this to cause any more work
3657 }
chaviw8b3871a2017-11-01 17:41:01 -07003658 if (what & layer_state_t::eReparentChildren) {
3659 if (layer->reparentChildren(s.reparentHandle)) {
3660 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003661 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003662 }
chaviw8b3871a2017-11-01 17:41:01 -07003663 if (what & layer_state_t::eDetachChildren) {
3664 layer->detachChildren();
3665 }
3666 if (what & layer_state_t::eOverrideScalingModeChanged) {
3667 layer->setOverrideScalingMode(s.overrideScalingMode);
3668 // We don't trigger a traversal here because if no other state is
3669 // changed, we don't want this to cause any more work
3670 }
Marissa Wall61c58622018-07-18 10:12:20 -07003671 if (what & layer_state_t::eTransformChanged) {
3672 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3673 }
3674 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3675 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3676 flags |= eTraversalNeeded;
3677 }
3678 if (what & layer_state_t::eCropChanged) {
3679 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3680 }
Marissa Wall861616d2018-10-22 12:52:23 -07003681 if (what & layer_state_t::eFrameChanged) {
3682 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3683 }
Marissa Wall61c58622018-07-18 10:12:20 -07003684 if (what & layer_state_t::eAcquireFenceChanged) {
3685 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3686 }
3687 if (what & layer_state_t::eDataspaceChanged) {
3688 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3689 }
3690 if (what & layer_state_t::eHdrMetadataChanged) {
3691 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3692 }
3693 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3694 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3695 }
3696 if (what & layer_state_t::eApiChanged) {
3697 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3698 }
3699 if (what & layer_state_t::eSidebandStreamChanged) {
3700 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3701 }
Robert Carr720e5062018-07-30 17:45:14 -07003702 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003703 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003704 layer->setInputInfo(s.inputInfo);
3705 flags |= eTraversalNeeded;
3706 } else {
3707 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3708 }
Robert Carr720e5062018-07-30 17:45:14 -07003709 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003710 if (what & layer_state_t::eMetadataChanged) {
3711 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3712 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003713 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3714 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3715 flags |= eTraversalNeeded;
3716 }
3717 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003718 if (what & layer_state_t::eShadowRadiusChanged) {
3719 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3720 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003721 if (what & layer_state_t::eFrameRateSelectionPriority) {
3722 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3723 flags |= eTraversalNeeded;
3724 }
3725 }
Steven Thomas3172e202020-01-06 19:25:30 -08003726 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003727 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3728 "SurfaceFlinger::setClientStateLocked") &&
3729 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3730 Layer::FrameRate::convertCompatibility(
3731 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003732 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003733 }
Steven Thomas3172e202020-01-06 19:25:30 -08003734 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003735 // This has to happen after we reparent children because when we reparent to null we remove
3736 // child layers from current state and remove its relative z. If the children are reparented in
3737 // the same transaction, then we have to make sure we reparent the children first so we do not
3738 // lose its relative z order.
3739 if (what & layer_state_t::eReparent) {
3740 bool hadParent = layer->hasParent();
3741 if (layer->reparent(s.parentHandleForChild)) {
3742 if (!hadParent) {
3743 mCurrentState.layersSortedByZ.remove(layer);
3744 }
3745 flags |= eTransactionNeeded | eTraversalNeeded;
3746 }
3747 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003748 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003749 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3750 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003751 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3752 }
3753 }
Marissa Wall78b72202019-03-15 14:58:34 -07003754 bool bufferChanged = what & layer_state_t::eBufferChanged;
3755 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3756 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003757 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003758 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003759 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3760 if (success) {
3761 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3762 success = ClientCache::getInstance()
3763 .registerErasedRecipient(s.cachedBuffer,
3764 wp<ClientCache::ErasedRecipient>(this));
3765 if (!success) {
3766 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3767 }
3768 }
Marissa Wall78b72202019-03-15 14:58:34 -07003769 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003770 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003771 } else if (bufferChanged) {
3772 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003773 }
Marissa Wall78b72202019-03-15 14:58:34 -07003774 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003775 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3776 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003777 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003778 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003779 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003780 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3781 // Do not put anything that updates layer state or modifies flags after
3782 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003783 return flags;
3784}
3785
chaviw273171b2018-12-26 11:46:30 -08003786uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3787 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003788 if (inputWindowCommands.syncInputWindows) {
3789 flags |= eTraversalNeeded;
3790 }
3791
Vishnu Nairec0ab382019-02-13 15:32:56 -08003792 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003793 return flags;
3794}
3795
chaviwfe94a222019-08-21 13:52:59 -07003796status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3797 sp<IBinder>* outHandle) {
3798 if (!mirrorFromHandle) {
3799 return NAME_NOT_FOUND;
3800 }
3801
3802 sp<Layer> mirrorLayer;
3803 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003804 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003805
3806 {
3807 Mutex::Autolock _l(mStateLock);
3808 mirrorFrom = fromHandle(mirrorFromHandle);
3809 if (!mirrorFrom) {
3810 return NAME_NOT_FOUND;
3811 }
3812
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003813 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3814 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003815 if (result != NO_ERROR) {
3816 return result;
3817 }
3818
3819 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3820 }
3821
3822 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3823}
3824
Marissa Wall2d814fb2019-04-09 18:52:57 +00003825status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3826 uint32_t h, PixelFormat format, uint32_t flags,
3827 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003828 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003829 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3830 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003831 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003832 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003833 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003834 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003835 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003836
Robert Carrc0df3122019-04-11 13:18:21 -07003837 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3838 "Expected only one of parentLayer or parentHandle to be non-null. "
3839 "Programmer error?");
3840
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003841 status_t result = NO_ERROR;
3842
3843 sp<Layer> layer;
3844
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003845 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003846
Evan Roskya1f1e152019-01-24 16:17:46 -08003847 bool primaryDisplayOnly = false;
3848
3849 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3850 // TODO b/64227542
3851 if (metadata.has(METADATA_WINDOW_TYPE)) {
3852 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3853 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003854 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003855 primaryDisplayOnly = true;
3856 }
3857 }
3858
Mathias Agopian3165cc22012-08-08 19:42:09 -07003859 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003860 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003861 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3862 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003863
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003864 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003865 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003866 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003867 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003868 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003869 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003870 // check if buffer size is set for color layer.
3871 if (w > 0 || h > 0) {
3872 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3873 int(w), int(h));
3874 return BAD_VALUE;
3875 }
3876
Vishnu Nairfa247b12020-02-11 08:58:26 -08003877 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3878 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003879 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003880 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003881 // check if buffer size is set for container layer.
3882 if (w > 0 || h > 0) {
3883 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3884 int(w), int(h));
3885 return BAD_VALUE;
3886 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003887 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3888 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003889 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003890 default:
3891 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003892 break;
3893 }
3894
Dan Stoza7d89d062015-04-30 13:29:25 -07003895 if (result != NO_ERROR) {
3896 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003897 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003898
Evan Roskya1f1e152019-01-24 16:17:46 -08003899 if (primaryDisplayOnly) {
3900 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003901 }
3902
Robert Carrb89ea9d2018-12-10 13:01:14 -08003903 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003904 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3905 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003906 if (result != NO_ERROR) {
3907 return result;
3908 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003909 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003910
3911 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003912 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003913}
3914
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003915std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3916 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003917
3918 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003919 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003920
Dan Stoza436ccf32018-06-21 12:10:12 -07003921 // Grab the state lock since we're accessing mCurrentState
3922 Mutex::Autolock lock(mStateLock);
3923
Cody Northropbc755282017-03-31 12:00:08 -06003924 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003925 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003926 while (matchFound) {
3927 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003928 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003929 if (layer->getName() == uniqueName) {
3930 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003931 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003932 }
3933 });
3934 }
3935
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003936 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003937 return uniqueName;
3938}
3939
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003940status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003941 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003942 LayerMetadata metadata, PixelFormat& format,
3943 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003944 sp<IGraphicBufferProducer>* gbp,
3945 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003946 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003947 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003948 case PIXEL_FORMAT_TRANSPARENT:
3949 case PIXEL_FORMAT_TRANSLUCENT:
3950 format = PIXEL_FORMAT_RGBA_8888;
3951 break;
3952 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003953 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003954 break;
3955 }
3956
chaviwb4c6e582019-08-16 14:35:07 -07003957 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003958 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003959 args.textureName = getNewTexture();
3960 {
3961 // Grab the SF state lock during this since it's the only safe way to access
3962 // RenderEngine when creating a BufferLayerConsumer
3963 // TODO: Check if this lock is still needed here
3964 Mutex::Autolock lock(mStateLock);
3965 layer = getFactory().createBufferQueueLayer(args);
3966 }
3967
Marissa Wallfd668622018-05-10 10:21:13 -07003968 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003969 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003970 *handle = layer->getHandle();
3971 *gbp = layer->getProducer();
3972 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003973 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003974
Marissa Wallfd668622018-05-10 10:21:13 -07003975 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003976 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003977}
3978
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003979status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003980 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003981 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003982 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003983 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003984 args.displayDevice = getDefaultDisplayDevice();
3985 args.textureName = getNewTexture();
3986 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003987 if (outTransformHint) {
3988 *outTransformHint = layer->getTransformHint();
3989 }
Marissa Wall61c58622018-07-18 10:12:20 -07003990 *handle = layer->getHandle();
3991 *outLayer = layer;
3992
3993 return NO_ERROR;
3994}
3995
Vishnu Nairfa247b12020-02-11 08:58:26 -08003996status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3997 uint32_t h, uint32_t flags, LayerMetadata metadata,
3998 sp<IBinder>* handle, sp<Layer>* outLayer) {
3999 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004000 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004001 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004002 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004003}
4004
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004005status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004006 uint32_t w, uint32_t h, uint32_t flags,
4007 LayerMetadata metadata, sp<IBinder>* handle,
4008 sp<Layer>* outLayer) {
4009 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004010 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004011 *handle = (*outLayer)->getHandle();
4012 return NO_ERROR;
4013}
4014
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004015void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004016 mLayersPendingRemoval.add(layer);
4017 mLayersRemoved = true;
4018 setTransactionFlags(eTransactionNeeded);
4019}
4020
Robert Carr695d5282018-12-18 15:27:58 -08004021void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004022{
Robert Carr2e102c92018-10-23 12:11:15 -07004023 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004024 // If a layer has a parent, we allow it to out-live it's handle
4025 // with the idea that the parent holds a reference and will eventually
4026 // be cleaned up. However no one cleans up the top-level so we do so
4027 // here.
4028 if (layer->getParent() == nullptr) {
4029 mCurrentState.layersSortedByZ.remove(layer);
4030 }
4031 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004032
4033 auto it = mLayersByLocalBinderToken.begin();
4034 while (it != mLayersByLocalBinderToken.end()) {
4035 if (it->second == layer) {
4036 it = mLayersByLocalBinderToken.erase(it);
4037 } else {
4038 it++;
4039 }
4040 }
4041
Robert Carr695d5282018-12-18 15:27:58 -08004042 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004043}
4044
Mathias Agopianb60314a2012-04-10 22:09:54 -07004045// ---------------------------------------------------------------------------
4046
Andy McFadden13a082e2012-08-24 10:16:42 -07004047void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004048 const auto display = getDefaultDisplayDeviceLocked();
4049 if (!display) return;
4050
4051 const sp<IBinder> token = display->getDisplayToken().promote();
4052 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004053
Jesse Hall01e29052013-02-19 16:13:35 -08004054 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004055 Vector<ComposerState> state;
4056 Vector<DisplayState> displays;
4057 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004058 d.what = DisplayState::eDisplayProjectionChanged |
4059 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004060 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004061 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004062 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004063 d.frame.makeInvalid();
4064 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004065 d.width = 0;
4066 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004067 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004068 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4069 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004070
Dominik Laskowskie9774092018-12-11 10:04:24 -08004071 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004072
Dominik Laskowski83b88212018-12-11 13:34:06 -08004073 const nsecs_t vsyncPeriod = getVsyncPeriod();
4074 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004075
Brian Andersond0010582017-03-07 13:20:31 -08004076 // Use phase of 0 since phase is not known.
4077 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004078 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004079 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004080}
4081
4082void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004083 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004084 postMessageAsync(
4085 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004086}
4087
Ady Abraham27c70212019-06-11 10:52:26 -07004088void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4089 if (mHWCVsyncState != enabled) {
4090 getHwComposer().setVsyncEnabled(displayId, enabled);
4091 mHWCVsyncState = enabled;
4092 }
4093}
4094
Dominik Laskowskie9774092018-12-11 10:04:24 -08004095void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004096 if (display->isVirtual()) {
4097 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004098 return;
4099 }
4100
Dominik Laskowski075d3172018-05-24 15:50:06 -07004101 const auto displayId = display->getId();
4102 LOG_ALWAYS_FATAL_IF(!displayId);
4103
Dominik Laskowski34157762018-10-31 13:07:19 -07004104 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004105
4106 int currentMode = display->getPowerMode();
4107 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004108 return;
4109 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004110
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004111 display->setPowerMode(mode);
4112
Lloyd Pique4dccc412018-01-22 17:21:36 -08004113 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004114 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004115 }
4116
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004117 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004118 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004119 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004120 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004121 mScheduler->onScreenAcquired(mAppConnectionHandle);
4122 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004123 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004124
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004125 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004126 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004127 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004128
4129 struct sched_param param = {0};
4130 param.sched_priority = 1;
4131 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4132 ALOGW("Couldn't set SCHED_FIFO on display on");
4133 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004134 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004135 // Turn off the display
4136 struct sched_param param = {0};
4137 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4138 ALOGW("Couldn't set SCHED_OTHER on display off");
4139 }
4140
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004141 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004142 mScheduler->disableHardwareVsync(true);
4143 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004144 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004145
Ady Abraham27c70212019-06-11 10:52:26 -07004146 // Make sure HWVsync is disabled before turning off the display
4147 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4148
Dominik Laskowski075d3172018-05-24 15:50:06 -07004149 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004150 mVisibleRegionsDirty = true;
4151 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004152 } else if (mode == HWC_POWER_MODE_DOZE ||
4153 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004154 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004155 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004156 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004157 mScheduler->onScreenAcquired(mAppConnectionHandle);
4158 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004159 }
4160 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4161 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004162 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004163 mScheduler->disableHardwareVsync(true);
4164 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004165 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004166 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004167 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004168 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004169 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004170 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004171
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004172 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004173 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004174 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004175 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004176 }
4177
Dominik Laskowski34157762018-10-31 13:07:19 -07004178 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004179}
4180
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004181void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004182 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004183 const auto display = getDisplayDevice(displayToken);
4184 if (!display) {
4185 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4186 displayToken.get());
4187 } else if (display->isVirtual()) {
4188 ALOGW("Attempt to set power mode %d for virtual display", mode);
4189 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004190 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004191 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004192 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004193}
4194
4195// ---------------------------------------------------------------------------
4196
Dominik Laskowskic2867142019-01-21 11:33:38 -08004197status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4198 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004199 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004200
Mathias Agopianbd115332013-04-18 16:41:04 -07004201 IPCThreadState* ipc = IPCThreadState::self();
4202 const int pid = ipc->getCallingPid();
4203 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004204
Mathias Agopianbd115332013-04-18 16:41:04 -07004205 if ((uid != AID_SHELL) &&
4206 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004207 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4208 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004209 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004210 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004211 // (this would indicate SF is stuck, but we want to be able to
4212 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004213 status_t err = mStateLock.timedLock(s2ns(1));
4214 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004215 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004216 StringAppendF(&result,
4217 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4218 "(no locks held)\n",
4219 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004220 }
4221
Dominik Laskowskic2867142019-01-21 11:33:38 -08004222 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004223 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004224 {"--dispsync"s,
4225 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004226 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004227 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4228 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4229 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4230 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4231 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4232 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004233 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004234 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4235 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004236
Dominik Laskowskic2867142019-01-21 11:33:38 -08004237 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004238
Dominik Laskowski46470112019-08-02 13:13:11 -07004239 const auto it = dumpers.find(flag);
4240 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004241 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004242 } else if (!asProto) {
4243 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004244 }
4245
Mathias Agopian9795c422009-08-26 16:36:26 -07004246 if (locked) {
4247 mStateLock.unlock();
4248 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004249
Dominik Laskowski46470112019-08-02 13:13:11 -07004250 if (it == dumpers.end()) {
4251 const LayersProto layersProto = dumpProtoFromMainThread();
4252 if (asProto) {
4253 result.append(layersProto.SerializeAsString());
4254 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004255 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004256 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4257 result.append(LayerProtoParser::layerTreeToString(layerTree));
4258 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004259 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004260 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004261 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004262 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004263 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004264 return NO_ERROR;
4265}
4266
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004267status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4268 if (asProto && mTracing.isEnabled()) {
4269 mTracing.writeToFileAsync();
4270 }
4271
4272 return doDump(fd, DumpArgs(), asProto);
4273}
4274
Dominik Laskowskic2867142019-01-21 11:33:38 -08004275void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004276 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004277 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004278}
4279
Dominik Laskowskic2867142019-01-21 11:33:38 -08004280void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004281 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004282
Dominik Laskowskic2867142019-01-21 11:33:38 -08004283 if (args.size() > 1) {
4284 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004285 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004286 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004287 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004288 }
Robert Carr2047fae2016-11-28 14:09:09 -08004289 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004290 } else {
4291 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004292 }
4293}
4294
Dominik Laskowskic2867142019-01-21 11:33:38 -08004295void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004296 const bool clearAll = args.size() < 2;
4297 const auto name = clearAll ? String8() : String8(args[1]);
4298
Edgar Arriaga844fa672020-01-16 14:21:42 -08004299 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004300 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004301 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004302 }
Robert Carr2047fae2016-11-28 14:09:09 -08004303 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004304
Svetoslavd85084b2014-03-20 10:28:31 -07004305 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004306}
4307
Dominik Laskowskic2867142019-01-21 11:33:38 -08004308void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4309 mTimeStats->parseArgs(asProto, args, result);
4310}
4311
Jamie Gennis6547ff42013-07-16 20:12:42 -07004312// This should only be called from the main thread. Otherwise it would need
4313// the lock and should use mCurrentState rather than mDrawingState.
4314void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004315 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004316 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004317 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004318
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004319 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004320}
4321
Yiwei Zhang5434a782018-12-05 18:06:32 -08004322void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004323 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004324
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004325 if (isLayerTripleBufferingDisabled())
4326 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004327
Yiwei Zhang5434a782018-12-05 18:06:32 -08004328 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4329 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4330 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4331 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4332 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4333 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004334 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004335}
4336
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004337void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004338 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004339
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004340 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004341 result.append("\n");
4342
Ady Abraham9e16a482019-12-03 17:19:41 -08004343 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004344 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004345 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004346 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004347
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004348 HwcConfigIndexType defaultConfig;
4349 float minFps, maxFps;
4350 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004351 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004352 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004353 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004354 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004355 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4356 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004357
Ana Krulecc2870422019-01-29 19:00:58 -08004358 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004359}
4360
Yiwei Zhang5434a782018-12-05 18:06:32 -08004361void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4362 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004363 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4364 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004365 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004366 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004367 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004368 }
David Sodman4a36e932017-11-07 14:29:47 -08004369 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004370 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004371 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004372 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4373 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004374}
4375
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004376void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4377 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004378 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4379 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004380 for (const auto& segment : history) {
4381 if (!segment.usedThirdBuffer) {
4382 stats.twoBufferTime += segment.totalTime;
4383 }
4384 if (segment.occupancyAverage < 1.0f) {
4385 stats.doubleBufferedTime += segment.totalTime;
4386 } else if (segment.occupancyAverage < 2.0f) {
4387 stats.tripleBufferedTime += segment.totalTime;
4388 }
4389 ++stats.numSegments;
4390 stats.totalTime += segment.totalTime;
4391 }
4392}
4393
Yiwei Zhang5434a782018-12-05 18:06:32 -08004394void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4395 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004396
4397 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4398 const size_t count = currentLayers.size();
4399 for (size_t i=0 ; i<count ; i++) {
4400 currentLayers[i]->dumpFrameEvents(result);
4401 }
4402}
4403
Yiwei Zhang5434a782018-12-05 18:06:32 -08004404void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004405 result.append("Buffering stats:\n");
4406 result.append(" [Layer name] <Active time> <Two buffer> "
4407 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004408 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004409 typedef std::tuple<std::string, float, float, float> BufferTuple;
4410 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004411 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004412 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004413 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004414 if (stats.numSegments == 0) {
4415 continue;
4416 }
4417 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4418 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4419 stats.totalTime;
4420 float doubleBufferRatio = static_cast<float>(
4421 stats.doubleBufferedTime) / stats.totalTime;
4422 float tripleBufferRatio = static_cast<float>(
4423 stats.tripleBufferedTime) / stats.totalTime;
4424 sorted.insert({activeTime, {name, twoBufferRatio,
4425 doubleBufferRatio, tripleBufferRatio}});
4426 }
4427 for (const auto& sortedPair : sorted) {
4428 float activeTime = sortedPair.first;
4429 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004430 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4431 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004432 }
4433 result.append("\n");
4434}
4435
Yiwei Zhang5434a782018-12-05 18:06:32 -08004436void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004437 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004438 const auto displayId = display->getId();
4439 if (!displayId) {
4440 continue;
4441 }
4442 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004443 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004444 continue;
4445 }
4446
Yiwei Zhang5434a782018-12-05 18:06:32 -08004447 StringAppendF(&result,
4448 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4449 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004450 uint8_t port;
4451 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004452 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004453 result.append("no identification data\n");
4454 continue;
4455 }
4456
4457 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004458 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004459 continue;
4460 }
4461
4462 const auto edid = parseEdid(data);
4463 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004464 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004465 continue;
4466 }
4467
Yiwei Zhang5434a782018-12-05 18:06:32 -08004468 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004469 result.append(edid->displayName.data(), edid->displayName.length());
4470 result.append("\"\n");
4471 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004472}
4473
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004474void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4475 std::string& result) const {
4476 hwc2_display_t hwcDisplayId;
4477 uint8_t port;
4478 DisplayIdentificationData data;
4479
4480 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4481 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4482 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4483 }
4484}
4485
Yiwei Zhang5434a782018-12-05 18:06:32 -08004486void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004487 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004488 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4489 StringAppendF(&result, "DisplayColorSetting: %s\n",
4490 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004491
4492 // TODO: print out if wide-color mode is active or not
4493
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004494 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004495 const auto displayId = display->getId();
4496 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004497 continue;
4498 }
4499
Yiwei Zhang5434a782018-12-05 18:06:32 -08004500 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004501 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004502 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004503 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004504 }
4505
Lloyd Pique32cbe282018-10-19 13:09:22 -07004506 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004507 StringAppendF(&result, " Current color mode: %s (%d)\n",
4508 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004509 }
4510 result.append("\n");
4511}
4512
Alec Mouri5793c7d2020-03-10 19:55:50 -07004513LayersProto SurfaceFlinger::dumpDrawingStateProto(
4514 uint32_t traceFlags, const sp<const DisplayDevice>& displayDevice) const {
chaviw1d044282017-09-27 12:19:28 -07004515 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004516 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Alec Mouri5793c7d2020-03-10 19:55:50 -07004517 layer->writeToProto(layersProto, traceFlags, displayDevice);
chaviw08f3cb22020-01-13 13:17:21 -08004518 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004519
chaviw1d044282017-09-27 12:19:28 -07004520 return layersProto;
4521}
4522
Alec Mouri6b9e9912020-01-21 10:50:24 -08004523void SurfaceFlinger::dumpHwc(std::string& result) const {
4524 getHwComposer().dump(result);
4525}
4526
Vishnu Nair0f085c62019-08-30 08:49:12 -07004527void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4528 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4529 // it.
4530 LayerProto* rootProto = layersProto.add_layers();
4531 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4532 rootProto->set_id(offscreenRootLayerId);
4533 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004534 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004535
4536 for (Layer* offscreenLayer : mOffscreenLayers) {
4537 // Add layer as child of the fake root
4538 rootProto->add_children(offscreenLayer->sequence);
4539
4540 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004541 LayerProto* layerProto =
4542 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004543 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004544 }
4545}
4546
Vishnu Nair8406fd72019-07-30 11:29:31 -07004547LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4548 LayersProto layersProto;
Alec Mouri5793c7d2020-03-10 19:55:50 -07004549 postMessageSync(new LambdaMessage([&]() {
4550 const auto& displayDevice = getDefaultDisplayDeviceLocked();
4551 layersProto = dumpDrawingStateProto(traceFlags, displayDevice);
4552 }));
Vishnu Nair8406fd72019-07-30 11:29:31 -07004553 return layersProto;
4554}
4555
Vishnu Nair0f085c62019-08-30 08:49:12 -07004556void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4557 result.append("Offscreen Layers:\n");
4558 postMessageSync(new LambdaMessage([&]() {
4559 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004560 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004561 layer->dumpCallingUidPid(result);
4562 });
4563 }
4564 }));
4565}
4566
Dominik Laskowskic2867142019-01-21 11:33:38 -08004567void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4568 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004569 Colorizer colorizer(colorize);
4570
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004571 // figure out if we're stuck somewhere
4572 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004573 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004574 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4575
4576 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004577 * Dump library configuration.
4578 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004579
4580 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004581 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004582 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004583 appendSfConfigString(result);
4584 appendUiConfigString(result);
4585 appendGuiConfigString(result);
4586 result.append("\n");
4587
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004588 result.append("\nDisplay identification data:\n");
4589 dumpDisplayIdentificationData(result);
4590
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004591 result.append("\nWide-Color information:\n");
4592 dumpWideColorInfo(result);
4593
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004594 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004595 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004596 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004597 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004598 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004599
Andy McFadden41d67d72014-04-25 16:58:34 -07004600 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004601 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004602 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004603 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004604 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004605
Dan Stozab90cf072015-03-05 11:05:59 -08004606 dumpStaticScreenStats(result);
4607 result.append("\n");
4608
Alec Mouri40189b02019-03-05 15:07:54 -08004609 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4610 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4611 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004612
Dan Stozae77c7662016-05-13 11:37:28 -07004613 dumpBufferingStats(result);
4614
Andy McFadden4803b742012-09-24 19:07:20 -07004615 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004616 * Dump the visible layer list
4617 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004618 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004619 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004620 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4621 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004622 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004623
Chia-I Wu2f884132018-09-13 15:17:58 -07004624 {
Lloyd Pique207def92019-02-28 16:09:52 -08004625 StringAppendF(&result, "Composition layers\n");
4626 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004627 auto* compositionState = layer->getCompositionState();
Vishnu Nair49529172020-02-25 10:19:44 -08004628 if (!compositionState || !compositionState->isVisible) return;
Lloyd Piquede196652020-01-22 17:29:58 -08004629
4630 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4631 layer->getDebugName() ? layer->getDebugName()
4632 : "<unknown>");
4633 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004634 });
4635 }
4636
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004637 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004638 * Dump Display state
4639 */
4640
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004641 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004642 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004643 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004644 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004645 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004646 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004647 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004648
4649 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004650 * Dump CompositionEngine state
4651 */
4652
4653 mCompositionEngine->dump(result);
4654
4655 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004656 * Dump SurfaceFlinger global state
4657 */
4658
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004659 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004660 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004661 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004662
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004663 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004664
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004665 DebugEGLImageTracker::getInstance()->dump(result);
4666
Dominik Laskowski075d3172018-05-24 15:50:06 -07004667 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004668 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4669 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004670 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4671 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004672 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004673 StringAppendF(&result,
4674 " transaction-flags : %08x\n"
4675 " gpu_to_cpu_unsupported : %d\n",
4676 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004677
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004678 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004679 displayId && getHwComposer().isConnected(*displayId)) {
4680 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004681 StringAppendF(&result,
4682 " refresh-rate : %f fps\n"
4683 " x-dpi : %f\n"
4684 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004685 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4686 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004687 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004688
Yiwei Zhang5434a782018-12-05 18:06:32 -08004689 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004690
Dan Stozae22aec72016-08-01 13:20:59 -07004691 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004692 * Tracing state
4693 */
4694 mTracing.dump(result);
4695 result.append("\n");
4696
4697 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004698 * HWC layer minidump
4699 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004700 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004701 const auto displayId = display->getId();
4702 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004703 continue;
4704 }
4705
Yiwei Zhang5434a782018-12-05 18:06:32 -08004706 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004707 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004708 const sp<DisplayDevice> displayDevice = display;
4709 mCurrentState.traverseInZOrder(
4710 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004711 result.append("\n");
4712 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004713
4714 /*
4715 * Dump HWComposer state
4716 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004717 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004718 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004719 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004720 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004721 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004722 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004723
4724 /*
4725 * Dump gralloc state
4726 */
4727 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4728 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004729
4730 /*
4731 * Dump VrFlinger state if in use.
4732 */
4733 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4734 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004735 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004736 result.append("\n");
4737 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004738
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004739 result.append(mTimeStats->miniDump());
4740 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004741}
4742
Chia-I Wu28f320b2018-05-03 11:02:56 -07004743void SurfaceFlinger::updateColorMatrixLocked() {
4744 mat4 colorMatrix;
4745 if (mGlobalSaturationFactor != 1.0f) {
4746 // Rec.709 luma coefficients
4747 float3 luminance{0.213f, 0.715f, 0.072f};
4748 luminance *= 1.0f - mGlobalSaturationFactor;
4749 mat4 saturationMatrix = mat4(
4750 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4751 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4752 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4753 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4754 );
4755 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4756 } else {
4757 colorMatrix = mClientColorMatrix * mDaltonizer();
4758 }
4759
4760 if (mCurrentState.colorMatrix != colorMatrix) {
4761 mCurrentState.colorMatrix = colorMatrix;
4762 mCurrentState.colorMatrixChanged = true;
4763 setTransactionFlags(eTransactionNeeded);
4764 }
4765}
4766
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004767status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004768#pragma clang diagnostic push
4769#pragma clang diagnostic error "-Wswitch-enum"
4770 switch (static_cast<ISurfaceComposerTag>(code)) {
4771 // These methods should at minimum make sure that the client requested
4772 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004773 case BOOT_FINISHED:
4774 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004775 case CREATE_DISPLAY:
4776 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004777 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004778 case GET_ANIMATION_FRAME_STATS:
4779 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004780 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004781 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004782 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004783 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4784 case SET_AUTO_LOW_LATENCY_MODE:
4785 case GET_GAME_CONTENT_TYPE_SUPPORT:
4786 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004787 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004788 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004789 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004790 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004791 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004792 case NOTIFY_POWER_HINT:
4793 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004794 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4795 IPCThreadState* ipc = IPCThreadState::self();
4796 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4797 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004798 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004799 }
Robert Carr1db73f62016-12-21 12:58:51 -08004800 return OK;
4801 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004802 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004803 IPCThreadState* ipc = IPCThreadState::self();
4804 const int pid = ipc->getCallingPid();
4805 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004806 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4807 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004808 return PERMISSION_DENIED;
4809 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004810 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004811 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004812 // Used by apps to hook Choreographer to SurfaceFlinger.
4813 case CREATE_DISPLAY_EVENT_CONNECTION:
4814 // The following calls are currently used by clients that do not
4815 // request necessary permissions. However, they do not expose any secret
4816 // information, so it is OK to pass them.
4817 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004818 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004819 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004820 case GET_PHYSICAL_DISPLAY_IDS:
4821 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004822 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004823 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004824 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004825 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004826 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004827 case GET_DISPLAY_STATS:
4828 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4829 // Calling setTransactionState is safe, because you need to have been
4830 // granted a reference to Client* and Handle* to do anything with it.
4831 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004832 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004833 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004834 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004835 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004836 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004837 // setFrameRate() is deliberately available for apps to call without any
4838 // special permissions.
4839 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004840 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4841 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004842 return OK;
4843 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004844 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004845 case CAPTURE_SCREEN:
4846 case ADD_REGION_SAMPLING_LISTENER:
4847 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004848 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004849 IPCThreadState* ipc = IPCThreadState::self();
4850 const int pid = ipc->getCallingPid();
4851 const int uid = ipc->getCallingUid();
4852 if ((uid != AID_GRAPHICS) &&
4853 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4854 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4855 return PERMISSION_DENIED;
4856 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004857 return OK;
4858 }
chaviw93df2ea2019-04-30 16:45:12 -07004859 case CAPTURE_SCREEN_BY_ID: {
4860 IPCThreadState* ipc = IPCThreadState::self();
4861 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004862 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004863 return OK;
4864 }
4865 return PERMISSION_DENIED;
4866 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004867 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004868
4869 // These codes are used for the IBinder protocol to either interrogate the recipient
4870 // side of the transaction for its canonical interface descriptor or to dump its state.
4871 // We let them pass by default.
4872 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4873 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4874 code == IBinder::SYSPROPS_TRANSACTION) {
4875 return OK;
4876 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004877 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004878 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004879 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004880 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4881 return OK;
4882 }
4883 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4884 return PERMISSION_DENIED;
4885#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004886}
4887
Ana Krulec13be8ad2018-08-21 02:43:56 +00004888status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4889 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004890 status_t credentialCheck = CheckTransactCodeCredentials(code);
4891 if (credentialCheck != OK) {
4892 return credentialCheck;
4893 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004894
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004895 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4896 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004897 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004898 IPCThreadState* ipc = IPCThreadState::self();
4899 const int uid = ipc->getCallingUid();
4900 if (CC_UNLIKELY(uid != AID_SYSTEM
4901 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004902 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004903 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004904 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004905 return PERMISSION_DENIED;
4906 }
4907 int n;
4908 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004909 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004910 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004911 return NO_ERROR;
4912 case 1002: // SHOW_UPDATES
4913 n = data.readInt32();
4914 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004915 invalidateHwcGeometry();
4916 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004917 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004918 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004919 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004920 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004921 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004922 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004923 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004924 setTransactionFlags(
4925 eTransactionNeeded|
4926 eDisplayTransactionNeeded|
4927 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004928 return NO_ERROR;
4929 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004930 case 1006:{ // send empty update
4931 signalRefresh();
4932 return NO_ERROR;
4933 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004934 case 1008: // toggle use of hw composer
4935 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004936 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004937 invalidateHwcGeometry();
4938 repaintEverything();
4939 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004940 case 1009: // toggle use of transform hint
4941 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004942 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004943 invalidateHwcGeometry();
4944 repaintEverything();
4945 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004946 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004947 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004948 reply->writeInt32(0);
4949 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004950 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004951 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004952 return NO_ERROR;
4953 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004954 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004955 if (!display) {
4956 return NAME_NOT_FOUND;
4957 }
4958
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004959 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004960 return NO_ERROR;
4961 }
4962 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004963 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004964 // daltonize
4965 n = data.readInt32();
4966 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004967 case 1:
4968 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4969 break;
4970 case 2:
4971 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4972 break;
4973 case 3:
4974 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4975 break;
4976 default:
4977 mDaltonizer.setType(ColorBlindnessType::None);
4978 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004979 }
4980 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004981 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004982 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004983 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004984 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004985
4986 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004987 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004988 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004989 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004990 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004991 // apply a color matrix
4992 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004993 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004994 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004995 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004996 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004997 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004998 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004999 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005000 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005001 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005002 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005003
5004 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5005 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005006 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005007 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5008 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5009 }
5010
Chia-I Wu28f320b2018-05-03 11:02:56 -07005011 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005012 return NO_ERROR;
5013 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005014 case 1016: { // Unused.
5015 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005016 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005017 case 1017: {
5018 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005019 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005020 return NO_ERROR;
5021 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005022 case 1018: { // Modify Choreographer's phase offset
5023 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005024 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005025 return NO_ERROR;
5026 }
5027 case 1019: { // Modify SurfaceFlinger's phase offset
5028 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005029 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005030 return NO_ERROR;
5031 }
Irvel468051e2016-06-13 16:44:44 -07005032 case 1020: { // Layer updates interceptor
5033 n = data.readInt32();
5034 if (n) {
5035 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005036 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005037 }
5038 else{
5039 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005040 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005041 }
5042 return NO_ERROR;
5043 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005044 case 1021: { // Disable HWC virtual displays
5045 n = data.readInt32();
5046 mUseHwcVirtualDisplays = !n;
5047 return NO_ERROR;
5048 }
Romain Guy0147a172017-06-01 13:53:56 -07005049 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005050 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005051 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005052
Chia-I Wu28f320b2018-05-03 11:02:56 -07005053 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005054 return NO_ERROR;
5055 }
Romain Guy54f154a2017-10-24 21:40:32 +01005056 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005057 int32_t colorMode;
5058
Chia-I Wu0d711262018-05-21 15:19:35 -07005059 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005060 if (data.readInt32(&colorMode) == NO_ERROR) {
5061 mForceColorMode = static_cast<ColorMode>(colorMode);
5062 }
Romain Guy54f154a2017-10-24 21:40:32 +01005063 invalidateHwcGeometry();
5064 repaintEverything();
5065 return NO_ERROR;
5066 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005067 // Deprecate, use 1030 to check whether the device is color managed.
5068 case 1024: {
5069 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005070 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005071 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005072 n = data.readInt32();
5073 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005074 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005075 Mutex::Autolock lock(mStateLock);
5076 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005077 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005078 reply->writeInt32(NO_ERROR);
5079 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005080 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005081 bool writeFile = false;
5082 {
5083 Mutex::Autolock lock(mStateLock);
5084 mTracingEnabledChanged = true;
5085 writeFile = mTracing.disable();
5086 }
5087
5088 if (writeFile) {
5089 reply->writeInt32(mTracing.writeToFile());
5090 } else {
5091 reply->writeInt32(NO_ERROR);
5092 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005093 }
5094 return NO_ERROR;
5095 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005096 case 1026: { // Get layer tracing status
5097 reply->writeBool(mTracing.isEnabled());
5098 return NO_ERROR;
5099 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005100 // Is a DisplayColorSetting supported?
5101 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005102 const auto display = getDefaultDisplayDevice();
5103 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005104 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005105 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005106
5107 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5108 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005109 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005110 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005111 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005112 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005113 reply->writeBool(true);
5114 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005115 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005116 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005117 break;
5118 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005119 reply->writeBool(
5120 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005121 break;
5122 }
5123 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005124 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005125 // Is VrFlinger active?
5126 case 1028: {
5127 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005128 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005129 return NO_ERROR;
5130 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005131 // Set buffer size for SF tracing (value in KB)
5132 case 1029: {
5133 n = data.readInt32();
5134 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5135 ALOGW("Invalid buffer size: %d KB", n);
5136 reply->writeInt32(BAD_VALUE);
5137 return BAD_VALUE;
5138 }
5139
5140 ALOGD("Updating trace buffer to %d KB", n);
5141 mTracing.setBufferSize(n * 1024);
5142 reply->writeInt32(NO_ERROR);
5143 return NO_ERROR;
5144 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005145 // Is device color managed?
5146 case 1030: {
5147 reply->writeBool(useColorManagement);
5148 return NO_ERROR;
5149 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005150 // Override default composition data space
5151 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5152 // && adb shell stop zygote && adb shell start zygote
5153 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5154 // adb shell stop zygote && adb shell start zygote
5155 case 1031: {
5156 Mutex::Autolock _l(mStateLock);
5157 n = data.readInt32();
5158 if (n) {
5159 n = data.readInt32();
5160 if (n) {
5161 Dataspace dataspace = static_cast<Dataspace>(n);
5162 if (!validateCompositionDataspace(dataspace)) {
5163 return BAD_VALUE;
5164 }
5165 mDefaultCompositionDataspace = dataspace;
5166 }
5167 n = data.readInt32();
5168 if (n) {
5169 Dataspace dataspace = static_cast<Dataspace>(n);
5170 if (!validateCompositionDataspace(dataspace)) {
5171 return BAD_VALUE;
5172 }
5173 mWideColorGamutCompositionDataspace = dataspace;
5174 }
5175 } else {
5176 // restore composition data space.
5177 mDefaultCompositionDataspace = defaultCompositionDataspace;
5178 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5179 }
5180 return NO_ERROR;
5181 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005182 // Set trace flags
5183 case 1033: {
5184 n = data.readUint32();
5185 ALOGD("Updating trace flags to 0x%x", n);
5186 mTracing.setTraceFlags(n);
5187 reply->writeInt32(NO_ERROR);
5188 return NO_ERROR;
5189 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005190 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005191 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005192 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005193 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005194 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005195 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005196 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005197 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005198 } else {
5199 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005200 }
5201 return NO_ERROR;
5202 }
Ady Abraham34392f72019-04-10 11:29:27 -07005203 case 1035: {
5204 n = data.readInt32();
5205 mDebugDisplayConfigSetByBackdoor = false;
5206 if (n >= 0) {
5207 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005208 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005209 if (result != NO_ERROR) {
5210 return result;
5211 }
5212 mDebugDisplayConfigSetByBackdoor = true;
5213 }
5214 return NO_ERROR;
5215 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005216 }
5217 }
5218 return err;
5219}
5220
Steven Thomas6d8110b2017-08-31 18:24:21 -07005221void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005222 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005223 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005224}
5225
Ana Krulec7d1d6832018-12-27 11:10:09 -08005226void SurfaceFlinger::repaintEverythingForHWC() {
5227 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005228 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005229 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005230}
5231
Ady Abrahama09852a2020-02-20 14:23:42 -08005232void SurfaceFlinger::kernelTimerChanged(bool expired) {
5233 static bool updateOverlay =
5234 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5235 if (!updateOverlay || !mRefreshRateOverlay) return;
5236
5237 // Update the overlay on the main thread to avoid race conditions with
5238 // mRefreshRateConfigs->getCurrentRefreshRate()
5239 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5240 if (mRefreshRateOverlay) {
5241 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5242 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005243 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005244 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5245 if (mDesiredActiveConfigChanged) {
5246 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5247 mDesiredActiveConfig.configId);
5248 }
5249
5250 return mRefreshRateConfigs->getCurrentRefreshRate();
5251 }();
5252 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5253
5254 if (current != min) {
5255 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5256 mEventQueue->invalidate();
5257 }
5258 }
5259 }));
5260}
5261
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005262// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5263class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005264public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005265 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5266 ~WindowDisconnector() {
5267 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005268 }
5269
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005270private:
5271 ANativeWindow* mWindow;
5272 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005273};
5274
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005275status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005276 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005277 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5278 const Rect& sourceCrop, uint32_t reqWidth,
5279 uint32_t reqHeight, bool useIdentityTransform,
5280 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005281 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005282
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005283 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005284
Dominik Laskowski718f9602019-11-09 20:01:35 -08005285 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5286 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5287 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5288 renderAreaRotation = ui::Transform::ROT_0;
5289 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005290
Chia-I Wu20261cb2018-08-23 12:55:44 -07005291 sp<DisplayDevice> display;
5292 {
5293 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005294
Chia-I Wu20261cb2018-08-23 12:55:44 -07005295 display = getDisplayDeviceLocked(displayToken);
5296 if (!display) return BAD_VALUE;
5297
Chia-I Wucb023152018-08-28 12:57:23 -07005298 // set the requested width/height to the logical display viewport size
5299 // by default
5300 if (reqWidth == 0 || reqHeight == 0) {
5301 reqWidth = uint32_t(display->getViewport().width());
5302 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005303 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005304 }
5305
Peiyong Lin0e003c92018-09-17 11:09:51 -07005306 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005307 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005308
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005309 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5310 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005311 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005312 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005313}
5314
chaviw93df2ea2019-04-30 16:45:12 -07005315static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5316 switch (colorMode) {
5317 case ColorMode::DISPLAY_P3:
5318 case ColorMode::BT2100_PQ:
5319 case ColorMode::BT2100_HLG:
5320 case ColorMode::DISPLAY_BT2020:
5321 return Dataspace::DISPLAY_P3;
5322 default:
5323 return Dataspace::V0_SRGB;
5324 }
5325}
5326
5327const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5328 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5329 if (displayToken) {
5330 return getDisplayDeviceLocked(displayToken);
5331 }
5332 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5333 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005334 return getDisplayByLayerStack(displayOrLayerStack);
5335}
5336
5337const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005338 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005339 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005340 return display;
5341 }
5342 }
5343 return nullptr;
5344}
5345
5346status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5347 sp<GraphicBuffer>* outBuffer) {
5348 sp<DisplayDevice> display;
5349 uint32_t width;
5350 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005351 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005352 {
5353 Mutex::Autolock _l(mStateLock);
5354 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5355 if (!display) {
5356 return BAD_VALUE;
5357 }
5358
5359 width = uint32_t(display->getViewport().width());
5360 height = uint32_t(display->getViewport().height());
5361
Dominik Laskowski718f9602019-11-09 20:01:35 -08005362 const auto orientation = display->getOrientation();
5363 captureOrientation = ui::Transform::toRotationFlags(orientation);
5364
5365 switch (captureOrientation) {
5366 case ui::Transform::ROT_90:
5367 captureOrientation = ui::Transform::ROT_270;
5368 break;
5369
5370 case ui::Transform::ROT_270:
5371 captureOrientation = ui::Transform::ROT_90;
5372 break;
5373
5374 case ui::Transform::ROT_INVALID:
5375 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5376 captureOrientation = ui::Transform::ROT_0;
5377 break;
5378
5379 default:
5380 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005381 }
chaviw93df2ea2019-04-30 16:45:12 -07005382 *outDataspace =
5383 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5384 }
5385
5386 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5387 false /* captureSecureLayers */);
5388
5389 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5390 std::placeholders::_1);
5391 bool ignored = false;
5392 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5393 false /* useIdentityTransform */,
5394 ignored /* outCapturedSecureLayers */);
5395}
5396
Robert Carr866455f2019-04-02 16:28:26 -07005397status_t SurfaceFlinger::captureLayers(
5398 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5399 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5400 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5401 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005402 ATRACE_CALL();
5403
5404 class LayerRenderArea : public RenderArea {
5405 public:
Robert Carr578038f2018-03-09 12:25:24 -08005406 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005407 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005408 bool childrenOnly, const Rect& displayViewport)
5409 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005410 mLayer(layer),
5411 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005412 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005413 mFlinger(flinger),
5414 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005415 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005416 Rect getBounds() const override {
5417 const Layer::State& layerState(mLayer->getDrawingState());
5418 return mLayer->getBufferSize(layerState);
5419 }
Marissa Wall61c58622018-07-18 10:12:20 -07005420 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005421 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005422 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005423 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005424 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005425 }
chaviwa76b2712017-09-20 12:02:26 -07005426 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005427 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005428 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005429 Rect getSourceCrop() const override {
5430 if (mCrop.isEmpty()) {
5431 return getBounds();
5432 } else {
5433 return mCrop;
5434 }
5435 }
Robert Carr578038f2018-03-09 12:25:24 -08005436 class ReparentForDrawing {
5437 public:
5438 const sp<Layer>& oldParent;
5439 const sp<Layer>& newParent;
5440
Vishnu Nair4351ad52019-02-11 14:13:02 -08005441 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5442 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005443 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005444 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005445 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5446 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005447 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005448 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005449 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005450 };
5451
5452 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005453 const Rect sourceCrop = getSourceCrop();
5454 // no need to check rotation because there is none
5455 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5456 sourceCrop.height() != getReqHeight();
5457
Robert Carr578038f2018-03-09 12:25:24 -08005458 if (!mChildrenOnly) {
5459 mTransform = mLayer->getTransform().inverse();
5460 drawLayers();
5461 } else {
5462 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005463 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5464 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005465 // In the "childrenOnly" case we reparent the children to a screenshot
5466 // layer which has no properties set and which does not draw.
5467 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005468 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5469 "Screenshot Parent"s, w, h, 0,
5470 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005471
Vishnu Nair4351ad52019-02-11 14:13:02 -08005472 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005473 drawLayers();
5474 }
5475 }
chaviwa76b2712017-09-20 12:02:26 -07005476
chaviwa76b2712017-09-20 12:02:26 -07005477 private:
chaviw7206d492017-11-10 16:16:12 -08005478 const sp<Layer> mLayer;
5479 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005480
Peiyong Linefefaac2018-08-17 12:27:51 -07005481 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005482 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005483
5484 SurfaceFlinger* mFlinger;
5485 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005486 };
5487
Robert Carrc0df3122019-04-11 13:18:21 -07005488 int reqWidth = 0;
5489 int reqHeight = 0;
5490 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005491 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005492 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005493 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005494 {
5495 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005496
Robert Carrc0df3122019-04-11 13:18:21 -07005497 parent = fromHandle(layerHandleBinder);
5498 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5499 ALOGE("captureLayers called with an invalid or removed parent");
5500 return NAME_NOT_FOUND;
5501 }
5502
5503 const int uid = IPCThreadState::self()->getCallingUid();
5504 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5505 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5506 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5507 return PERMISSION_DENIED;
5508 }
5509
Vishnu Nairefc42e22019-12-03 17:36:12 -08005510 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005511 if (sourceCrop.width() <= 0) {
5512 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005513 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005514 }
5515
5516 if (sourceCrop.height() <= 0) {
5517 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005518 crop.bottom = parentSourceBounds.getHeight();
5519 }
5520
5521 if (crop.isEmpty() || frameScale <= 0.0f) {
5522 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5523 // crop was not specified, or an invalid frame scale was provided.
5524 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005525 }
5526 reqWidth = crop.width() * frameScale;
5527 reqHeight = crop.height() * frameScale;
5528
5529 for (const auto& handle : excludeHandles) {
5530 sp<Layer> excludeLayer = fromHandle(handle);
5531 if (excludeLayer != nullptr) {
5532 excludeLayers.emplace(excludeLayer);
5533 } else {
5534 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5535 return NAME_NOT_FOUND;
5536 }
5537 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005538
5539 auto display = getDisplayByLayerStack(parent->getLayerStack());
5540 if (!display) {
5541 return BAD_VALUE;
5542 }
5543
5544 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005545 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005546
Chia-I Wu20261cb2018-08-23 12:55:44 -07005547 // really small crop or frameScale
5548 if (reqWidth <= 0) {
5549 reqWidth = 1;
5550 }
5551 if (reqHeight <= 0) {
5552 reqHeight = 1;
5553 }
5554
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005555 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5556 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005557 auto traverseLayers = [parent, childrenOnly,
5558 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005559 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5560 if (!layer->isVisible()) {
5561 return;
Robert Carr578038f2018-03-09 12:25:24 -08005562 } else if (childrenOnly && layer == parent.get()) {
5563 return;
chaviwa76b2712017-09-20 12:02:26 -07005564 }
Robert Carr866455f2019-04-02 16:28:26 -07005565
5566 sp<Layer> p = layer;
5567 while (p != nullptr) {
5568 if (excludeLayers.count(p) != 0) {
5569 return;
5570 }
5571 p = p->getParent();
5572 }
5573
chaviwa76b2712017-09-20 12:02:26 -07005574 visitor(layer);
5575 });
5576 };
Robert Carr108b2c72019-04-02 16:32:58 -07005577
5578 bool outCapturedSecureLayers = false;
5579 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5580 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005581}
5582
5583status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5584 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005585 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005586 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005587 bool useIdentityTransform,
5588 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005589 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005590
Peiyong Lin0e003c92018-09-17 11:09:51 -07005591 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005592 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5593 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005594 *outBuffer =
5595 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5596 static_cast<android_pixel_format>(reqPixelFormat), 1,
5597 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005598
Robert Carr108b2c72019-04-02 16:32:58 -07005599 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5600 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005601}
5602
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005603status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5604 TraverseLayersFunction traverseLayers,
5605 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005606 bool useIdentityTransform,
5607 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005608 // This mutex protects syncFd and captureResult for communication of the return values from the
5609 // main thread back to this Binder thread
5610 std::mutex captureMutex;
5611 std::condition_variable captureCondition;
5612 std::unique_lock<std::mutex> captureLock(captureMutex);
5613 int syncFd = -1;
5614 std::optional<status_t> captureResult;
5615
Robert Carr03480e22018-01-04 16:02:06 -08005616 const int uid = IPCThreadState::self()->getCallingUid();
5617 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5618
Dominik Laskowski8c001672018-05-30 16:52:06 -07005619 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005620 // If there is a refresh pending, bug out early and tell the binder thread to try again
5621 // after the refresh.
5622 if (mRefreshPending) {
5623 ATRACE_NAME("Skipping screenshot for now");
5624 std::unique_lock<std::mutex> captureLock(captureMutex);
5625 captureResult = std::make_optional<status_t>(EAGAIN);
5626 captureCondition.notify_one();
5627 return;
5628 }
5629
5630 status_t result = NO_ERROR;
5631 int fd = -1;
5632 {
5633 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005634 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005635 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005636 useIdentityTransform, forSystem, &fd,
5637 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005638 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005639 }
5640
5641 {
5642 std::unique_lock<std::mutex> captureLock(captureMutex);
5643 syncFd = fd;
5644 captureResult = std::make_optional<status_t>(result);
5645 captureCondition.notify_one();
5646 }
5647 });
5648
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005649 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005650 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005651 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005652 while (*captureResult == EAGAIN) {
5653 captureResult.reset();
5654 result = postMessageAsync(message);
5655 if (result != NO_ERROR) {
5656 return result;
5657 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005658 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005659 }
5660 result = *captureResult;
5661 }
5662
5663 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005664 sync_wait(syncFd, -1);
5665 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005666 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005667
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005668 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005669}
5670
chaviwa76b2712017-09-20 12:02:26 -07005671void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005672 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005673 const sp<GraphicBuffer>& buffer,
5674 bool useIdentityTransform, int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005675 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005676
chaviwa76b2712017-09-20 12:02:26 -07005677 const auto reqWidth = renderArea.getReqWidth();
5678 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005679 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005680 const auto transform = renderArea.getTransform();
5681 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005682 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005683
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005684 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005685 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005686
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005687 // assume that bounds are never offset, and that they are the same as the
5688 // buffer bounds.
5689 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005690 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005691 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005692
5693 // Now take into account the rotation flag. We append a transform that
5694 // rotates the layer stack about the origin, then translate by buffer
5695 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005696 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005697 int displacementX = 0;
5698 int displacementY = 0;
5699 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5700 switch (rotation) {
5701 case ui::Transform::ROT_90:
5702 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005703 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005704 break;
5705 case ui::Transform::ROT_180:
5706 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005707 displacementY = renderArea.getBounds().getWidth();
5708 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005709 break;
5710 case ui::Transform::ROT_270:
5711 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005712 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005713 break;
5714 default:
5715 break;
5716 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005717
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005718 // We need to transform the clipping window into the right spot.
5719 // First, rotate the clipping rectangle by the rotation hint to get the
5720 // right orientation
5721 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5722 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5723 const vec4 rotClipTL = rotMatrix * clipTL;
5724 const vec4 rotClipBR = rotMatrix * clipBR;
5725 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5726 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5727 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5728 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5729
5730 // Now reposition the clipping rectangle with the displacement vector
5731 // computed above.
5732 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005733 clientCompositionDisplay.clip =
5734 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5735 newClipRight + displacementX, newClipBottom + displacementY);
5736
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005737 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005738 clientCompositionDisplay.globalTransform =
5739 clipTransform * clientCompositionDisplay.globalTransform;
5740
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005741 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5742 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005743
chaviw50da5042018-04-09 13:49:37 -07005744 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005745
Vishnu Nair9b079a22020-01-21 14:36:08 -08005746 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005747 fillLayer.source.buffer.buffer = nullptr;
5748 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5749 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5750 fillLayer.alpha = half(alpha);
5751 clientCompositionLayers.push_back(fillLayer);
5752
5753 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005754 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005755 const bool supportProtectedContent = false;
5756 Region clip(renderArea.getBounds());
5757 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5758 clip,
5759 useIdentityTransform,
5760 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5761 renderArea.isSecure(),
5762 supportProtectedContent,
5763 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005764 displayViewport,
5765 clientCompositionDisplay.outputDataspace,
5766 true, /* realContentIsVisible */
5767 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005768 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005769 std::vector<compositionengine::LayerFE::LayerSettings> results =
5770 layer->prepareClientCompositionList(targetSettings);
5771 clientCompositionLayers.insert(clientCompositionLayers.end(),
5772 std::make_move_iterator(results.begin()),
5773 std::make_move_iterator(results.end()));
5774 results.clear();
5775
chaviwa76b2712017-09-20 12:02:26 -07005776 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005777
Vishnu Nair9b079a22020-01-21 14:36:08 -08005778 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5779 clientCompositionLayers.reserve(clientCompositionLayers.size());
5780 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5781 std::back_inserter(clientCompositionLayerPointers),
5782 [](compositionengine::LayerFE::LayerSettings& settings)
5783 -> renderengine::LayerSettings* { return &settings; });
5784
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005785 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005786 // Use an empty fence for the buffer fence, since we just created the buffer so
5787 // there is no need for synchronization with the GPU.
5788 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005789 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005790 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005791 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005792 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005793
5794 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005795}
5796
chaviwa76b2712017-09-20 12:02:26 -07005797status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5798 TraverseLayersFunction traverseLayers,
Ana Krulecfc874ae2020-02-22 15:39:32 -08005799 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005800 bool useIdentityTransform, bool forSystem,
5801 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005802 ATRACE_CALL();
5803
chaviwa76b2712017-09-20 12:02:26 -07005804 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005805 outCapturedSecureLayers =
5806 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005807 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005808
Robert Carr03480e22018-01-04 16:02:06 -08005809 // We allow the system server to take screenshots of secure layers for
5810 // use in situations like the Screen-rotation animation and place
5811 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005812 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005813 ALOGW("FB is protected: PERMISSION_DENIED");
5814 return PERMISSION_DENIED;
5815 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005816 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005817 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005818}
5819
chaviw95ef3c42019-02-14 10:55:09 -08005820void SurfaceFlinger::setInputWindowsFinished() {
5821 Mutex::Autolock _l(mStateLock);
5822
5823 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005824
chaviw95ef3c42019-02-14 10:55:09 -08005825 mTransactionCV.broadcast();
5826}
chaviw5f21a5e2019-02-14 10:00:34 -08005827
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005828// ---------------------------------------------------------------------------
5829
Edgar Arriaga844fa672020-01-16 14:21:42 -08005830void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5831 layersSortedByZ.traverse(visitor);
5832}
5833
Dan Stoza412903f2017-04-27 13:42:17 -07005834void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5835 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005836}
5837
Dan Stoza412903f2017-04-27 13:42:17 -07005838void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5839 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005840}
5841
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005842void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005843 const LayerVector::Visitor& visitor) {
5844 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005845 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005846 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005847 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005848 continue;
5849 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005850 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005851 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005852 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005853 return;
5854 }
chaviwa76b2712017-09-20 12:02:26 -07005855 if (!layer->isVisible()) {
5856 return;
5857 }
5858 visitor(layer);
5859 });
5860 }
5861}
5862
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005863status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5864 HwcConfigIndexType defaultConfig,
5865 float minRefreshRate,
5866 float maxRefreshRate) {
5867 Mutex::Autolock lock(mStateLock);
5868
Dominik Laskowski22488f62019-03-28 09:53:04 -07005869 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005870 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5871 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5872 // it should go thru setDesiredActiveConfig, similar to primary display.
5873 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5874 const auto displayId = display->getId();
5875 LOG_ALWAYS_FATAL_IF(!displayId);
5876
5877 HWC2::VsyncPeriodChangeConstraints constraints;
5878 constraints.desiredTimeNanos = systemTime();
5879 constraints.seamlessRequired = false;
5880
5881 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005882 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5883 constraints, &timeline) < 0) {
5884 return BAD_VALUE;
5885 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005886 if (timeline.refreshRequired) {
5887 repaintEverythingForHWC();
5888 }
5889
Ady Abrahamdfa37362020-01-21 18:02:39 -08005890 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005891 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005892 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5893 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005894 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005895 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005896 }
5897
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005898 if (mDebugDisplayConfigSetByBackdoor) {
5899 // ignore this request as config is overridden by backdoor
5900 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005901 }
5902
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005903 bool policyChanged;
5904 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5905 &policyChanged) < 0) {
5906 return BAD_VALUE;
5907 }
5908 if (!policyChanged) {
5909 return NO_ERROR;
5910 }
5911
5912 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5913 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005914
5915 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5916 // that listeners that care about a change in allowed configs can get the notification.
5917 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005918 const nsecs_t vsyncPeriod =
5919 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005920 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005921 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005922
Ana Krulec3f6a2062020-01-23 15:48:01 -08005923 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005924 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005925 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5926 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5927 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5928 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5929 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5930
5931 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5932 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5933 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005934 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005935 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005936 }
5937
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005938 return NO_ERROR;
5939}
5940
Ana Krulec0782b882019-10-15 17:34:54 -07005941status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005942 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005943 float maxRefreshRate) {
5944 ATRACE_CALL();
5945
5946 if (!displayToken) {
5947 return BAD_VALUE;
5948 }
5949
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005950 status_t result = NO_ERROR;
5951
Ana Krulec234bb162019-11-10 22:55:55 +01005952 postMessageSync(new LambdaMessage([&]() {
5953 const auto display = getDisplayDeviceLocked(displayToken);
5954 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005955 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005956 ALOGE("Attempt to set desired display configs for invalid display token %p",
5957 displayToken.get());
5958 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005959 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005960 ALOGW("Attempt to set desired display configs for virtual display");
5961 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005962 result =
5963 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5964 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005965 }
5966 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005967
5968 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005969}
5970
5971status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005972 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005973 float* outMinRefreshRate,
5974 float* outMaxRefreshRate) {
5975 ATRACE_CALL();
5976
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005977 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005978 return BAD_VALUE;
5979 }
5980
5981 Mutex::Autolock lock(mStateLock);
5982 const auto display = getDisplayDeviceLocked(displayToken);
5983 if (!display) {
5984 return NAME_NOT_FOUND;
5985 }
5986
5987 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005988 HwcConfigIndexType defaultConfig;
5989 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5990 *outDefaultConfig = defaultConfig.value();
5991 return NO_ERROR;
5992 } else if (display->isVirtual()) {
5993 return BAD_VALUE;
5994 } else {
5995 const auto displayId = display->getId();
5996 if (!displayId) {
5997 return BAD_VALUE;
5998 }
5999 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6000 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6001 *outMinRefreshRate = 1e9f / vsyncPeriod;
6002 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6003 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006004 }
Ana Krulec0782b882019-10-15 17:34:54 -07006005}
6006
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006007void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006008 mFlinger->setInputWindowsFinished();
6009}
6010
Robert Carrc0df3122019-04-11 13:18:21 -07006011sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006012 BBinder* b = nullptr;
6013 if (handle) {
6014 b = handle->localBinder();
6015 }
Robert Carrc0df3122019-04-11 13:18:21 -07006016 if (b == nullptr) {
6017 return nullptr;
6018 }
6019 auto it = mLayersByLocalBinderToken.find(b);
6020 if (it != mLayersByLocalBinderToken.end()) {
6021 return it->second.promote();
6022 }
6023 return nullptr;
6024}
6025
Dominik Laskowski75848362019-11-11 17:57:20 -08006026void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006027 mNumLayers++;
6028 mScheduler->registerLayer(layer);
6029}
6030
6031void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6032 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006033 removeFromOffscreenLayers(layer);
6034}
6035
6036// WARNING: ONLY CALL THIS FROM LAYER DTOR
6037// Here we add children in the current state to offscreen layers and remove the
6038// layer itself from the offscreen layer list. Since
6039// this is the dtor, it is safe to access the current state. This keeps us
6040// from dangling children layers such that they are not reachable from the
6041// Drawing state nor the offscreen layer list
6042// See b/141111965
6043void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6044 for (auto& child : layer->getCurrentChildren()) {
6045 mOffscreenLayers.emplace(child.get());
6046 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006047 mOffscreenLayers.erase(layer);
6048}
6049
Alec Mouri4545a8a2019-08-08 20:05:32 -07006050void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6051 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6052}
6053
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006054status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6055 float lightPosY, float lightPosZ,
6056 float lightRadius) {
6057 Mutex::Autolock _l(mStateLock);
6058 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6059 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6060 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6061 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6062 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6063
6064 // these values are overridden when calculating the shadow settings for a layer.
6065 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6066 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006067 return NO_ERROR;
6068}
6069
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006070const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6071 const {
6072 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6073 // on the work to remove the table in that bug rather than adding more to
6074 // it.
6075 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6076 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6077 // supported, and exposed via the
6078 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6079 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6080 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6081 };
6082 return genericLayerMetadataKeyMap;
6083}
6084
Steven Thomas62a4cf82020-01-31 12:04:03 -08006085status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6086 int8_t compatibility) {
6087 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6088 return BAD_VALUE;
6089 }
6090
6091 Mutex::Autolock lock(mStateLock);
6092 if (authenticateSurfaceTextureLocked(surface)) {
6093 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6094 if (layer->setFrameRate(
6095 Layer::FrameRate(frameRate,
6096 Layer::FrameRate::convertCompatibility(compatibility)))) {
6097 setTransactionFlags(eTraversalNeeded);
6098 }
6099 } else {
6100 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6101 return BAD_VALUE;
6102 }
6103 return NO_ERROR;
6104}
6105
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006106} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006107
Mathias Agopian3f844832013-08-07 21:24:32 -07006108#if defined(__gl_h_)
6109#error "don't include gl/gl.h in this file"
6110#endif
6111
6112#if defined(__gl2_h_)
6113#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006114#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006115
6116// TODO(b/129481165): remove the #pragma below and fix conversion issues
6117#pragma clang diagnostic pop // ignored "-Wconversion"