blob: 5a7372787d463b61cb92e5773ba978d307c1f6af [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri989ddbe2020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri989ddbe2020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri989ddbe2020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800104#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
111#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700114#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/EventControlThread.h"
116#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700117#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700118#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700119#include "Scheduler/Scheduler.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800120#include "StartPropertySetThread.h"
121#include "SurfaceFlingerProperties.h"
122#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800123#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700124#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800125#include "android-base/stringprintf.h"
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Steven Thomasb02664d2017-07-26 18:48:28 -0700143namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700144
145#pragma clang diagnostic push
146#pragma clang diagnostic error "-Wswitch-enum"
147
148bool isWideColorMode(const ColorMode colorMode) {
149 switch (colorMode) {
150 case ColorMode::DISPLAY_P3:
151 case ColorMode::ADOBE_RGB:
152 case ColorMode::DCI_P3:
153 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700154 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700155 case ColorMode::BT2100_PQ:
156 case ColorMode::BT2100_HLG:
157 return true;
158 case ColorMode::NATIVE:
159 case ColorMode::STANDARD_BT601_625:
160 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
161 case ColorMode::STANDARD_BT601_525:
162 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
163 case ColorMode::STANDARD_BT709:
164 case ColorMode::SRGB:
165 return false;
166 }
167 return false;
168}
169
170#pragma clang diagnostic pop
171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172class ConditionalLock {
173public:
174 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
175 if (lock) {
176 mMutex.lock();
177 }
178 }
179 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
180private:
181 Mutex& mMutex;
182 bool mLocked;
183};
Peiyong Linfca547f2018-07-09 13:03:33 -0700184
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800185// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
186constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
187
188float getDensityFromProperty(const char* property, bool required) {
189 char value[PROPERTY_VALUE_MAX];
190 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
191 if (!density && required) {
192 ALOGE("%s must be defined as a build property", property);
193 return FALLBACK_DENSITY;
194 }
195 return density / 160.f;
196}
197
Peiyong Lin9d846a52018-11-05 13:18:20 -0800198// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
199bool validateCompositionDataspace(Dataspace dataspace) {
200 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
201}
202
Steven Thomasb02664d2017-07-26 18:48:28 -0700203} // namespace anonymous
204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205// ---------------------------------------------------------------------------
206
Mathias Agopian99b49842011-06-27 16:05:52 -0700207const String16 sHardwareTest("android.permission.HARDWARE_TEST");
208const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
209const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
210const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800211const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700212
213// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700214int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700215bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800217bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800218bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800219int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100220uint32_t SurfaceFlinger::maxGraphicsWidth;
221uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600222bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800223ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700224bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700225bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700226Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
227ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
228Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
229ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800230bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700231
Kalle Raitaa099a242017-01-11 11:17:29 -0800232std::string getHwcServiceName() {
233 char value[PROPERTY_VALUE_MAX] = {};
234 property_get("debug.sf.hwc_service_name", value, "default");
235 ALOGI("Using HWComposer service: '%s'", value);
236 return std::string(value);
237}
238
239bool useTrebleTestingOverride() {
240 char value[PROPERTY_VALUE_MAX] = {};
241 property_get("debug.sf.treble_testing_override", value, "false");
242 ALOGI("Treble testing override: '%s'", value);
243 return std::string(value) == "true";
244}
245
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800246std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
247 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800248 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700249 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800250 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700251 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800252 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700253 return std::string("Enhanced");
254 default:
255 return std::string("Unknown ") +
256 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800258}
259
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700260SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800261
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700262SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
263 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700264 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700265 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700266 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700267 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700268 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800269 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
270 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800271
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700272SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800273 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800274
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700278
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900279 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700280
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900281 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800282
Steven Thomas050b2c82017-03-06 11:45:16 -0800283 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800287
Brian Lindahla13f2d52020-03-05 11:54:17 +0100288 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
289 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 mDefaultCompositionDataspace =
296 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700297 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
298 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 defaultCompositionDataspace = mDefaultCompositionDataspace;
300 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
301 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
302 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
303 wideColorGamutCompositionPixelFormat =
304 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700305
Yichi Chenda901bf2019-06-28 14:58:27 +0800306 mColorSpaceAgnosticDataspace =
307 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
308
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800310
Dominik Laskowski718f9602019-11-09 20:01:35 -0800311 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
312 switch (primary_display_orientation(Values::ORIENTATION_0)) {
313 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800314 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800315 case Values::ORIENTATION_90:
316 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800317 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800318 case Values::ORIENTATION_180:
319 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800320 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800321 case Values::ORIENTATION_270:
322 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800323 break;
324 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800325 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800326
Sundong Ahn85131bd2019-02-18 15:51:53 +0900327 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800328
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800329 // debugging stuff...
330 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700331
Mathias Agopianb4b17302013-03-20 18:36:41 -0700332 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700333 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700334
Alec Mouri989ddbe2020-02-06 09:26:19 -0800335 property_get("ro.build.type", value, "user");
336 mIsUserBuild = strcmp(value, "user") == 0;
337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 property_get("debug.sf.showupdates", value, "0");
339 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700340
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700341 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000342
343 // DDMS debugging deprecated (b/120782499)
344 property_get("debug.sf.ddms", value, "0");
345 int debugDdms = atoi(value);
346 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700347
348 property_get("debug.sf.disable_backpressure", value, "0");
349 mPropagateBackpressure = !atoi(value);
350 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700351
Ady Abrahamadb9a992019-09-19 21:21:55 +0000352 property_get("debug.sf.enable_gl_backpressure", value, "0");
353 mPropagateBackpressureClientComposition = atoi(value);
354 ALOGI_IF(mPropagateBackpressureClientComposition,
355 "Enabling backpressure propagation for Client Composition");
356
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800357 property_get("debug.sf.enable_hwc_vds", value, "0");
358 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800359 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800360
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800361 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800362 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800363 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700364
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800365 property_get("ro.surface_flinger.supports_background_blur", value, "0");
366 bool supportsBlurs = atoi(value);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800367 property_get("debug.sf.disable_blurs", value, "0");
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800368 bool disableBlurs = atoi(value);
369 mEnableBlurs = supportsBlurs && !disableBlurs;
370 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
371 disableBlurs);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800372 property_get("ro.sf.blurs_are_expensive", value, "0");
373 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800374
Ady Abraham0a525092020-03-03 12:51:24 -0800375 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700376 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
377 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
378
Dan Stozaec460082018-12-17 15:35:09 -0800379 property_get("debug.sf.luma_sampling", value, "1");
380 mLumaSampling = atoi(value);
381
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800382 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800383 mDisableClientCompositionCache = atoi(value);
384
Romain Guy11d63f42017-07-20 12:47:14 -0700385 // We should be reading 'persist.sys.sf.color_saturation' here
386 // but since /data may be encrypted, we need to wait until after vold
387 // comes online to attempt to read the property. The property is
388 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800389
390 if (useTrebleTestingOverride()) {
391 // Without the override SurfaceFlinger cannot connect to HIDL
392 // services that are not listed in the manifests. Considered
393 // deriving the setting from the set service name, but it
394 // would be brittle if the name that's not 'default' is used
395 // for production purposes later on.
396 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
397 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800398
399 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800400}
401
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800402void SurfaceFlinger::onFirstRef()
403{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800404 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800405}
406
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700407SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800408
Dan Stozac7014012014-02-14 15:03:43 -0800409void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410{
411 // the window manager died on us. prepare its eulogy.
412
Andy McFadden13a082e2012-08-24 10:16:42 -0700413 // restore initial conditions (default device unblank, etc)
414 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800415
416 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700417 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800418}
419
Robert Carr1db73f62016-12-21 12:58:51 -0800420static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700421 status_t err = client->initCheck();
422 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800423 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800424 }
Robert Carr1db73f62016-12-21 12:58:51 -0800425 return nullptr;
426}
427
428sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
429 return initClient(new Client(this));
430}
431
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700432sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
433 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700434{
435 class DisplayToken : public BBinder {
436 sp<SurfaceFlinger> flinger;
437 virtual ~DisplayToken() {
438 // no more references, this display must be terminated
439 Mutex::Autolock _l(flinger->mStateLock);
440 flinger->mCurrentState.displays.removeItem(this);
441 flinger->setTransactionFlags(eDisplayTransactionNeeded);
442 }
443 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700444 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700445 : flinger(flinger) {
446 }
447 };
448
449 sp<BBinder> token = new DisplayToken(this);
450
451 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700452 // Display ID is assigned when virtual display is allocated by HWC.
453 DisplayDeviceState state;
454 state.isSecure = secure;
455 state.displayName = displayName;
456 mCurrentState.displays.add(token, state);
457 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700458 return token;
459}
460
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700461void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700462 Mutex::Autolock _l(mStateLock);
463
Dominik Laskowski075d3172018-05-24 15:50:06 -0700464 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
465 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700466 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700467 return;
468 }
469
Dominik Laskowski075d3172018-05-24 15:50:06 -0700470 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
471 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700472 ALOGE("destroyDisplay called for non-virtual display");
473 return;
474 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475 mInterceptor->saveDisplayDeletion(state.sequenceId);
476 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700477 setTransactionFlags(eDisplayTransactionNeeded);
478}
479
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800480std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
481 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700482
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800483 const auto internalDisplayId = getInternalDisplayIdLocked();
484 if (!internalDisplayId) {
485 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700486 }
487
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800488 std::vector<PhysicalDisplayId> displayIds;
489 displayIds.reserve(mPhysicalDisplayTokens.size());
490 displayIds.push_back(internalDisplayId->value);
491
492 for (const auto& [id, token] : mPhysicalDisplayTokens) {
493 if (id != *internalDisplayId) {
494 displayIds.push_back(id.value);
495 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700496 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700497
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800498 return displayIds;
499}
500
501sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
502 Mutex::Autolock lock(mStateLock);
503 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700504}
505
Ady Abraham37965d42018-11-01 13:43:32 -0700506status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
507 if (!outGetColorManagement) {
508 return BAD_VALUE;
509 }
510 *outGetColorManagement = useColorManagement;
511 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700512}
513
Lloyd Pique441d5042018-10-18 16:49:51 -0700514HWComposer& SurfaceFlinger::getHwComposer() const {
515 return mCompositionEngine->getHwComposer();
516}
517
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700518renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
519 return mCompositionEngine->getRenderEngine();
520}
521
Lloyd Pique70d91362018-10-18 16:02:55 -0700522compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
523 return *mCompositionEngine.get();
524}
525
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800526void SurfaceFlinger::bootFinished()
527{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700528 if (mStartPropertySetThread->join() != NO_ERROR) {
529 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800530 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800531 const nsecs_t now = systemTime();
532 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000533 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700534
Mikael Pessa90092f42019-08-26 17:22:04 -0700535 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000536 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700537
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700538 // wait patiently for the window manager death
539 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700540 mWindowManager = defaultServiceManager()->getService(name);
541 if (mWindowManager != 0) {
542 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700543 }
Robert Carr720e5062018-07-30 17:45:14 -0700544 sp<IBinder> input(defaultServiceManager()->getService(
545 String16("inputflinger")));
546 if (input == nullptr) {
547 ALOGE("Failed to link to input service");
548 } else {
549 mInputFlinger = interface_cast<IInputFlinger>(input);
550 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700551
Steven Thomas050b2c82017-03-06 11:45:16 -0800552 if (mVrFlinger) {
553 mVrFlinger->OnBootFinished();
554 }
555
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700556 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700557 // formerly we would just kill the process, but we now ask it to exit so it
558 // can choose where to stop the animation.
559 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700560
561 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
562 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
563 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700564
Ana Krulecbd6654b2019-02-15 15:18:15 -0800565 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800566 readPersistentProperties();
567 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800568
Ady Abraham8a82ba62020-01-17 12:43:17 -0800569 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
570 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
571 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
572 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800573 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800574}
575
Dan Stoza436ccf32018-06-21 12:10:12 -0700576uint32_t SurfaceFlinger::getNewTexture() {
577 {
578 std::lock_guard lock(mTexturePoolMutex);
579 if (!mTexturePool.empty()) {
580 uint32_t name = mTexturePool.back();
581 mTexturePool.pop_back();
582 ATRACE_INT("TexturePoolSize", mTexturePool.size());
583 return name;
584 }
585
586 // The pool was too small, so increase it for the future
587 ++mTexturePoolSize;
588 }
589
590 // The pool was empty, so we need to get a new texture name directly using a
591 // blocking call to the main thread
592 uint32_t name = 0;
593 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
594 return name;
595}
596
Mathias Agopian3f844832013-08-07 21:24:32 -0700597void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700598 std::lock_guard lock(mTexturePoolMutex);
599 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
600 // to actually delete this or not based on mTexturePoolSize
601 mTexturePool.push_back(texture);
602 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700603}
604
Wei Wangf9b05ee2017-07-19 20:59:39 -0700605// Do not call property_set on main thread which will be blocked by init
606// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700607void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700608 ALOGI( "SurfaceFlinger's main thread ready to run. "
609 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700610 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800611
Steven Thomasb02664d2017-07-26 18:48:28 -0700612 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700613 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800614 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700615 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
616 renderengine::RenderEngineCreationArgs::Builder()
617 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
618 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
619 .setUseColorManagerment(useColorManagement)
620 .setEnableProtectedContext(enable_protected_contents(false))
621 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800622 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700623 .setContextPriority(useContextPriority
624 ? renderengine::RenderEngine::ContextPriority::HIGH
625 : renderengine::RenderEngine::ContextPriority::MEDIUM)
626 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800627 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700628
629 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
630 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700631 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800632 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800633 // Process any initial hotplug and resulting display changes.
634 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700635 const auto display = getDefaultDisplayDeviceLocked();
636 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700637 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700638 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800639
Steven Thomas050b2c82017-03-06 11:45:16 -0800640 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700641 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700642 // This callback is called from the vr flinger dispatch thread. We
643 // need to call signalTransaction(), which requires holding
644 // mStateLock when we're not on the main thread. Acquiring
645 // mStateLock from the vr flinger dispatch thread might trigger a
646 // deadlock in surface flinger (see b/66916578), so post a message
647 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700648 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700649 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
650 mVrFlingerRequestsDisplay = requestDisplay;
651 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700652 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800653 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700654 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
655 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700656 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700657 .value_or(0),
658 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800659 if (!mVrFlinger) {
660 ALOGE("Failed to start vrflinger");
661 }
662 }
663
Mathias Agopian92a979a2012-08-02 18:32:23 -0700664 // initialize our drawing state
665 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700666
Andy McFadden13a082e2012-08-24 10:16:42 -0700667 // set initial conditions (e.g. unblank default device)
668 initializeDisplays();
669
Steven Thomas137d4bc2019-07-25 16:55:14 -0700670 char primeShaderCache[PROPERTY_VALUE_MAX];
671 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
672 if (atoi(primeShaderCache)) {
673 getRenderEngine().primeCache();
674 }
Dan Stoza4e637772016-07-28 13:31:51 -0700675
Wei Wangf9b05ee2017-07-19 20:59:39 -0700676 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700677
678 const bool presentFenceReliable =
679 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
680 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700681
682 if (mStartPropertySetThread->Start() != NO_ERROR) {
683 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800684 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800685
Dan Stoza9e56aa02015-11-02 13:00:03 -0800686 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700687}
688
Romain Guy11d63f42017-07-20 12:47:14 -0700689void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700690 Mutex::Autolock _l(mStateLock);
691
Romain Guy11d63f42017-07-20 12:47:14 -0700692 char value[PROPERTY_VALUE_MAX];
693
694 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800695 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700696 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800697 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100698
699 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700700 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800701
702 property_get("persist.sys.sf.color_mode", value, "0");
703 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700704}
705
Mathias Agopiana67e4182012-06-19 17:26:12 -0700706void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800707 // Start boot animation service by setting a property mailbox
708 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700709 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800710 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700711 if (mStartPropertySetThread->join() != NO_ERROR) {
712 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800713 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700714}
715
Mathias Agopian875d8e12013-06-07 15:35:48 -0700716size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700717 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700718}
719
Mathias Agopian875d8e12013-06-07 15:35:48 -0700720size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700721 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700722}
723
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800724// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800725
Jamie Gennis582270d2011-08-17 18:19:00 -0700726bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800727 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800728 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800729 return authenticateSurfaceTextureLocked(bufferProducer);
730}
731
732bool SurfaceFlinger::authenticateSurfaceTextureLocked(
733 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800734 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800735 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800736}
737
Brian Anderson6b376712017-04-04 10:51:39 -0700738status_t SurfaceFlinger::getSupportedFrameTimestamps(
739 std::vector<FrameEvent>* outSupported) const {
740 *outSupported = {
741 FrameEvent::REQUESTED_PRESENT,
742 FrameEvent::ACQUIRE,
743 FrameEvent::LATCH,
744 FrameEvent::FIRST_REFRESH_START,
745 FrameEvent::LAST_REFRESH_START,
746 FrameEvent::GPU_COMPOSITION_DONE,
747 FrameEvent::DEQUEUE_READY,
748 FrameEvent::RELEASE,
749 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700750 ConditionalLock _l(mStateLock,
751 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700752 if (!getHwComposer().hasCapability(
753 HWC2::Capability::PresentFenceIsNotReliable)) {
754 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
755 }
756 return NO_ERROR;
757}
758
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800759status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
760 if (!displayToken || !state) {
761 return BAD_VALUE;
762 }
763
764 Mutex::Autolock lock(mStateLock);
765
766 const auto display = getDisplayDeviceLocked(displayToken);
767 if (!display) {
768 return NAME_NOT_FOUND;
769 }
770
771 state->layerStack = display->getLayerStack();
772 state->orientation = display->getOrientation();
773
774 const Rect viewport = display->getViewport();
775 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
776
777 return NO_ERROR;
778}
779
780status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
781 if (!displayToken || !info) {
782 return BAD_VALUE;
783 }
784
785 Mutex::Autolock lock(mStateLock);
786
787 const auto display = getDisplayDeviceLocked(displayToken);
788 if (!display) {
789 return NAME_NOT_FOUND;
790 }
791
Dominik Laskowski55c85402020-01-21 16:25:47 -0800792 if (const auto connectionType = display->getConnectionType())
793 info->connectionType = *connectionType;
794 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800795 return INVALID_OPERATION;
796 }
797
798 if (mEmulatedDisplayDensity) {
799 info->density = mEmulatedDisplayDensity;
800 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800801 info->density = info->connectionType == DisplayConnectionType::Internal
802 ? mInternalDisplayDensity
803 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800804 }
805
806 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200807 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800808
809 return NO_ERROR;
810}
811
Dominik Laskowski22488f62019-03-28 09:53:04 -0700812status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800813 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700814 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700815 return BAD_VALUE;
816 }
817
Dominik Laskowski22488f62019-03-28 09:53:04 -0700818 Mutex::Autolock lock(mStateLock);
819
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800820 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700821 if (!displayId) {
822 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700823 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700824
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800825 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700826
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700828
Dominik Laskowski075d3172018-05-24 15:50:06 -0700829 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800830 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700831
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800832 auto width = hwConfig->getWidth();
833 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700834
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800835 auto xDpi = hwConfig->getDpiX();
836 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700837
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800838 if (isInternal &&
839 (internalDisplayOrientation == ui::ROTATION_90 ||
840 internalDisplayOrientation == ui::ROTATION_270)) {
841 std::swap(width, height);
842 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 }
844
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800845 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800846
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800847 if (mEmulatedDisplayDensity) {
848 config.xDpi = mEmulatedDisplayDensity;
849 config.yDpi = mEmulatedDisplayDensity;
850 } else {
851 config.xDpi = xDpi;
852 config.yDpi = yDpi;
853 }
854
855 const nsecs_t period = hwConfig->getVsyncPeriod();
856 config.refreshRate = 1e9f / period;
857
858 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
859 config.appVsyncOffset = offsets.late.app;
860 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800861 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800862
Andy McFadden91b2ca82014-06-13 14:04:23 -0700863 // This is how far in advance a buffer must be queued for
864 // presentation at a given time. If you want a buffer to appear
865 // on the screen at time N, you must submit the buffer before
866 // (N - presentationDeadline).
867 //
868 // Normally it's one full refresh period (to give SF a chance to
869 // latch the buffer), but this can be reduced by configuring a
870 // DispSync offset. Any additional delays introduced by the hardware
871 // composer or panel must be accounted for here.
872 //
873 // We add an additional 1ms to allow for processing time and
874 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800875 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700876
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800877 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700878 }
879
Dan Stoza7f7da322014-05-02 15:26:25 -0700880 return NO_ERROR;
881}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700882
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700883status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
884 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700885 return BAD_VALUE;
886 }
887
Ana Krulecc2870422019-01-29 19:00:58 -0800888 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700889 return NO_ERROR;
890}
891
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700892int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
893 const auto display = getDisplayDevice(displayToken);
894 if (!display) {
895 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800896 return BAD_VALUE;
897 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700898
Steven Thomasc9098452019-09-30 17:15:05 -0700899 if (display->isPrimary()) {
900 std::lock_guard<std::mutex> lock(mActiveConfigLock);
901 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800902 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700903 }
Steven Thomasc9098452019-09-30 17:15:05 -0700904 }
Ady Abraham2139f732019-11-13 18:56:40 -0800905
906 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700907}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700908
Ady Abraham03b02dd2019-03-21 15:40:11 -0700909void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800910 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800911 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
912 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800913
Ady Abrahamb838aed2019-02-12 15:30:16 -0800914 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800915 if (mDesiredActiveConfigChanged) {
916 // If a config change is pending, just cache the latest request in
917 // mDesiredActiveConfig
918 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
919 mDesiredActiveConfig = info;
920 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
921 } else {
922 // Check is we are already at the desired config
923 const auto display = getDefaultDisplayDeviceLocked();
924 if (!display || display->getActiveConfig() == refreshRate.configId) {
925 return;
926 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800927
Ady Abraham59db0a32020-03-02 18:04:20 -0800928 // Initiate a config change.
929 mDesiredActiveConfigChanged = true;
930 mDesiredActiveConfig = info;
931
Ady Abrahamb838aed2019-02-12 15:30:16 -0800932 // This will trigger HWC refresh without resetting the idle timer.
933 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700934 // Start receiving vsync samples now, so that we can detect a period
935 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800936 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700937 // As we called to set period, we will call to onRefreshRateChangeCompleted once
938 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700939 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800940
Ady Abraham9e16a482019-12-03 17:19:41 -0800941 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
942 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800943 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700944
945 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800946 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700947 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800948}
949
950status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
951 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800952
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100953 if (!displayToken) {
954 return BAD_VALUE;
955 }
Ady Abraham838de062019-02-04 10:24:03 -0800956
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100957 status_t result = NO_ERROR;
958
959 postMessageSync(new LambdaMessage([&]() {
960 const auto display = getDisplayDeviceLocked(displayToken);
961 if (!display) {
962 ALOGE("Attempt to set allowed display configs for invalid display token %p",
963 displayToken.get());
964 result = BAD_VALUE;
965 } else if (display->isVirtual()) {
966 ALOGW("Attempt to set allowed display configs for virtual display");
967 result = BAD_VALUE;
968 } else {
969 HwcConfigIndexType config(mode);
970 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
971 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
972 refreshRate.fps);
973 }
974 }));
975
976 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977}
978
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979void SurfaceFlinger::setActiveConfigInternal() {
980 ATRACE_CALL();
981
Dominik Laskowski22488f62019-03-28 09:53:04 -0700982 const auto display = getDefaultDisplayDeviceLocked();
983 if (!display) {
984 return;
985 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800986
Dominik Laskowski22488f62019-03-28 09:53:04 -0700987 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800988 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700989 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800990 display->setActiveConfig(mUpcomingActiveConfig.configId);
991
Ady Abraham2139f732019-11-13 18:56:40 -0800992 auto refreshRate =
993 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800994 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
995 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800996 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700997
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800998 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700999 const nsecs_t vsyncPeriod =
1000 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
1001 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -08001002 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001003 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001004 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001005}
1006
Ady Abraham53852a52019-05-28 18:07:44 -07001007void SurfaceFlinger::desiredActiveConfigChangeDone() {
1008 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1009 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1010 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001011
Kevin DuBois5988f482020-01-17 09:03:32 -08001012 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001013 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001014 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001015 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1016 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001017}
1018
Dominik Laskowski22488f62019-03-28 09:53:04 -07001019bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001020 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001021 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001022 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001023 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001024 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001025 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001026 return true;
1027 }
1028
1029 // We received the present fence from the HWC, so we assume it successfully updated
1030 // the config, hence we update SF.
1031 mCheckPendingFence = false;
1032 setActiveConfigInternal();
1033 }
1034
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001035 // Store the local variable to release the lock.
1036 ActiveConfigInfo desiredActiveConfig;
1037 {
1038 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001039 if (!mDesiredActiveConfigChanged) {
1040 return false;
1041 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001042 desiredActiveConfig = mDesiredActiveConfig;
1043 }
1044
Ady Abraham2139f732019-11-13 18:56:40 -08001045 auto refreshRate =
1046 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1047 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1048 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001049 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001050 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1051 // display is not valid or we are already in the requested mode
1052 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001053 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001054 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001055 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001056
Ady Abraham838de062019-02-04 10:24:03 -08001057 // Desired active config was set, it is different than the config currently in use, however
1058 // allowed configs might have change by the time we process the refresh.
1059 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001060 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001061 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001062 return false;
1063 }
Alec Mouri7f015182019-07-11 13:56:22 -07001064
Ady Abrahamb838aed2019-02-12 15:30:16 -08001065 mUpcomingActiveConfig = desiredActiveConfig;
1066 const auto displayId = display->getId();
1067 LOG_ALWAYS_FATAL_IF(!displayId);
1068
Ady Abraham2139f732019-11-13 18:56:40 -08001069 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001070
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001071 // TODO(b/142753666) use constrains
1072 HWC2::VsyncPeriodChangeConstraints constraints;
1073 constraints.desiredTimeNanos = systemTime();
1074 constraints.seamlessRequired = false;
1075
1076 HWC2::VsyncPeriodChangeTimeline outTimeline;
1077 auto status =
1078 getHwComposer().setActiveConfigWithConstraints(*displayId,
1079 mUpcomingActiveConfig.configId.value(),
1080 constraints, &outTimeline);
1081 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001082 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1083 // to be sent. We just log the error in this case.
1084 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001085 return false;
1086 }
1087
1088 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1089 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001090 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001091 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001092}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001093
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1095 Vector<ColorMode>* outColorModes) {
1096 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001097 return BAD_VALUE;
1098 }
1099
Peiyong Lina52f0292018-03-14 17:26:31 -07001100 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001101 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001102 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001103 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1104
1105 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1106 if (!displayId) {
1107 return NAME_NOT_FOUND;
1108 }
1109
Dominik Laskowski075d3172018-05-24 15:50:06 -07001110 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001111 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001112 }
Michael Wright28f24d02016-07-12 13:30:53 -07001113 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001114
1115 // If it's built-in display and the configuration claims it's not wide color capable,
1116 // filter out all wide color modes. The typical reason why this happens is that the
1117 // hardware is not good enough to support GPU composition of wide color, and thus the
1118 // OEMs choose to disable this capability.
1119 if (isInternalDisplay && !hasWideColorDisplay) {
1120 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1121 isWideColorMode);
1122 } else {
1123 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1124 }
Michael Wright28f24d02016-07-12 13:30:53 -07001125
1126 return NO_ERROR;
1127}
1128
Daniel Solomon42d04562019-01-20 21:03:19 -08001129status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1130 ui::DisplayPrimaries &primaries) {
1131 if (!displayToken) {
1132 return BAD_VALUE;
1133 }
1134
1135 // Currently we only support this API for a single internal display.
1136 if (getInternalDisplayToken() != displayToken) {
1137 return BAD_VALUE;
1138 }
1139
1140 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1141 return NO_ERROR;
1142}
1143
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001144ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1145 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001146 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001147 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001148 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001149}
1150
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001151status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001152 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001153 Vector<ColorMode> modes;
1154 getDisplayColorModes(displayToken, &modes);
1155 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1156 if (mode < ColorMode::NATIVE || !exists) {
1157 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1158 decodeColorMode(mode).c_str(), mode, displayToken.get());
1159 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001160 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001161 const auto display = getDisplayDevice(displayToken);
1162 if (!display) {
1163 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1164 decodeColorMode(mode).c_str(), mode, displayToken.get());
1165 } else if (display->isVirtual()) {
1166 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1167 decodeColorMode(mode).c_str(), mode);
1168 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001169 display->getCompositionDisplay()->setColorProfile(
1170 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1171 RenderIntent::COLORIMETRIC,
1172 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001173 }
1174 }));
1175
Michael Wright28f24d02016-07-12 13:30:53 -07001176 return NO_ERROR;
1177}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001178
Galia Peycheva5492cb52019-10-30 14:13:16 +01001179status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1180 bool* outSupport) const {
1181 Mutex::Autolock _l(mStateLock);
1182
1183 if (!displayToken) {
1184 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1185 return BAD_VALUE;
1186 }
1187 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1188 if (!displayId) {
1189 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1190 displayToken.get());
1191 return NAME_NOT_FOUND;
1192 }
1193 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1194 HWC2::DisplayCapability::AutoLowLatencyMode);
1195 return NO_ERROR;
1196}
1197
1198void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1199 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1200}
1201
1202void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1203 if (!displayToken) {
1204 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1205 return;
1206 }
1207 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1208 if (!displayId) {
1209 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1210 displayToken.get());
1211 return;
1212 }
1213
1214 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1215}
1216
1217status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1218 bool* outSupport) const {
1219 Mutex::Autolock _l(mStateLock);
1220
1221 if (!displayToken) {
1222 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1223 return BAD_VALUE;
1224 }
1225 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1226 if (!displayId) {
1227 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1228 displayToken.get());
1229 return NAME_NOT_FOUND;
1230 }
1231
1232 std::vector<HWC2::ContentType> outSupportedContentTypes;
1233 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1234 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1235 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1236 return NO_ERROR;
1237}
1238
1239void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1240 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1241}
1242
1243void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1244 if (!displayToken) {
1245 ALOGE("setGameContentType() failed. Missing display token.");
1246 return;
1247 }
1248 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1249 if (!displayId) {
1250 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1251 displayToken.get());
1252 return;
1253 }
1254
1255 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1256 getHwComposer().setContentType(*displayId, type);
1257}
1258
Svetoslavd85084b2014-03-20 10:28:31 -07001259status_t SurfaceFlinger::clearAnimationFrameStats() {
1260 Mutex::Autolock _l(mStateLock);
1261 mAnimFrameTracker.clearStats();
1262 return NO_ERROR;
1263}
1264
1265status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1266 Mutex::Autolock _l(mStateLock);
1267 mAnimFrameTracker.getStats(outStats);
1268 return NO_ERROR;
1269}
1270
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001271status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1272 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001273 Mutex::Autolock _l(mStateLock);
1274
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001275 const auto display = getDisplayDeviceLocked(displayToken);
1276 if (!display) {
1277 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001278 return BAD_VALUE;
1279 }
1280
Peiyong Linfb069302018-04-25 14:34:31 -07001281 // At this point the DisplayDeivce should already be set up,
1282 // meaning the luminance information is already queried from
1283 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001284 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001285 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1286 capabilities.getDesiredMaxLuminance(),
1287 capabilities.getDesiredMaxAverageLuminance(),
1288 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001289
1290 return NO_ERROR;
1291}
1292
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001293std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1294 const DisplayDevice& display) const {
1295 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1296 // avoid repetitive HAL IPC and EDID parsing.
1297 const auto displayId = display.getId();
1298 LOG_FATAL_IF(!displayId);
1299
1300 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1301 LOG_FATAL_IF(!hwcDisplayId);
1302
1303 uint8_t port;
1304 DisplayIdentificationData data;
1305 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1306 ALOGV("%s: No identification data.", __FUNCTION__);
1307 return {};
1308 }
1309
1310 const auto info = parseDisplayIdentificationData(port, data);
1311 if (!info) {
1312 return {};
1313 }
1314 return info->deviceProductInfo;
1315}
1316
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001317status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1318 ui::PixelFormat* outFormat,
1319 ui::Dataspace* outDataspace,
1320 uint8_t* outComponentMask) const {
1321 if (!outFormat || !outDataspace || !outComponentMask) {
1322 return BAD_VALUE;
1323 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001324 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001325 if (!display || !display->getId()) {
1326 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1327 return BAD_VALUE;
1328 }
1329 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1330 outDataspace, outComponentMask);
1331}
1332
Kevin DuBois74e53772018-11-19 10:52:38 -08001333status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1334 bool enable, uint8_t componentMask,
1335 uint64_t maxFrames) const {
1336 const auto display = getDisplayDevice(displayToken);
1337 if (!display || !display->getId()) {
1338 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1339 return BAD_VALUE;
1340 }
1341
1342 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1343 componentMask, maxFrames);
1344}
1345
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001346status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1347 uint64_t maxFrames, uint64_t timestamp,
1348 DisplayedFrameStats* outStats) const {
1349 const auto display = getDisplayDevice(displayToken);
1350 if (!display || !display->getId()) {
1351 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1352 return BAD_VALUE;
1353 }
1354
1355 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1356 outStats);
1357}
1358
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001359status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1360 if (!outSupported) {
1361 return BAD_VALUE;
1362 }
1363 *outSupported = getRenderEngine().supportsProtectedContent();
1364 return NO_ERROR;
1365}
1366
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001367status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1368 bool* outIsWideColorDisplay) const {
1369 if (!displayToken || !outIsWideColorDisplay) {
1370 return BAD_VALUE;
1371 }
1372 Mutex::Autolock _l(mStateLock);
1373 const auto display = getDisplayDeviceLocked(displayToken);
1374 if (!display) {
1375 return BAD_VALUE;
1376 }
Peiyong Linff84a152019-05-17 18:36:19 -07001377
1378 // Use hasWideColorDisplay to override built-in display.
1379 const auto displayId = display->getId();
1380 if (displayId && displayId == getInternalDisplayIdLocked()) {
1381 *outIsWideColorDisplay = hasWideColorDisplay;
1382 return NO_ERROR;
1383 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001384 *outIsWideColorDisplay = display->hasWideColorGamut();
1385 return NO_ERROR;
1386}
1387
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001388status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001389 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001390 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001391
Dominik Laskowski6505f792019-09-18 11:10:05 -07001392 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1393 mEventQueue->setEventConnection(
1394 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001395 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001396 }));
1397
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001398 return NO_ERROR;
1399}
1400
1401status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001402 Mutex::Autolock lock(mStateLock);
1403 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001404}
1405
Lloyd Pique755e3192018-01-31 16:46:15 -08001406status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1407 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001408 // Try to acquire a lock for 1s, fail gracefully
1409 const status_t err = mStateLock.timedLock(s2ns(1));
1410 const bool locked = (err == NO_ERROR);
1411 if (!locked) {
1412 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1413 return TIMED_OUT;
1414 }
1415
1416 outLayers->clear();
1417 mCurrentState.traverseInZOrder([&](Layer* layer) {
1418 outLayers->push_back(layer->getLayerDebugInfo());
1419 });
1420
1421 mStateLock.unlock();
1422 return NO_ERROR;
1423}
1424
Peiyong Linc6780972018-10-28 15:24:08 -07001425status_t SurfaceFlinger::getCompositionPreference(
1426 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1427 Dataspace* outWideColorGamutDataspace,
1428 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001429 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001430 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001431 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001432 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001433 return NO_ERROR;
1434}
1435
Dan Stozaec460082018-12-17 15:35:09 -08001436status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1437 const sp<IBinder>& stopLayerHandle,
1438 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001439 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001440 return BAD_VALUE;
1441 }
1442 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001443 return NO_ERROR;
1444}
1445
Dan Stozaec460082018-12-17 15:35:09 -08001446status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001447 if (!listener) {
1448 return BAD_VALUE;
1449 }
Dan Stozaec460082018-12-17 15:35:09 -08001450 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001451 return NO_ERROR;
1452}
Dan Gittik57e63c52019-01-18 16:37:54 +00001453
1454status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1455 bool* outSupport) const {
1456 if (!displayToken || !outSupport) {
1457 return BAD_VALUE;
1458 }
1459 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1460 if (!displayId) {
1461 return NAME_NOT_FOUND;
1462 }
1463 *outSupport =
1464 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1465 return NO_ERROR;
1466}
1467
1468status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1469 float brightness) const {
1470 if (!displayToken) {
1471 return BAD_VALUE;
1472 }
1473 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1474 if (!displayId) {
1475 return NAME_NOT_FOUND;
1476 }
1477 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1478}
1479
Ady Abraham8532d012019-05-08 14:50:56 -07001480status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1481 PowerHint powerHint = static_cast<PowerHint>(hintId);
1482
1483 if (powerHint == PowerHint::INTERACTION) {
1484 mScheduler->notifyTouchEvent();
1485 }
1486
1487 return NO_ERROR;
1488}
1489
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001490// ----------------------------------------------------------------------------
1491
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001492sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001493 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001494 const auto& handle =
1495 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001496
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001497 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001498}
1499
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001500// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001501
1502void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001503 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001504}
1505
1506void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001507 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001508 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001509 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001510}
1511
1512void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001513 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001514 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001515 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001516}
1517
1518void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001519 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001520 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001521}
1522
1523status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001524 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001525 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001526}
1527
1528status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001529 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001530 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001531 if (res == NO_ERROR) {
1532 msg->wait();
1533 }
1534 return res;
1535}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001536
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001537void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001538 do {
1539 waitForEvent();
1540 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001541}
1542
Dominik Laskowski83b88212018-12-11 13:34:06 -08001543nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001544 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001545 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1546 return 0;
1547 }
1548
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001549 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001550}
1551
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001552void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001553 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001554 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001555 ATRACE_NAME("SF onVsync");
1556
Steven Thomas3cfac282017-02-06 12:29:30 -08001557 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001558 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001559 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001560 return;
1561 }
1562
Dominik Laskowski075d3172018-05-24 15:50:06 -07001563 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001564 return;
1565 }
1566
Dominik Laskowski075d3172018-05-24 15:50:06 -07001567 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001568 // For now, we don't do anything with external display vsyncs.
1569 return;
1570 }
1571
Alec Mourif8e689c2019-05-20 18:32:22 -07001572 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001573 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001574 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001575 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001576 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001577}
1578
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001579void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001580 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1581 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001582}
1583
Ady Abraham2139f732019-11-13 18:56:40 -08001584bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001585 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001586}
1587
Ady Abraham2139f732019-11-13 18:56:40 -08001588void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1589 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001590 const auto display = getDefaultDisplayDeviceLocked();
1591 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001592 return;
1593 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001594 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001595
Ana Krulec7d1d6832018-12-27 11:10:09 -08001596 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001597 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1598 ALOGV("Skipping config %d as it is not part of allowed configs",
1599 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001600 return;
1601 }
1602
Ady Abraham2139f732019-11-13 18:56:40 -08001603 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001604}
1605
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001606void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001607 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001608 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001609 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001610
Lloyd Piqueba04e622017-12-14 17:11:26 -08001611 // Ignore events that do not have the right sequenceId.
1612 if (sequenceId != getBE().mComposerSequenceId) {
1613 return;
1614 }
1615
Steven Thomasb02664d2017-07-26 18:48:28 -07001616 // Only lock if we're not on the main thread. This function is normally
1617 // called on a hwbinder thread, but for the primary display it's called on
1618 // the main thread with the state lock already held, so don't attempt to
1619 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001620 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001621
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001622 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001623
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001624 if (std::this_thread::get_id() == mMainThreadId) {
1625 // Process all pending hot plug events immediately if we are on the main thread.
1626 processDisplayHotplugEventsLocked();
1627 }
1628
Lloyd Piqueba04e622017-12-14 17:11:26 -08001629 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001630}
1631
Ady Abraham7159f572019-10-11 11:10:18 -07001632void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001633 int32_t sequenceId, hwc2_display_t /*display*/,
1634 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1635 Mutex::Autolock lock(mStateLock);
1636 if (sequenceId != getBE().mComposerSequenceId) {
1637 return;
1638 }
1639 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001640}
1641
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001642void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1643 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1644 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1645}
1646
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001647void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001648 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001649 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001650 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001651 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001652 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001653}
1654
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001655void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001656 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001657
1658 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1659 // display power state.
1660 postMessageAsync(new LambdaMessage(
1661 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1662}
1663
1664void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1665 ATRACE_CALL();
1666
Ady Abraham27c70212019-06-11 10:52:26 -07001667 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1668
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001669 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001670 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1671 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001672 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001673 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001674 }
Mathias Agopian86303202012-07-24 22:46:10 -07001675}
1676
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001677// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001678void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001679 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001680 // Clear the drawing state so that the logic inside of
1681 // handleTransactionLocked will fire. It will determine the delta between
1682 // mCurrentState and mDrawingState and re-apply all changes when we make the
1683 // transition.
1684 mDrawingState.displays.clear();
1685 mDisplays.clear();
1686}
1687
Steven Thomas050b2c82017-03-06 11:45:16 -08001688void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001689 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001690 if (!mVrFlinger)
1691 return;
1692 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001693 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001694 return;
1695 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001696
Lloyd Pique441d5042018-10-18 16:49:51 -07001697 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001698 ALOGE("Vr flinger is only supported for remote hardware composer"
1699 " service connections. Ignoring request to transition to vr"
1700 " flinger.");
1701 mVrFlingerRequestsDisplay = false;
1702 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001703 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001704
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001705 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001706
Steven Thomas0123ac62018-07-12 11:32:34 -07001707 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001708 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001709
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001710 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001711
1712 // Clear out all the output layers from the composition engine for all
1713 // displays before destroying the hardware composer interface. This ensures
1714 // any HWC layers are destroyed through that interface before it becomes
1715 // invalid.
1716 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001717 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001718 }
1719
Steven Thomas0123ac62018-07-12 11:32:34 -07001720 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1721 // called below. Clear the reference now so we don't accidentally use it
1722 // later.
1723 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001724
Steven Thomasb02664d2017-07-26 18:48:28 -07001725 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001726 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001727 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001728
Steven Thomasb02664d2017-07-26 18:48:28 -07001729 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001730 // Delete the current instance before creating the new one
1731 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1732 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1733 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001734 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001735
Lloyd Pique441d5042018-10-18 16:49:51 -07001736 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001737 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001738
1739 if (vrFlingerRequestsDisplay) {
1740 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001741 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001742
1743 mVisibleRegionsDirty = true;
1744 invalidateHwcGeometry();
1745
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001746 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001747 display = getDefaultDisplayDeviceLocked();
1748 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001749 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001750
Steven Thomasb02664d2017-07-26 18:48:28 -07001751 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001752 const nsecs_t vsyncPeriod = getVsyncPeriod();
1753 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001754
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001755 // The present fences returned from vr_hwc are not an accurate
1756 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001757 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001758
Steven Thomasb02664d2017-07-26 18:48:28 -07001759 // Use phase of 0 since phase is not known.
1760 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001761 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001762 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001763
Ana Krulecc2870422019-01-29 19:00:58 -08001764 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001765
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001766 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001767 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001768}
1769
Ady Abraham11579302019-09-19 12:35:58 -07001770bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1771 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001772 // We are storing the last 2 present fences. If sf's phase offset is to be
1773 // woken up before the actual vsync but targeting the next vsync, we need to check
1774 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001775 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1776 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001777
Ady Abraham11579302019-09-19 12:35:58 -07001778 if (fence == Fence::NO_FENCE) {
1779 return false;
1780 }
1781
1782 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1783 fence->wait(graceTimeMs);
1784 }
1785
1786 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001787}
1788
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001789void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001790 DisplayStatInfo stats;
1791 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001792 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001793 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001794 mExpectedPresentTime.store(
1795 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001796}
1797
Dominik Laskowski22488f62019-03-28 09:53:04 -07001798void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001799 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001800 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001801 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001802 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001803 // calculate the expected present time once and use the cached
1804 // value throughout this frame to make sure all layers are
1805 // seeing this same value.
1806 populateExpectedPresentTime();
1807
Ady Abraham11579302019-09-19 12:35:58 -07001808 // When Backpressure propagation is enabled we want to give a small grace period
1809 // for the present fence to fire instead of just giving up on this frame to handle cases
1810 // where present fence is just about to get signaled.
1811 const int graceTimeForPresentFenceMs =
1812 (mPropagateBackpressure &&
1813 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1814 ? 1
1815 : 0;
1816 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1817 previousFrameMissed(
1818 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001819 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1820 mHadDeviceComposition && frameMissed};
1821 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1822 mHadClientComposition && frameMissed};
1823
Alec Mouricc0fc602019-02-26 21:45:19 -08001824 if (frameMissed) {
1825 mFrameMissedCount++;
1826 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001827 if (mMissedFrameJankCount == 0) {
1828 mMissedFrameJankStart = systemTime();
1829 }
1830 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001831 }
1832
Alec Mouri40189b02019-03-05 15:07:54 -08001833 if (hwcFrameMissed) {
1834 mHwcFrameMissedCount++;
1835 }
1836
1837 if (gpuFrameMissed) {
1838 mGpuFrameMissedCount++;
1839 }
1840
Ady Abrahamadb9a992019-09-19 21:21:55 +00001841 if (frameMissed && mPropagateBackpressure) {
1842 if ((hwcFrameMissed && !gpuFrameMissed) ||
1843 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001844 signalLayerUpdate();
1845 break;
1846 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001847 }
Dan Stoza50182882016-07-08 12:02:20 -07001848
Alec Mouri989ddbe2020-02-06 09:26:19 -08001849 // Our jank window is always at least 100ms since we missed a
1850 // frame...
1851 static constexpr nsecs_t kMinJankyDuration =
1852 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1853 // ...but if it's larger than 1s then we missed the trace cutoff.
1854 static constexpr nsecs_t kMaxJankyDuration =
1855 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1856 // If we're in a user build then don't push any atoms
1857 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1858 const auto displayDevice = getDefaultDisplayDeviceLocked();
1859 // Only report jank when the display is on, as displays in DOZE
1860 // power mode may operate at a different frame rate than is
1861 // reported in their config, which causes noticeable (but less
1862 // severe) jank.
1863 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1864 const nsecs_t currentTime = systemTime();
1865 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1866 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1867 ATRACE_NAME("Jank detected");
1868 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1869 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1870 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1871 jankyDurationMillis, mMissedFrameJankCount);
1872 }
1873
1874 // We either reported a jank event or we missed the trace
1875 // window, so clear counters here.
1876 if (jankDuration > kMinJankyDuration) {
1877 mMissedFrameJankCount = 0;
1878 mMissedFrameJankStart = 0;
1879 }
1880 }
1881 }
1882
Steven Thomas050b2c82017-03-06 11:45:16 -08001883 // Now that we're going to make it to the handleMessageTransaction()
1884 // call below it's safe to call updateVrFlinger(), which will
1885 // potentially trigger a display handoff.
1886 updateVrFlinger();
1887
Dan Stoza6b9454d2014-11-07 16:00:59 -08001888 bool refreshNeeded = handleMessageTransaction();
1889 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001890
Ana Krulecc84d09b2019-11-02 23:10:29 +01001891 // Layers need to get updated (in the previous line) before we can use them for
1892 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001893 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1894 // and may eventually call to ~Layer() if it holds the last reference
1895 {
1896 Mutex::Autolock _l(mStateLock);
1897 mScheduler->chooseRefreshRateForContent();
1898 }
1899
Ana Krulecc84d09b2019-11-02 23:10:29 +01001900 if (performSetActiveConfig()) {
1901 break;
1902 }
1903
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001904 updateCursorAsync();
1905 updateInputFlinger();
1906
Dan Stoza58784442014-12-02 16:58:17 -08001907 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001908 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001909 // Signal a refresh if a transaction modified the window state,
1910 // a new buffer was latched, or if HWC has requested a full
1911 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001912 if (mFrameStartTime <= 0) {
1913 // We should only use the time of the first invalidate
1914 // message that signals a refresh as the beginning of the
1915 // frame. Otherwise the real frame time will be
1916 // underestimated.
1917 mFrameStartTime = frameStart;
1918 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001919 signalRefresh();
1920 }
1921 break;
1922 }
1923 case MessageQueue::REFRESH: {
1924 handleMessageRefresh();
1925 break;
1926 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001927 }
1928}
1929
Dan Stoza6b9454d2014-11-07 16:00:59 -08001930bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001931 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001932 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001933
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001934 bool flushedATransaction = flushTransactionQueues();
1935
1936 bool runHandleTransaction = transactionFlags &&
1937 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1938
1939 if (runHandleTransaction) {
1940 handleTransaction(eTransactionMask);
1941 } else {
1942 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001943 }
1944
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001945 if (transactionFlushNeeded()) {
1946 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001947 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001948
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001949 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001950}
1951
Mathias Agopian4fec8732012-06-29 14:12:52 -07001952void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001953 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001954
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001955 mRefreshPending = false;
1956
Lloyd Piqueab039b52019-02-13 14:22:42 -08001957 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001958 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001959 for (const auto& [_, display] : mDisplays) {
1960 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1961 }
1962 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001963 if (auto layerFE = layer->getCompositionEngineLayerFE())
1964 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001965 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001966 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1967 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001968 if (auto layerFE = layer->getCompositionEngineLayerFE())
1969 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001970 }
1971
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001972 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001973 refreshArgs.outputColorSetting = useColorManagement
1974 ? mDisplayColorSetting
1975 : compositionengine::OutputColorSetting::kUnmanaged;
1976 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1977 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001978
1979 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1980 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001981 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001982
1983 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1984 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1985 mDrawingState.colorMatrixChanged = false;
1986 }
1987
1988 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1989
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001990 if (mDebugRegion != 0) {
1991 refreshArgs.devOptFlashDirtyRegionsDelay =
1992 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1993 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001994
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001995 mGeometryInvalid = false;
1996
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001997 // Store the present time just before calling to the composition engine so we could notify
1998 // the scheduler.
1999 const auto presentTime = systemTime();
2000
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002001 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002002 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2003 // Reset the frame start time now that we've recorded this frame.
2004 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002005
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002006 mScheduler->onDisplayRefreshed(presentTime);
2007
David Sodmanfa9b2af2017-12-24 13:28:59 -08002008 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002009 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002010
Lloyd Pique66d68602019-02-13 14:23:31 -08002011 mHadClientComposition =
2012 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2013 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002014 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2015 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002016 });
2017 mHadDeviceComposition =
2018 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2019 auto& displayDevice = tokenDisplayPair.second;
2020 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2021 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002022 mReusedClientComposition =
2023 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2024 auto& displayDevice = tokenDisplayPair.second;
2025 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2026 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002027
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002028 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002029
David Sodman7e4ae112018-02-09 15:02:28 -08002030 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002031 if (mVisibleRegionsDirty) {
2032 mVisibleRegionsDirty = false;
2033 if (mTracingEnabled) {
2034 mTracing.notify("visibleRegionsDirty");
2035 }
2036 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002037
2038 if (mCompositionEngine->needsAnotherUpdate()) {
2039 signalLayerUpdate();
2040 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002041}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002042
David Sodmanfa9b2af2017-12-24 13:28:59 -08002043
2044bool SurfaceFlinger::handleMessageInvalidate() {
2045 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002046 bool refreshNeeded = handlePageFlip();
2047
Vishnu Nair4351ad52019-02-11 14:13:02 -08002048 if (mVisibleRegionsDirty) {
2049 computeLayerBounds();
2050 }
2051
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002052 for (auto& layer : mLayersPendingRefresh) {
2053 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002054 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002055 invalidateLayerStack(layer, visibleReg);
2056 }
2057 mLayersPendingRefresh.clear();
2058 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002059}
2060
Ana Krulece588e312018-09-18 12:32:24 -07002061void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2062 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002063 // Update queue of past composite+present times and determine the
2064 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002065 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002066 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002067 while (!getBE().mCompositePresentTimes.empty()) {
2068 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002069 // Cached values should have been updated before calling this method,
2070 // which helps avoid duplicate syscalls.
2071 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2072 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2073 break;
2074 }
2075 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002076 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002077 }
2078
2079 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002080 while (getBE().mCompositePresentTimes.size() > 16) {
2081 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002082 }
2083
Ana Krulece588e312018-09-18 12:32:24 -07002084 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002085}
2086
Ana Krulece588e312018-09-18 12:32:24 -07002087void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2088 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002089 // Integer division and modulo round toward 0 not -inf, so we need to
2090 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002091 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2092 ? (stats.vsyncPeriod -
2093 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2094 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002095
Ady Abraham9e16a482019-12-03 17:19:41 -08002096 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002097 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002098 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002099 }
2100
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002101 // Snap the latency to a value that removes scheduling jitter from the
2102 // composition and present times, which often have >1ms of jitter.
2103 // Reducing jitter is important if an app attempts to extrapolate
2104 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002105 // Snapping also allows an app to precisely calculate
2106 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002107 nsecs_t bias = stats.vsyncPeriod / 2;
2108 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2109 nsecs_t snappedCompositeToPresentLatency =
2110 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002111
David Sodman99974d22017-11-28 12:04:33 -08002112 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002113 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2114 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002115 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002116}
2117
David Sodman2b406362017-12-15 13:33:47 -08002118void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002119{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002120 ATRACE_CALL();
2121 ALOGV("postComposition");
2122
Brian Andersonf6386862016-10-31 16:34:13 -07002123 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002124 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002125 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002126 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002127 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002128 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002129
David Sodman73beded2017-11-15 11:56:06 -08002130 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002131 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002132 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002133 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002134 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2135 ->getRenderSurface()
2136 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002137 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002138 } else {
2139 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2140 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002141
David Sodman73beded2017-11-15 11:56:06 -08002142 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002143 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2144 mPreviousPresentFences[0] = displayDevice
2145 ? getHwComposer().getPresentFence(*displayDevice->getId())
2146 : Fence::NO_FENCE;
2147 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002148 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002149
Ana Krulece588e312018-09-18 12:32:24 -07002150 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002151 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002152
Lloyd Piqueab039b52019-02-13 14:22:42 -08002153 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2154 // be sampled a little later than when we started doing work for this frame,
2155 // but that should be okay since updateCompositorTiming has snapping logic.
2156 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2157 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002158 CompositorTiming compositorTiming;
2159 {
David Sodman99974d22017-11-28 12:04:33 -08002160 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2161 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002162 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002163
Edgar Arriaga844fa672020-01-16 14:21:42 -08002164 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002165 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2166 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002167 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002168 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002169 }
Robert Carr2047fae2016-11-28 14:09:09 -08002170 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002171
Ady Abraham92fa2f42020-02-11 15:33:56 -08002172 if (displayDevice && displayDevice->isPrimary() &&
2173 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002174 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002175 }
2176
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002177 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002178 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2179 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002180 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002181 }
2182 }
2183
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002184 if (mAnimCompositionPending) {
2185 mAnimCompositionPending = false;
2186
Brian Anderson4e606e32017-03-16 15:34:57 -07002187 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002188 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002189 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002190 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002191 // The HWC doesn't support present fences, so use the refresh
2192 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002193 const nsecs_t presentTime =
2194 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002195 mAnimFrameTracker.setActualPresentTime(presentTime);
2196 }
2197 mAnimFrameTracker.advanceFrame();
2198 }
Dan Stozab90cf072015-03-05 11:05:59 -08002199
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002200 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002201 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002202 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002203 }
2204
Vishnu Nair9b079a22020-01-21 14:36:08 -08002205 if (mReusedClientComposition) {
2206 mTimeStats->incrementClientCompositionReusedFrames();
2207 }
2208
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002209 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002210
Alec Mouri717bcb62020-02-10 17:07:19 -08002211 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2212 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2213 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2214
Lloyd Pique32cbe282018-10-19 13:09:22 -07002215 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2216 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002217 return;
2218 }
2219
2220 nsecs_t currentTime = systemTime();
2221 if (mHasPoweredOff) {
2222 mHasPoweredOff = false;
2223 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002224 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002225 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002226 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2227 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002228 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002229 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002230 }
David Sodman4a36e932017-11-07 14:29:47 -08002231 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002232 }
David Sodman4a36e932017-11-07 14:29:47 -08002233 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002234
2235 {
2236 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002237 if (mTexturePool.size() < mTexturePoolSize) {
2238 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002239 const size_t offset = mTexturePool.size();
2240 mTexturePool.resize(mTexturePoolSize);
2241 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2242 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002243 } else if (mTexturePool.size() > mTexturePoolSize) {
2244 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2245 const size_t offset = mTexturePoolSize;
2246 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2247 mTexturePool.resize(mTexturePoolSize);
2248 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002249 }
2250 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002251
Ady Abrahambe0f9482019-04-24 15:41:53 -07002252 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002253 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002254
Kevin DuBois413287f2019-02-25 08:46:47 -08002255 if (mLumaSampling && mRegionSamplingThread) {
2256 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002257 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002258
2259 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2260 // side-effect of getTotalSize(), so we check that again here
2261 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002262 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002263 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2264 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002265}
2266
Vishnu Nair4351ad52019-02-11 14:13:02 -08002267void SurfaceFlinger::computeLayerBounds() {
2268 for (const auto& pair : mDisplays) {
2269 const auto& displayDevice = pair.second;
2270 const auto display = displayDevice->getCompositionDisplay();
2271 for (const auto& layer : mDrawingState.layersSortedByZ) {
2272 // only consider the layers on the given layer stack
2273 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002274 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002275 }
2276
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002277 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2278 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002279 }
2280 }
2281}
2282
David Sodmanfa9b2af2017-12-24 13:28:59 -08002283void SurfaceFlinger::postFrame()
2284{
2285 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002286 const auto display = getDefaultDisplayDeviceLocked();
2287 if (display && getHwComposer().isConnected(*display->getId())) {
2288 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002289 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2290 logFrameStats();
2291 }
2292 }
2293}
2294
Mathias Agopian87baae12012-07-31 12:38:26 -07002295void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002296{
Mathias Agopian841cde52012-03-01 15:44:37 -08002297 ATRACE_CALL();
2298
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002299 // here we keep a copy of the drawing state (that is the state that's
2300 // going to be overwritten by handleTransactionLocked()) outside of
2301 // mStateLock so that the side-effects of the State assignment
2302 // don't happen with mStateLock held (which can cause deadlocks).
2303 State drawingState(mDrawingState);
2304
Mathias Agopianca4d3602011-05-19 15:38:14 -07002305 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002306 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002307
Mathias Agopianca4d3602011-05-19 15:38:14 -07002308 // Here we're guaranteed that some transaction flags are set
2309 // so we can call handleTransactionLocked() unconditionally.
2310 // We call getTransactionFlags(), which will also clear the flags,
2311 // with mStateLock held to guarantee that mCurrentState won't change
2312 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002313
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002314 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002315 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002316 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002317
Mathias Agopianca4d3602011-05-19 15:38:14 -07002318 mDebugInTransaction = 0;
2319 invalidateHwcGeometry();
2320 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002321}
2322
Lloyd Piqueba04e622017-12-14 17:11:26 -08002323void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2324 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002325 const std::optional<DisplayIdentificationInfo> info =
2326 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002327
Dominik Laskowski075d3172018-05-24 15:50:06 -07002328 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002329 continue;
2330 }
2331
Dominik Laskowski55c85402020-01-21 16:25:47 -08002332 const DisplayId displayId = info->id;
2333 const auto it = mPhysicalDisplayTokens.find(displayId);
2334
Lloyd Piqueba04e622017-12-14 17:11:26 -08002335 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002336 if (it == mPhysicalDisplayTokens.end()) {
2337 ALOGV("Creating display %s", to_string(displayId).c_str());
2338
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002339 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002340 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002341 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002342
Dominik Laskowski075d3172018-05-24 15:50:06 -07002343 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002344 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002345 state.isSecure = true; // All physical displays are currently considered secure.
2346 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002347
2348 sp<IBinder> token = new BBinder();
2349 mCurrentState.displays.add(token, state);
2350 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2351
Dominik Laskowski075d3172018-05-24 15:50:06 -07002352 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002353 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002354 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002355 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002356
Dominik Laskowski55c85402020-01-21 16:25:47 -08002357 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002358 if (index >= 0) {
2359 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2360 mInterceptor->saveDisplayDeletion(state.sequenceId);
2361 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002362 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002363 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002364 }
2365
2366 processDisplayChangesLocked();
2367 }
2368
2369 mPendingHotplugEvents.clear();
2370}
2371
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002372void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002373 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2374 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002375}
2376
Lloyd Pique99d3da52018-01-22 17:48:03 -08002377sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002378 const wp<IBinder>& displayToken,
2379 std::shared_ptr<compositionengine::Display> compositionDisplay,
Lloyd Pique542307f2018-10-19 13:24:08 -07002380 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002381 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002382 auto displayId = compositionDisplay->getDisplayId();
2383 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002384 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002385 creationArgs.isSecure = state.isSecure;
2386 creationArgs.displaySurface = dispSurface;
2387 creationArgs.hasWideColorGamut = false;
2388 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002389
Dominik Laskowski55c85402020-01-21 16:25:47 -08002390 if (const auto& physical = state.physical) {
2391 creationArgs.connectionType = physical->type;
2392 }
2393
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002394 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002395 creationArgs.isPrimary = isInternalDisplay;
2396
2397 if (useColorManagement && displayId) {
2398 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002399 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002400 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002401 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002403
Dominik Laskowski7e045462018-05-30 13:02:02 -07002404 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002405 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002406 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002407 }
tangrobin6753a022018-08-10 10:58:54 +08002408 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002409
Dominik Laskowski075d3172018-05-24 15:50:06 -07002410 if (displayId) {
2411 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002412 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002413 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002414 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002415
Lloyd Pique90c115d2018-09-18 21:39:42 -07002416 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002417 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002418 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002419
Lloyd Pique99d3da52018-01-22 17:48:03 -08002420 // Make sure that composition can never be stalled by a virtual display
2421 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002422 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002423 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002424 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2425 }
2426
Dominik Laskowski718f9602019-11-09 20:01:35 -08002427 creationArgs.physicalOrientation =
2428 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002429
Lloyd Pique99d3da52018-01-22 17:48:03 -08002430 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002431 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002432
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002433 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002434
2435 if (maxFrameBufferAcquiredBuffers >= 3) {
2436 nativeWindowSurface->preallocateBuffers();
2437 }
2438
2439 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002440 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002441 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002442 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002443 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002444 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002445 display->getCompositionDisplay()->setColorProfile(
2446 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2447 RenderIntent::COLORIMETRIC,
2448 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002449 if (!state.isVirtual()) {
2450 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002451 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2452 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002453 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002454
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002455 display->setLayerStack(state.layerStack);
2456 display->setProjection(state.orientation, state.viewport, state.frame);
2457 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002458
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002459 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002460}
2461
Lloyd Pique347200f2017-12-14 17:00:15 -08002462void SurfaceFlinger::processDisplayChangesLocked() {
2463 // here we take advantage of Vector's copy-on-write semantics to
2464 // improve performance by skipping the transaction entirely when
2465 // know that the lists are identical
2466 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2467 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2468 if (!curr.isIdenticalTo(draw)) {
2469 mVisibleRegionsDirty = true;
2470 const size_t cc = curr.size();
2471 size_t dc = draw.size();
2472
2473 // find the displays that were removed
2474 // (ie: in drawing state but not in current state)
2475 // also handle displays that changed
2476 // (ie: displays that are in both lists)
2477 for (size_t i = 0; i < dc;) {
2478 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2479 if (j < 0) {
2480 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002481 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002482 // Save display ID before disconnecting.
2483 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002484 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002485
2486 if (!display->isVirtual()) {
2487 LOG_ALWAYS_FATAL_IF(!displayId);
2488 dispatchDisplayHotplugEvent(displayId->value, false);
2489 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002490 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002491
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002492 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002493 } else {
2494 // this display is in both lists. see if something changed.
2495 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002496 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002497 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2498 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2499 if (state_binder != draw_binder) {
2500 // changing the surface is like destroying and
2501 // recreating the DisplayDevice, so we just remove it
2502 // from the drawing state, so that it get re-added
2503 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002504 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002505 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002506 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002507 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002508 mDrawingState.displays.removeItemsAt(i);
2509 dc--;
2510 // at this point we must loop to the next item
2511 continue;
2512 }
2513
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002514 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002515 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002516 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002517 }
2518 if ((state.orientation != draw[i].orientation) ||
2519 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002520 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002521 }
2522 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002523 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002524 if (display->isPrimary()) {
2525 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2526 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002527 }
2528 }
2529 }
2530 ++i;
2531 }
2532
2533 // find displays that were added
2534 // (ie: in current state but not in drawing state)
2535 for (size_t i = 0; i < cc; i++) {
2536 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2537 const DisplayDeviceState& state(curr[i]);
2538
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002539 int width = 0;
2540 int height = 0;
2541 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2542 if (state.physical) {
2543 const auto& activeConfig =
2544 getCompositionEngine().getHwComposer().getActiveConfig(
2545 state.physical->id);
2546 width = activeConfig->getWidth();
2547 height = activeConfig->getHeight();
2548 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2549 } else if (state.surface != nullptr) {
2550 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2551 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2552 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2553 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2554 int intPixelFormat;
2555 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2556 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2557 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2558 } else {
2559 // Virtual displays without a surface are dormant:
2560 // they have external state (layer stack, projection,
2561 // etc.) but no internal state (i.e. a DisplayDevice).
2562 continue;
2563 }
2564
2565 compositionengine::DisplayCreationArgsBuilder builder;
2566 if (const auto& physical = state.physical) {
2567 builder.setPhysical({physical->id, physical->type});
2568 }
2569 builder.setPixels(ui::Size(width, height));
2570 builder.setPixelFormat(pixelFormat);
2571 builder.setIsSecure(state.isSecure);
2572 builder.setLayerStackId(state.layerStack);
2573 builder.setPowerAdvisor(&mPowerAdvisor);
2574 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays ||
2575 getHwComposer().isUsingVrComposer());
2576 builder.setName(state.displayName);
2577 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2578
Lloyd Pique542307f2018-10-19 13:24:08 -07002579 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002580 sp<IGraphicBufferProducer> producer;
2581 sp<IGraphicBufferProducer> bqProducer;
2582 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002583 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002584
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002585 std::optional<DisplayId> displayId = compositionDisplay->getId();
2586
Dominik Laskowski663bd282018-04-19 15:26:54 -07002587 if (state.isVirtual()) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002588 sp<VirtualDisplaySurface> vds =
2589 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
2590 bqProducer, bqConsumer, state.displayName);
Lloyd Pique347200f2017-12-14 17:00:15 -08002591
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002592 dispSurface = vds;
2593 producer = vds;
Lloyd Pique347200f2017-12-14 17:00:15 -08002594 } else {
2595 ALOGE_IF(state.surface != nullptr,
2596 "adding a supported display, but rendering "
2597 "surface is provided (%p), ignoring it",
2598 state.surface.get());
2599
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002600 LOG_ALWAYS_FATAL_IF(!displayId);
Brian Lindahla13f2d52020-03-05 11:54:17 +01002601 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2602 maxGraphicsWidth, maxGraphicsHeight);
Lloyd Pique347200f2017-12-14 17:00:15 -08002603 producer = bqProducer;
2604 }
2605
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002606 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002607 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002608 mDisplays.emplace(displayToken,
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002609 setupNewDisplayDeviceInternal(displayToken,
2610 compositionDisplay, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002611 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002612 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002613 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002614 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002615 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002616
2617 const auto displayDevice = mDisplays[displayToken];
2618 if (displayDevice->isPrimary()) {
2619 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2620 displayDevice->getHeight());
2621 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002622 }
2623 }
2624 }
2625 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002626
2627 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002628}
2629
Mathias Agopian87baae12012-07-31 12:38:26 -07002630void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002631{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002632 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2633
Dan Stoza7dde5992015-05-22 09:51:44 -07002634 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002635 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002636 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002637 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002638
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639 /*
2640 * Traversal of the children
2641 * (perform the transaction for each of them if needed)
2642 */
2643
Marissa Wall06255332019-03-27 13:48:27 -07002644 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002645 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002646 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002647 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648
2649 const uint32_t flags = layer->doTransaction(0);
2650 if (flags & Layer::eVisibleRegion)
2651 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002652
2653 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002654 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002655 }
Robert Carr2047fae2016-11-28 14:09:09 -08002656 });
Marissa Wall06255332019-03-27 13:48:27 -07002657 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658 }
2659
2660 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002661 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662 */
2663
Mathias Agopiane57f2922012-08-09 16:29:12 -07002664 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002665 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002666 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002667 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002669 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002670 // The transform hint might have changed for some layers
2671 // (either because a display has changed, or because a layer
2672 // as changed).
2673 //
2674 // Walk through all the layers in currentLayers,
2675 // and update their transform hint.
2676 //
2677 // If a layer is visible only on a single display, then that
2678 // display is used to calculate the hint, otherwise we use the
2679 // default display.
2680 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002681 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002682 // the hint is set before we acquire a buffer from the surface texture.
2683 //
2684 // NOTE: layer transactions have taken place already, so we use their
2685 // drawing state. However, SurfaceFlinger's own transaction has not
2686 // happened yet, so we must use the current state layer list
2687 // (soon to become the drawing state list).
2688 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002689 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002690 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002691 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002692 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002693 // NOTE: we rely on the fact that layers are sorted by
2694 // layerStack first (so we don't have to traverse the list
2695 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002696 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002697 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002698 currentlayerStack = layerStack;
2699 // figure out if this layerstack is mirrored
2700 // (more than one display) if so, pick the default display,
2701 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002702 hintDisplay = nullptr;
2703 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002704 if (display->getCompositionDisplay()
2705 ->belongsInOutput(layer->getLayerStack(),
2706 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002707 if (hintDisplay) {
2708 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002709 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002710 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002711 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002712 }
2713 }
2714 }
2715 }
Chet Haase91d25932013-04-11 15:24:55 -07002716
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002717 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002718 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2719 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002720
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002721 // could be null when this layer is using a layerStack
2722 // that is not visible on any display. Also can occur at
2723 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002724 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002725 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002726
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002727 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002728 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002729 if (hintDisplay) {
2730 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002731 }
Robert Carr2047fae2016-11-28 14:09:09 -08002732
2733 first = false;
2734 });
Mathias Agopian84300952012-11-21 16:02:13 -08002735 }
2736
2737
Mathias Agopian3559b072012-08-15 13:46:03 -07002738 /*
2739 * Perform our own transaction if needed
2740 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002741
2742 if (mLayersAdded) {
2743 mLayersAdded = false;
2744 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002745 mVisibleRegionsDirty = true;
2746 }
2747
2748 // some layers might have been removed, so
2749 // we need to update the regions they're exposing.
2750 if (mLayersRemoved) {
2751 mLayersRemoved = false;
2752 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002753 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002754 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002755 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002756 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002757 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002758 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002759 }
Robert Carr2047fae2016-11-28 14:09:09 -08002760 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002761 }
2762
Vishnu Nairec0ab382019-02-13 15:32:56 -08002763 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002764 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002765}
2766
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002767void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002768 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002769 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002770 return;
2771 }
2772
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002773 if (mVisibleRegionsDirty || mInputInfoChanged) {
2774 mInputInfoChanged = false;
2775 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002776 } else if (mInputWindowCommands.syncInputWindows) {
2777 // If the caller requested to sync input windows, but there are no
2778 // changes to input windows, notify immediately.
2779 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002780 }
2781
Arthur Hung6cbb9752019-09-05 16:38:18 +08002782 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002783}
2784
2785void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002786 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002787
2788 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2789 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002790 // When calculating the screen bounds we ignore the transparent region since it may
2791 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002792 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002793 }
2794 });
chaviw291d88a2019-02-14 10:33:58 -08002795
2796 mInputFlinger->setInputWindows(inputHandles,
2797 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2798 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002799}
2800
Vishnu Nairec0ab382019-02-13 15:32:56 -08002801void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002802 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002803 mPendingInputWindowCommands.clear();
2804}
2805
Riley Andrews03414a12014-07-01 14:22:59 -07002806void SurfaceFlinger::updateCursorAsync()
2807{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002808 compositionengine::CompositionRefreshArgs refreshArgs;
2809 for (const auto& [_, display] : mDisplays) {
2810 if (display->getId()) {
2811 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002812 }
2813 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002814
2815 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002816}
2817
Ady Abraham2139f732019-11-13 18:56:40 -08002818void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002819 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2820 // If this is called from the main thread mStateLock must be locked before
2821 // Currently the only way to call this function from the main thread is from
2822 // Sheduler::chooseRefreshRateForContent
2823
2824 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002825 changeRefreshRateLocked(refreshRate, event);
2826}
2827
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002828void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2829 if (mScheduler) {
2830 // In practice it's not allowed to hotplug in/out the primary display once it's been
2831 // connected during startup, but some tests do it, so just warn and return.
2832 ALOGW("Can't re-init scheduler");
2833 return;
2834 }
2835
Ady Abraham2139f732019-11-13 18:56:40 -08002836 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002837 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002838 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002839 primaryDisplayId),
2840 currentConfig);
2841 mRefreshRateStats =
2842 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2843 currentConfig, HWC_POWER_MODE_OFF);
2844 mRefreshRateStats->setConfigMode(currentConfig);
2845
Ady Abraham9e16a482019-12-03 17:19:41 -08002846 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2847
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002848 // start the EventThread
2849 mScheduler =
2850 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002851 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002852 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002853 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002854 impl::EventThread::InterceptVSyncsCallback());
2855 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002856 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002857 [this](nsecs_t timestamp) {
2858 mInterceptor->saveVSyncEvent(timestamp);
2859 });
2860
2861 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2862 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002863 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002864
2865 mRegionSamplingThread =
2866 new RegionSamplingThread(*this, *mScheduler,
2867 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002868 // Dispatch a config change request for the primary display on scheduler
2869 // initialization, so that the EventThreads always contain a reference to a
2870 // prior configuration.
2871 //
2872 // This is a bit hacky, but this avoids a back-pointer into the main SF
2873 // classes from EventThread, and there should be no run-time binder cost
2874 // anyway since there are no connected apps at this point.
2875 const nsecs_t vsyncPeriod =
2876 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2877 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2878 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002879}
2880
Mathias Agopian4fec8732012-06-29 14:12:52 -07002881void SurfaceFlinger::commitTransaction()
2882{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002883 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002884
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002885 mTransactionPending = false;
2886 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002887 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002888}
2889
Lloyd Pique58e24a32019-08-01 15:50:14 -07002890void SurfaceFlinger::commitTransactionLocked() {
2891 if (!mLayersPendingRemoval.isEmpty()) {
2892 // Notify removed layers now that they can't be drawn from
2893 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002894 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002895
2896 // Ensure any buffers set to display on any children are released.
2897 if (l->isRemovedFromCurrentState()) {
2898 l->latchAndReleaseBuffer();
2899 }
2900
2901 // If the layer has been removed and has no parent, then it will not be reachable
2902 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2903 // ensure we can copy its current to drawing state.
2904 if (!l->getParent()) {
2905 mOffscreenLayers.emplace(l.get());
2906 }
2907 }
2908 mLayersPendingRemoval.clear();
2909 }
2910
2911 // If this transaction is part of a window animation then the next frame
2912 // we composite should be considered an animation as well.
2913 mAnimCompositionPending = mAnimTransactionPending;
2914
2915 mDrawingState = mCurrentState;
2916 // clear the "changed" flags in current state
2917 mCurrentState.colorMatrixChanged = false;
2918
Edgar Arriaga844fa672020-01-16 14:21:42 -08002919 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002920 layer->commitChildList();
2921
2922 // If the layer can be reached when traversing mDrawingState, then the layer is no
2923 // longer offscreen. Remove the layer from the offscreenLayer set.
2924 if (mOffscreenLayers.count(layer)) {
2925 mOffscreenLayers.erase(layer);
2926 }
2927 });
2928
2929 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002930 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002931}
2932
Nataniel Borges2b796da2019-02-15 13:32:18 -08002933void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2934 if (mTracingEnabledChanged) {
2935 mTracingEnabled = mTracing.isEnabled();
2936 mTracingEnabledChanged = false;
2937 }
2938
2939 // Synchronize with Tracing thread
2940 std::unique_lock<std::mutex> lock;
2941 if (mTracingEnabled) {
2942 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2943 }
2944
2945 lockedOperation();
2946
2947 // Synchronize with Tracing thread
2948 if (mTracingEnabled) {
2949 lock.unlock();
2950 }
2951}
2952
chaviw74d90ad2019-04-26 14:45:26 -07002953void SurfaceFlinger::commitOffscreenLayers() {
2954 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002955 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002956 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2957 if (!trFlags) return;
2958
2959 layer->doTransaction(0);
2960 layer->commitChildList();
2961 });
2962 }
2963}
2964
Chia-I Wuab0c3192017-08-01 11:29:00 -07002965void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002966 for (const auto& [token, displayDevice] : mDisplays) {
2967 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002968 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002969 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002970 }
2971 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002972}
2973
Dan Stoza6b9454d2014-11-07 16:00:59 -08002974bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002975{
Ady Abraham09bd3922019-04-08 10:44:56 -07002976 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002977 ALOGV("handlePageFlip");
2978
Brian Andersond6927fb2016-07-23 23:37:30 -07002979 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002980
Mathias Agopian4fec8732012-06-29 14:12:52 -07002981 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002982 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002983 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002984
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002985 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2986
Eric Penner51c59cd2014-07-28 19:51:58 -07002987 // Store the set of layers that need updates. This set must not change as
2988 // buffers are being latched, as this could result in a deadlock.
2989 // Example: Two producers share the same command stream and:
2990 // 1.) Layer 0 is latched
2991 // 2.) Layer 0 gets a new frame
2992 // 2.) Layer 1 gets a new frame
2993 // 3.) Layer 1 is latched.
2994 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2995 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002996 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002997 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002998 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002999 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003000 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003001 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003002 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003003 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003004 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003005 } else {
3006 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003007 }
Robert Carr2047fae2016-11-28 14:09:09 -08003008 });
3009
chaviw49a108c2019-08-12 11:23:06 -07003010 // The client can continue submitting buffers for offscreen layers, but they will not
3011 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3012 // layers to ensure dequeueBuffer doesn't block indefinitely.
3013 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003014 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003015 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3016 }
3017
Lloyd Piquef2c79392018-12-20 16:23:33 -08003018 if (!mLayersWithQueuedFrames.empty()) {
3019 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3020 // writes to Layer current state. See also b/119481871
3021 Mutex::Autolock lock(mStateLock);
3022
3023 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003024 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003025 mLayersPendingRefresh.push_back(layer);
3026 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003027 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003028 if (layer->isBufferLatched()) {
3029 newDataLatched = true;
3030 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003031 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003032 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003033
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003034 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003035
3036 // If we will need to wake up at some time in the future to deal with a
3037 // queued frame that shouldn't be displayed during this vsync period, wake
3038 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003039 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003040 signalLayerUpdate();
3041 }
3042
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003043 // enter boot animation on first buffer latch
3044 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3045 ALOGI("Enter boot animation");
3046 mBootStage = BootStage::BOOTANIMATION;
3047 }
3048
Edgar Arriaga844fa672020-01-16 14:21:42 -08003049 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003050
Dan Stoza6b9454d2014-11-07 16:00:59 -08003051 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003052 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003053}
3054
Mathias Agopianad456f92011-01-13 17:53:01 -08003055void SurfaceFlinger::invalidateHwcGeometry()
3056{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003057 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003058}
3059
Robert Carrc0df3122019-04-11 13:18:21 -07003060status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3061 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3062 const sp<IBinder>& parentHandle,
3063 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003064 // add this layer to the current state list
3065 {
3066 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003067 sp<Layer> parent;
3068 if (parentHandle != nullptr) {
3069 parent = fromHandle(parentHandle);
3070 if (parent == nullptr) {
3071 return NAME_NOT_FOUND;
3072 }
3073 } else {
3074 parent = parentLayer;
3075 }
3076
Ady Abraham0a525092020-03-03 12:51:24 -08003077 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003078 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003079 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003080 return NO_MEMORY;
3081 }
Robert Carrc0df3122019-04-11 13:18:21 -07003082
3083 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3084
Robert Carrb89ea9d2018-12-10 13:01:14 -08003085 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003086 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003087 } else if (parent == nullptr) {
3088 lbc->onRemovedFromCurrentState();
3089 } else if (parent->isRemovedFromCurrentState()) {
3090 parent->addChild(lbc);
3091 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003092 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003093 parent->addChild(lbc);
3094 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003095
Yiwei Zhang243b3782018-05-15 17:40:04 -07003096 if (gbc != nullptr) {
3097 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3098 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3099 mMaxGraphicBufferProducerListSize,
3100 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3101 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003102 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003103 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003104 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003105 }
3106
Mathias Agopian96f08192010-06-02 23:28:45 -07003107 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003108 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003109
Dan Stoza7d89d062015-04-30 13:29:25 -07003110 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003111}
3112
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003113uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003114 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003115}
3116
Mathias Agopian3f844832013-08-07 21:24:32 -07003117uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003118 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003119}
3120
Mathias Agopian3f844832013-08-07 21:24:32 -07003121uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003122 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003123}
3124
3125uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003126 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003127 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003128 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003129 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003130 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003131 }
3132 return old;
3133}
3134
Marissa Wall713b63f2018-10-17 15:42:43 -07003135bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003136 // to prevent onHandleDestroyed from being called while the lock is held,
3137 // we must keep a copy of the transactions (specifically the composer
3138 // states) around outside the scope of the lock
3139 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003140 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003141 {
3142 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003143
Valerie Haufce31b82019-04-30 16:41:14 -07003144 auto it = mTransactionQueues.begin();
3145 while (it != mTransactionQueues.end()) {
3146 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003147
Valerie Haufce31b82019-04-30 16:41:14 -07003148 while (!transactionQueue.empty()) {
3149 const auto& transaction = transactionQueue.front();
3150 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003151 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003152 transaction.states)) {
3153 setTransactionFlags(eTransactionFlushNeeded);
3154 break;
3155 }
3156 transactions.push_back(transaction);
3157 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3158 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003159 transaction.buffer, transaction.postTime,
3160 transaction.privileged, transaction.hasListenerCallbacks,
3161 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003162 transactionQueue.pop();
3163 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003164 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003165
Valerie Haufce31b82019-04-30 16:41:14 -07003166 if (transactionQueue.empty()) {
3167 it = mTransactionQueues.erase(it);
3168 mTransactionCV.broadcast();
3169 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003170 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003171 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003172 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003173 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003174 return flushedATransaction;
3175}
3176
3177bool SurfaceFlinger::transactionFlushNeeded() {
3178 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003179}
3180
chaviwca27f252018-02-06 16:46:39 -08003181
Marissa Wall17b4e452018-12-26 16:32:34 -08003182bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003183 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003184 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003185 if (!useCachedExpectedPresentTime)
3186 populateExpectedPresentTime();
3187
3188 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003189 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3190 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3191 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3192 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3193 return false;
3194 }
3195
Marissa Wall713b63f2018-10-17 15:42:43 -07003196 for (const ComposerState& state : states) {
3197 const layer_state_t& s = state.state;
3198 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3199 continue;
3200 }
3201 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003202 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003203 }
3204 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003205 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003206}
3207
Valerie Hau9dab9732019-08-20 09:29:25 -07003208void SurfaceFlinger::setTransactionState(
3209 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3210 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3211 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3212 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003213 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003214
Valerie Haubc6ddb12019-03-08 11:10:15 -08003215 const int64_t postTime = systemTime();
3216
Robert Carr14167e02019-02-13 13:50:55 -08003217 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3218
Mathias Agopian698c0872011-06-28 19:09:31 -07003219 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003220
Marissa Wall713b63f2018-10-17 15:42:43 -07003221 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003222 auto itr = mTransactionQueues.find(applyToken);
3223 // if this is an animation frame, wait until prior animation frame has
3224 // been applied by SF
3225 if (flags & eAnimation) {
3226 while (itr != mTransactionQueues.end()) {
3227 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3228 if (CC_UNLIKELY(err != NO_ERROR)) {
3229 ALOGW_IF(err == TIMED_OUT,
3230 "setTransactionState timed out "
3231 "waiting for animation frame to apply");
3232 break;
3233 }
3234 itr = mTransactionQueues.find(applyToken);
3235 }
3236 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003237
3238 // Expected present time is computed and cached on invalidate, so it may be stale.
3239 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3240 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003241 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003242 uncacheBuffer, postTime, privileged,
3243 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003244 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003245 return;
3246 }
3247
Valerie Haubc6ddb12019-03-08 11:10:15 -08003248 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003249 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3250 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003251}
3252
Valerie Hau9dab9732019-08-20 09:29:25 -07003253void SurfaceFlinger::applyTransactionState(
3254 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3255 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3256 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3257 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3258 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003259 uint32_t transactionFlags = 0;
3260
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003261 if (flags & eAnimation) {
3262 // For window updates that are part of an animation we must wait for
3263 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003264 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003265 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003266 if (CC_UNLIKELY(err != NO_ERROR)) {
3267 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003268 // caller after a few seconds.
3269 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3270 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003271 mAnimTransactionPending = false;
3272 break;
3273 }
3274 }
3275 }
3276
chaviwca27f252018-02-06 16:46:39 -08003277 for (const DisplayState& display : displays) {
3278 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003279 }
3280
Valerie Hau9dab9732019-08-20 09:29:25 -07003281 // start and end registration for listeners w/ no surface so they can get their callback. Note
3282 // that listeners with SurfaceControls will start registration during setClientStateLocked
3283 // below.
3284 for (const auto& listener : listenerCallbacks) {
3285 mTransactionCompletedThread.startRegistration(listener);
3286 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003287 }
3288
Valerie Hau9dab9732019-08-20 09:29:25 -07003289 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003290 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003291 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003292 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3293 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003294 }
3295
Valerie Hau9dab9732019-08-20 09:29:25 -07003296 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003297 mTransactionCompletedThread.endRegistration(listenerCallback);
3298 }
3299
Marissa Walle2ffb422018-10-12 11:33:52 -07003300 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003301 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003302 mTransactionCompletedThread.sendCallbacks();
3303 }
3304 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003305
chaviw273171b2018-12-26 11:46:30 -08003306 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3307
Marissa Wall947d34e2019-03-29 14:03:53 -07003308 if (uncacheBuffer.isValid()) {
3309 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003310 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003311 }
3312
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003313 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3314 // anyway. This can be used as a flush mechanism for previous async transactions.
3315 // Empty animation transaction can be used to simulate back-pressure, so also force a
3316 // transaction for empty animation transactions.
3317 if (transactionFlags == 0 &&
3318 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003319 transactionFlags = eTransactionNeeded;
3320 }
3321
Marissa Wall06255332019-03-27 13:48:27 -07003322 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3323 // so we don't have to wake up again next frame to preform an uneeded traversal.
3324 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3325 transactionFlags = transactionFlags & (~eTraversalNeeded);
3326 mTraversalNeededMainThread = true;
3327 }
3328
Mathias Agopian386aa982011-11-07 21:58:03 -08003329 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003330 if (mInterceptor->isEnabled()) {
3331 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003332 }
Irvel468051e2016-06-13 16:44:44 -07003333
Mathias Agopian386aa982011-11-07 21:58:03 -08003334 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003335 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3336 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003337 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003338
3339 // if this is a synchronous transaction, wait for it to take effect
3340 // before returning.
3341 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003342 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003343 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003344 if (flags & eAnimation) {
3345 mAnimTransactionPending = true;
3346 }
chaviw4fe36852019-04-15 16:25:49 -07003347 if (mPendingInputWindowCommands.syncInputWindows) {
3348 mPendingSyncInputWindows = true;
3349 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003350
3351 // applyTransactionState can be called by either the main SF thread or by
3352 // another process through setTransactionState. While a given process may wish
3353 // to wait on synchronous transactions, the main SF thread should never
3354 // be blocked. Therefore, we only wait if isMainThread is false.
3355 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003356 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3357 if (CC_UNLIKELY(err != NO_ERROR)) {
3358 // just in case something goes wrong in SF, return to the
3359 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003360 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3361 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003362 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003363 break;
3364 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003365 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003366 }
3367}
3368
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003369uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3370 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3371 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003372
Mathias Agopiane57f2922012-08-09 16:29:12 -07003373 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003374 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3375
3376 const uint32_t what = s.what;
3377 if (what & DisplayState::eSurfaceChanged) {
3378 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3379 state.surface = s.surface;
3380 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003381 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003382 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003383 if (what & DisplayState::eLayerStackChanged) {
3384 if (state.layerStack != s.layerStack) {
3385 state.layerStack = s.layerStack;
3386 flags |= eDisplayTransactionNeeded;
3387 }
3388 }
3389 if (what & DisplayState::eDisplayProjectionChanged) {
3390 if (state.orientation != s.orientation) {
3391 state.orientation = s.orientation;
3392 flags |= eDisplayTransactionNeeded;
3393 }
3394 if (state.frame != s.frame) {
3395 state.frame = s.frame;
3396 flags |= eDisplayTransactionNeeded;
3397 }
3398 if (state.viewport != s.viewport) {
3399 state.viewport = s.viewport;
3400 flags |= eDisplayTransactionNeeded;
3401 }
3402 }
3403 if (what & DisplayState::eDisplaySizeChanged) {
3404 if (state.width != s.width) {
3405 state.width = s.width;
3406 flags |= eDisplayTransactionNeeded;
3407 }
3408 if (state.height != s.height) {
3409 state.height = s.height;
3410 flags |= eDisplayTransactionNeeded;
3411 }
3412 }
3413
Mathias Agopiane57f2922012-08-09 16:29:12 -07003414 return flags;
3415}
3416
Robert Carr14167e02019-02-13 13:50:55 -08003417bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003418 IPCThreadState* ipc = IPCThreadState::self();
3419 const int pid = ipc->getCallingPid();
3420 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003421 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003422 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003423 return false;
3424 }
3425 return true;
3426}
3427
Marissa Wall3dad52d2019-03-22 14:03:19 -07003428uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003429 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3430 bool privileged,
3431 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003432 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003433
Valerie Hau9dab9732019-08-20 09:29:25 -07003434 for (auto& listener : s.listeners) {
3435 // note that startRegistration will not re-register if the listener has
3436 // already be registered for a prior surface control
3437 mTransactionCompletedThread.startRegistration(listener);
3438 listenerCallbacks.insert(listener);
3439 }
3440
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003441 sp<Layer> layer = nullptr;
3442 if (s.surface) {
3443 layer = fromHandle(s.surface);
3444 } else {
3445 // The client may provide us a null handle. Treat it as if the layer was removed.
3446 ALOGW("Attempt to set client state with a null layer handle");
3447 }
chaviw8b3871a2017-11-01 17:41:01 -07003448 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003449 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003450 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003451 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003452 }
chaviw8b3871a2017-11-01 17:41:01 -07003453 return 0;
3454 }
3455
chaviw8b3871a2017-11-01 17:41:01 -07003456 uint32_t flags = 0;
3457
Garfield Tan8a3083e2018-12-03 13:21:07 -08003458 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003459
3460 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3461 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003462 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003463 layer->pushPendingState();
3464 }
3465
Valerie Hau871d6352020-01-29 08:44:02 -08003466 // Only set by BLAST adapter layers
3467 if (what & layer_state_t::eProducerDisconnect) {
3468 layer->onDisconnect();
3469 }
3470
chaviw8b3871a2017-11-01 17:41:01 -07003471 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003472 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003473 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003474 }
chaviw8b3871a2017-11-01 17:41:01 -07003475 }
3476 if (what & layer_state_t::eLayerChanged) {
3477 // NOTE: index needs to be calculated before we update the state
3478 const auto& p = layer->getParent();
3479 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003480 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003481 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003482 mCurrentState.layersSortedByZ.removeAt(idx);
3483 mCurrentState.layersSortedByZ.add(layer);
3484 // we need traversal (state changed)
3485 // AND transaction (list changed)
3486 flags |= eTransactionNeeded|eTraversalNeeded;
3487 }
chaviw8b3871a2017-11-01 17:41:01 -07003488 } else {
3489 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003490 flags |= eTransactionNeeded|eTraversalNeeded;
3491 }
3492 }
chaviw8b3871a2017-11-01 17:41:01 -07003493 }
3494 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003495 // NOTE: index needs to be calculated before we update the state
3496 const auto& p = layer->getParent();
3497 if (p == nullptr) {
3498 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3499 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3500 mCurrentState.layersSortedByZ.removeAt(idx);
3501 mCurrentState.layersSortedByZ.add(layer);
3502 // we need traversal (state changed)
3503 // AND transaction (list changed)
3504 flags |= eTransactionNeeded|eTraversalNeeded;
3505 }
3506 } else {
3507 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3508 flags |= eTransactionNeeded|eTraversalNeeded;
3509 }
chaviw8b3871a2017-11-01 17:41:01 -07003510 }
3511 }
3512 if (what & layer_state_t::eSizeChanged) {
3513 if (layer->setSize(s.w, s.h)) {
3514 flags |= eTraversalNeeded;
3515 }
3516 }
3517 if (what & layer_state_t::eAlphaChanged) {
3518 if (layer->setAlpha(s.alpha))
3519 flags |= eTraversalNeeded;
3520 }
3521 if (what & layer_state_t::eColorChanged) {
3522 if (layer->setColor(s.color))
3523 flags |= eTraversalNeeded;
3524 }
Peiyong Lind3788632018-09-18 16:01:31 -07003525 if (what & layer_state_t::eColorTransformChanged) {
3526 if (layer->setColorTransform(s.colorTransform)) {
3527 flags |= eTraversalNeeded;
3528 }
3529 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003530 if (what & layer_state_t::eBackgroundColorChanged) {
3531 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3532 flags |= eTraversalNeeded;
3533 }
3534 }
chaviw8b3871a2017-11-01 17:41:01 -07003535 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003536 // TODO: b/109894387
3537 //
3538 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3539 // rotation. To see the problem observe that if we have a square parent, and a child
3540 // of the same size, then we rotate the child 45 degrees around it's center, the child
3541 // must now be cropped to a non rectangular 8 sided region.
3542 //
3543 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3544 // private API, and the WindowManager only uses rotation in one case, which is on a top
3545 // level layer in which cropping is not an issue.
3546 //
3547 // However given that abuse of rotation matrices could lead to surfaces extending outside
3548 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3549 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3550 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003551 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003552 flags |= eTraversalNeeded;
3553 }
3554 if (what & layer_state_t::eTransparentRegionChanged) {
3555 if (layer->setTransparentRegionHint(s.transparentRegion))
3556 flags |= eTraversalNeeded;
3557 }
3558 if (what & layer_state_t::eFlagsChanged) {
3559 if (layer->setFlags(s.flags, s.mask))
3560 flags |= eTraversalNeeded;
3561 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003562 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003563 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003564 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003565 if (what & layer_state_t::eCornerRadiusChanged) {
3566 if (layer->setCornerRadius(s.cornerRadius))
3567 flags |= eTraversalNeeded;
3568 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003569 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3570 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3571 }
chaviw8b3871a2017-11-01 17:41:01 -07003572 if (what & layer_state_t::eLayerStackChanged) {
3573 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3574 // We only allow setting layer stacks for top level layers,
3575 // everything else inherits layer stack from its parent.
3576 if (layer->hasParent()) {
3577 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003578 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003579 } else if (idx < 0) {
3580 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003581 "that also does not appear in the top level layer list. Something"
3582 " has gone wrong.",
3583 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003584 } else if (layer->setLayerStack(s.layerStack)) {
3585 mCurrentState.layersSortedByZ.removeAt(idx);
3586 mCurrentState.layersSortedByZ.add(layer);
3587 // we need traversal (state changed)
3588 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003589 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003590 }
3591 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003592 if (what & layer_state_t::eDeferTransaction_legacy) {
3593 if (s.barrierHandle_legacy != nullptr) {
3594 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3595 } else if (s.barrierGbp_legacy != nullptr) {
3596 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003597 if (authenticateSurfaceTextureLocked(gbp)) {
3598 const auto& otherLayer =
3599 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003600 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003601 } else {
3602 ALOGE("Attempt to defer transaction to to an"
3603 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003604 }
3605 }
chaviw8b3871a2017-11-01 17:41:01 -07003606 // We don't trigger a traversal here because if no other state is
3607 // changed, we don't want this to cause any more work
3608 }
chaviw8b3871a2017-11-01 17:41:01 -07003609 if (what & layer_state_t::eReparentChildren) {
3610 if (layer->reparentChildren(s.reparentHandle)) {
3611 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003612 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003613 }
chaviw8b3871a2017-11-01 17:41:01 -07003614 if (what & layer_state_t::eDetachChildren) {
3615 layer->detachChildren();
3616 }
3617 if (what & layer_state_t::eOverrideScalingModeChanged) {
3618 layer->setOverrideScalingMode(s.overrideScalingMode);
3619 // We don't trigger a traversal here because if no other state is
3620 // changed, we don't want this to cause any more work
3621 }
Marissa Wall61c58622018-07-18 10:12:20 -07003622 if (what & layer_state_t::eTransformChanged) {
3623 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3624 }
3625 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3626 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3627 flags |= eTraversalNeeded;
3628 }
3629 if (what & layer_state_t::eCropChanged) {
3630 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3631 }
Marissa Wall861616d2018-10-22 12:52:23 -07003632 if (what & layer_state_t::eFrameChanged) {
3633 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3634 }
Marissa Wall61c58622018-07-18 10:12:20 -07003635 if (what & layer_state_t::eAcquireFenceChanged) {
3636 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3637 }
3638 if (what & layer_state_t::eDataspaceChanged) {
3639 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3640 }
3641 if (what & layer_state_t::eHdrMetadataChanged) {
3642 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3643 }
3644 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3645 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3646 }
3647 if (what & layer_state_t::eApiChanged) {
3648 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3649 }
3650 if (what & layer_state_t::eSidebandStreamChanged) {
3651 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3652 }
Robert Carr720e5062018-07-30 17:45:14 -07003653 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003654 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003655 layer->setInputInfo(s.inputInfo);
3656 flags |= eTraversalNeeded;
3657 } else {
3658 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3659 }
Robert Carr720e5062018-07-30 17:45:14 -07003660 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003661 if (what & layer_state_t::eMetadataChanged) {
3662 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3663 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003664 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3665 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3666 flags |= eTraversalNeeded;
3667 }
3668 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003669 if (what & layer_state_t::eShadowRadiusChanged) {
3670 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3671 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003672 if (what & layer_state_t::eFrameRateSelectionPriority) {
3673 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3674 flags |= eTraversalNeeded;
3675 }
3676 }
Steven Thomas3172e202020-01-06 19:25:30 -08003677 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003678 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3679 "SurfaceFlinger::setClientStateLocked") &&
3680 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3681 Layer::FrameRate::convertCompatibility(
3682 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003683 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003684 }
Steven Thomas3172e202020-01-06 19:25:30 -08003685 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003686 // This has to happen after we reparent children because when we reparent to null we remove
3687 // child layers from current state and remove its relative z. If the children are reparented in
3688 // the same transaction, then we have to make sure we reparent the children first so we do not
3689 // lose its relative z order.
3690 if (what & layer_state_t::eReparent) {
3691 bool hadParent = layer->hasParent();
3692 if (layer->reparent(s.parentHandleForChild)) {
3693 if (!hadParent) {
3694 mCurrentState.layersSortedByZ.remove(layer);
3695 }
3696 flags |= eTransactionNeeded | eTraversalNeeded;
3697 }
3698 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003699 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003700 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3701 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003702 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3703 }
3704 }
Marissa Wall78b72202019-03-15 14:58:34 -07003705 bool bufferChanged = what & layer_state_t::eBufferChanged;
3706 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3707 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003708 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003709 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003710 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3711 if (success) {
3712 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3713 success = ClientCache::getInstance()
3714 .registerErasedRecipient(s.cachedBuffer,
3715 wp<ClientCache::ErasedRecipient>(this));
3716 if (!success) {
3717 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3718 }
3719 }
Marissa Wall78b72202019-03-15 14:58:34 -07003720 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003721 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003722 } else if (bufferChanged) {
3723 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003724 }
Marissa Wall78b72202019-03-15 14:58:34 -07003725 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003726 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3727 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003728 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003729 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003730 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003731 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3732 // Do not put anything that updates layer state or modifies flags after
3733 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003734 return flags;
3735}
3736
chaviw273171b2018-12-26 11:46:30 -08003737uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3738 uint32_t flags = 0;
3739 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3740 flags |= eTraversalNeeded;
3741 }
3742
chaviwa911b102019-02-14 10:18:33 -08003743 if (inputWindowCommands.syncInputWindows) {
3744 flags |= eTraversalNeeded;
3745 }
3746
Vishnu Nairec0ab382019-02-13 15:32:56 -08003747 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003748 return flags;
3749}
3750
chaviwfe94a222019-08-21 13:52:59 -07003751status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3752 sp<IBinder>* outHandle) {
3753 if (!mirrorFromHandle) {
3754 return NAME_NOT_FOUND;
3755 }
3756
3757 sp<Layer> mirrorLayer;
3758 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003759 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003760
3761 {
3762 Mutex::Autolock _l(mStateLock);
3763 mirrorFrom = fromHandle(mirrorFromHandle);
3764 if (!mirrorFrom) {
3765 return NAME_NOT_FOUND;
3766 }
3767
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003768 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3769 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003770 if (result != NO_ERROR) {
3771 return result;
3772 }
3773
3774 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3775 }
3776
3777 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3778}
3779
Marissa Wall2d814fb2019-04-09 18:52:57 +00003780status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3781 uint32_t h, PixelFormat format, uint32_t flags,
3782 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003783 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003784 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3785 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003786 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003787 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003788 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003789 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003790 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003791
Robert Carrc0df3122019-04-11 13:18:21 -07003792 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3793 "Expected only one of parentLayer or parentHandle to be non-null. "
3794 "Programmer error?");
3795
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003796 status_t result = NO_ERROR;
3797
3798 sp<Layer> layer;
3799
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003800 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003801
Evan Roskya1f1e152019-01-24 16:17:46 -08003802 bool primaryDisplayOnly = false;
3803
3804 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3805 // TODO b/64227542
3806 if (metadata.has(METADATA_WINDOW_TYPE)) {
3807 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3808 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003809 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003810 primaryDisplayOnly = true;
3811 }
3812 }
3813
Mathias Agopian3165cc22012-08-08 19:42:09 -07003814 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003815 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003816 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3817 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003818
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003819 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003820 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003821 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003822 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003823 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003824 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003825 // check if buffer size is set for color layer.
3826 if (w > 0 || h > 0) {
3827 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3828 int(w), int(h));
3829 return BAD_VALUE;
3830 }
3831
Vishnu Nairfa247b12020-02-11 08:58:26 -08003832 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3833 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003834 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003835 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003836 // check if buffer size is set for container layer.
3837 if (w > 0 || h > 0) {
3838 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3839 int(w), int(h));
3840 return BAD_VALUE;
3841 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003842 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3843 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003844 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003845 default:
3846 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003847 break;
3848 }
3849
Dan Stoza7d89d062015-04-30 13:29:25 -07003850 if (result != NO_ERROR) {
3851 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003852 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003853
Evan Roskya1f1e152019-01-24 16:17:46 -08003854 if (primaryDisplayOnly) {
3855 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003856 }
3857
Robert Carrb89ea9d2018-12-10 13:01:14 -08003858 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003859 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3860 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003861 if (result != NO_ERROR) {
3862 return result;
3863 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003864 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003865
3866 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003867 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003868}
3869
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003870std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3871 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003872
3873 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003874 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003875
Dan Stoza436ccf32018-06-21 12:10:12 -07003876 // Grab the state lock since we're accessing mCurrentState
3877 Mutex::Autolock lock(mStateLock);
3878
Cody Northropbc755282017-03-31 12:00:08 -06003879 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003880 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003881 while (matchFound) {
3882 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003883 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003884 if (layer->getName() == uniqueName) {
3885 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003886 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003887 }
3888 });
3889 }
3890
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003891 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003892 return uniqueName;
3893}
3894
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003895status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003896 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003897 LayerMetadata metadata, PixelFormat& format,
3898 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003899 sp<IGraphicBufferProducer>* gbp,
3900 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003901 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003902 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003903 case PIXEL_FORMAT_TRANSPARENT:
3904 case PIXEL_FORMAT_TRANSLUCENT:
3905 format = PIXEL_FORMAT_RGBA_8888;
3906 break;
3907 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003908 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003909 break;
3910 }
3911
chaviwb4c6e582019-08-16 14:35:07 -07003912 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003913 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003914 args.textureName = getNewTexture();
3915 {
3916 // Grab the SF state lock during this since it's the only safe way to access
3917 // RenderEngine when creating a BufferLayerConsumer
3918 // TODO: Check if this lock is still needed here
3919 Mutex::Autolock lock(mStateLock);
3920 layer = getFactory().createBufferQueueLayer(args);
3921 }
3922
Marissa Wallfd668622018-05-10 10:21:13 -07003923 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003924 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003925 *handle = layer->getHandle();
3926 *gbp = layer->getProducer();
3927 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003928 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003929
Marissa Wallfd668622018-05-10 10:21:13 -07003930 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003931 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003932}
3933
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003934status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003935 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003936 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003937 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003938 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003939 args.displayDevice = getDefaultDisplayDevice();
3940 args.textureName = getNewTexture();
3941 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003942 if (outTransformHint) {
3943 *outTransformHint = layer->getTransformHint();
3944 }
Marissa Wall61c58622018-07-18 10:12:20 -07003945 *handle = layer->getHandle();
3946 *outLayer = layer;
3947
3948 return NO_ERROR;
3949}
3950
Vishnu Nairfa247b12020-02-11 08:58:26 -08003951status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3952 uint32_t h, uint32_t flags, LayerMetadata metadata,
3953 sp<IBinder>* handle, sp<Layer>* outLayer) {
3954 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003955 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003956 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003957 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003958}
3959
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003960status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003961 uint32_t w, uint32_t h, uint32_t flags,
3962 LayerMetadata metadata, sp<IBinder>* handle,
3963 sp<Layer>* outLayer) {
3964 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003965 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003966 *handle = (*outLayer)->getHandle();
3967 return NO_ERROR;
3968}
3969
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003970void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003971 mLayersPendingRemoval.add(layer);
3972 mLayersRemoved = true;
3973 setTransactionFlags(eTransactionNeeded);
3974}
3975
Robert Carr695d5282018-12-18 15:27:58 -08003976void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003977{
Robert Carr2e102c92018-10-23 12:11:15 -07003978 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003979 // If a layer has a parent, we allow it to out-live it's handle
3980 // with the idea that the parent holds a reference and will eventually
3981 // be cleaned up. However no one cleans up the top-level so we do so
3982 // here.
3983 if (layer->getParent() == nullptr) {
3984 mCurrentState.layersSortedByZ.remove(layer);
3985 }
3986 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003987
3988 auto it = mLayersByLocalBinderToken.begin();
3989 while (it != mLayersByLocalBinderToken.end()) {
3990 if (it->second == layer) {
3991 it = mLayersByLocalBinderToken.erase(it);
3992 } else {
3993 it++;
3994 }
3995 }
3996
Robert Carr695d5282018-12-18 15:27:58 -08003997 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003998}
3999
Mathias Agopianb60314a2012-04-10 22:09:54 -07004000// ---------------------------------------------------------------------------
4001
Andy McFadden13a082e2012-08-24 10:16:42 -07004002void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004003 const auto display = getDefaultDisplayDeviceLocked();
4004 if (!display) return;
4005
4006 const sp<IBinder> token = display->getDisplayToken().promote();
4007 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004008
Jesse Hall01e29052013-02-19 16:13:35 -08004009 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004010 Vector<ComposerState> state;
4011 Vector<DisplayState> displays;
4012 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004013 d.what = DisplayState::eDisplayProjectionChanged |
4014 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004015 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004016 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004017 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004018 d.frame.makeInvalid();
4019 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004020 d.width = 0;
4021 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004022 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004023 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4024 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004025
Dominik Laskowskie9774092018-12-11 10:04:24 -08004026 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004027
Dominik Laskowski83b88212018-12-11 13:34:06 -08004028 const nsecs_t vsyncPeriod = getVsyncPeriod();
4029 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004030
Brian Andersond0010582017-03-07 13:20:31 -08004031 // Use phase of 0 since phase is not known.
4032 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004033 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004034 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004035}
4036
4037void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004038 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004039 postMessageAsync(
4040 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004041}
4042
Ady Abraham27c70212019-06-11 10:52:26 -07004043void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4044 if (mHWCVsyncState != enabled) {
4045 getHwComposer().setVsyncEnabled(displayId, enabled);
4046 mHWCVsyncState = enabled;
4047 }
4048}
4049
Dominik Laskowskie9774092018-12-11 10:04:24 -08004050void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004051 if (display->isVirtual()) {
4052 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004053 return;
4054 }
4055
Dominik Laskowski075d3172018-05-24 15:50:06 -07004056 const auto displayId = display->getId();
4057 LOG_ALWAYS_FATAL_IF(!displayId);
4058
Dominik Laskowski34157762018-10-31 13:07:19 -07004059 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004060
4061 int currentMode = display->getPowerMode();
4062 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004063 return;
4064 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004065
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004066 display->setPowerMode(mode);
4067
Lloyd Pique4dccc412018-01-22 17:21:36 -08004068 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004069 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004070 }
4071
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004072 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004073 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004074 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004075 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004076 mScheduler->onScreenAcquired(mAppConnectionHandle);
4077 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004078 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004079
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004080 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004081 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004082 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004083
4084 struct sched_param param = {0};
4085 param.sched_priority = 1;
4086 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4087 ALOGW("Couldn't set SCHED_FIFO on display on");
4088 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004089 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004090 // Turn off the display
4091 struct sched_param param = {0};
4092 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4093 ALOGW("Couldn't set SCHED_OTHER on display off");
4094 }
4095
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004096 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004097 mScheduler->disableHardwareVsync(true);
4098 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004099 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004100
Ady Abraham27c70212019-06-11 10:52:26 -07004101 // Make sure HWVsync is disabled before turning off the display
4102 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4103
Dominik Laskowski075d3172018-05-24 15:50:06 -07004104 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004105 mVisibleRegionsDirty = true;
4106 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004107 } else if (mode == HWC_POWER_MODE_DOZE ||
4108 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004109 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004110 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004111 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004112 mScheduler->onScreenAcquired(mAppConnectionHandle);
4113 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004114 }
4115 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4116 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004117 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004118 mScheduler->disableHardwareVsync(true);
4119 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004120 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004121 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004122 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004123 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004124 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004125 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004126
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004127 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004128 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004129 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004130 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004131 }
4132
Dominik Laskowski34157762018-10-31 13:07:19 -07004133 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004134}
4135
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004136void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004137 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004138 const auto display = getDisplayDevice(displayToken);
4139 if (!display) {
4140 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4141 displayToken.get());
4142 } else if (display->isVirtual()) {
4143 ALOGW("Attempt to set power mode %d for virtual display", mode);
4144 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004145 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004146 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004147 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004148}
4149
4150// ---------------------------------------------------------------------------
4151
Dominik Laskowskic2867142019-01-21 11:33:38 -08004152status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4153 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004154 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004155
Mathias Agopianbd115332013-04-18 16:41:04 -07004156 IPCThreadState* ipc = IPCThreadState::self();
4157 const int pid = ipc->getCallingPid();
4158 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004159
Mathias Agopianbd115332013-04-18 16:41:04 -07004160 if ((uid != AID_SHELL) &&
4161 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004162 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4163 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004164 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004165 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004166 // (this would indicate SF is stuck, but we want to be able to
4167 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004168 status_t err = mStateLock.timedLock(s2ns(1));
4169 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004170 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004171 StringAppendF(&result,
4172 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4173 "(no locks held)\n",
4174 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004175 }
4176
Dominik Laskowskic2867142019-01-21 11:33:38 -08004177 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004178 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004179 {"--dispsync"s,
4180 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004181 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004182 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4183 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4184 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4185 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4186 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4187 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004188 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004189 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4190 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004191
Dominik Laskowskic2867142019-01-21 11:33:38 -08004192 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004193
Dominik Laskowski46470112019-08-02 13:13:11 -07004194 const auto it = dumpers.find(flag);
4195 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004196 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004197 } else if (!asProto) {
4198 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004199 }
4200
Mathias Agopian9795c422009-08-26 16:36:26 -07004201 if (locked) {
4202 mStateLock.unlock();
4203 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004204
Dominik Laskowski46470112019-08-02 13:13:11 -07004205 if (it == dumpers.end()) {
4206 const LayersProto layersProto = dumpProtoFromMainThread();
4207 if (asProto) {
4208 result.append(layersProto.SerializeAsString());
4209 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004210 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004211 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4212 result.append(LayerProtoParser::layerTreeToString(layerTree));
4213 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004214 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004215 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004216 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004217 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004218 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004219 return NO_ERROR;
4220}
4221
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004222status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4223 if (asProto && mTracing.isEnabled()) {
4224 mTracing.writeToFileAsync();
4225 }
4226
4227 return doDump(fd, DumpArgs(), asProto);
4228}
4229
Dominik Laskowskic2867142019-01-21 11:33:38 -08004230void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004231 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004232 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004233}
4234
Dominik Laskowskic2867142019-01-21 11:33:38 -08004235void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004236 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004237
Dominik Laskowskic2867142019-01-21 11:33:38 -08004238 if (args.size() > 1) {
4239 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004240 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004241 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004242 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004243 }
Robert Carr2047fae2016-11-28 14:09:09 -08004244 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004245 } else {
4246 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004247 }
4248}
4249
Dominik Laskowskic2867142019-01-21 11:33:38 -08004250void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004251 const bool clearAll = args.size() < 2;
4252 const auto name = clearAll ? String8() : String8(args[1]);
4253
Edgar Arriaga844fa672020-01-16 14:21:42 -08004254 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004255 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004256 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004257 }
Robert Carr2047fae2016-11-28 14:09:09 -08004258 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004259
Svetoslavd85084b2014-03-20 10:28:31 -07004260 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004261}
4262
Dominik Laskowskic2867142019-01-21 11:33:38 -08004263void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4264 mTimeStats->parseArgs(asProto, args, result);
4265}
4266
Jamie Gennis6547ff42013-07-16 20:12:42 -07004267// This should only be called from the main thread. Otherwise it would need
4268// the lock and should use mCurrentState rather than mDrawingState.
4269void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004270 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004271 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004272 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004273
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004274 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004275}
4276
Yiwei Zhang5434a782018-12-05 18:06:32 -08004277void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004278 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004279
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004280 if (isLayerTripleBufferingDisabled())
4281 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004282
Yiwei Zhang5434a782018-12-05 18:06:32 -08004283 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4284 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4285 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4286 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4287 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4288 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004289 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004290}
4291
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004292void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004293 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004294
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004295 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004296 result.append("\n");
4297
Ady Abraham9e16a482019-12-03 17:19:41 -08004298 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004299 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004300 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004301 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004302
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004303 HwcConfigIndexType defaultConfig;
4304 float minFps, maxFps;
4305 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004306 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004307 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004308 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004309 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004310 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4311 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004312
Ana Krulecc2870422019-01-29 19:00:58 -08004313 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004314}
4315
Yiwei Zhang5434a782018-12-05 18:06:32 -08004316void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4317 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004318 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4319 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004320 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004321 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004322 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004323 }
David Sodman4a36e932017-11-07 14:29:47 -08004324 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004325 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004326 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004327 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4328 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004329}
4330
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004331void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4332 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004333 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4334 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004335 for (const auto& segment : history) {
4336 if (!segment.usedThirdBuffer) {
4337 stats.twoBufferTime += segment.totalTime;
4338 }
4339 if (segment.occupancyAverage < 1.0f) {
4340 stats.doubleBufferedTime += segment.totalTime;
4341 } else if (segment.occupancyAverage < 2.0f) {
4342 stats.tripleBufferedTime += segment.totalTime;
4343 }
4344 ++stats.numSegments;
4345 stats.totalTime += segment.totalTime;
4346 }
4347}
4348
Yiwei Zhang5434a782018-12-05 18:06:32 -08004349void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4350 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004351
4352 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4353 const size_t count = currentLayers.size();
4354 for (size_t i=0 ; i<count ; i++) {
4355 currentLayers[i]->dumpFrameEvents(result);
4356 }
4357}
4358
Yiwei Zhang5434a782018-12-05 18:06:32 -08004359void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004360 result.append("Buffering stats:\n");
4361 result.append(" [Layer name] <Active time> <Two buffer> "
4362 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004363 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004364 typedef std::tuple<std::string, float, float, float> BufferTuple;
4365 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004366 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004367 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004368 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004369 if (stats.numSegments == 0) {
4370 continue;
4371 }
4372 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4373 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4374 stats.totalTime;
4375 float doubleBufferRatio = static_cast<float>(
4376 stats.doubleBufferedTime) / stats.totalTime;
4377 float tripleBufferRatio = static_cast<float>(
4378 stats.tripleBufferedTime) / stats.totalTime;
4379 sorted.insert({activeTime, {name, twoBufferRatio,
4380 doubleBufferRatio, tripleBufferRatio}});
4381 }
4382 for (const auto& sortedPair : sorted) {
4383 float activeTime = sortedPair.first;
4384 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004385 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4386 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004387 }
4388 result.append("\n");
4389}
4390
Yiwei Zhang5434a782018-12-05 18:06:32 -08004391void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004392 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004393 const auto displayId = display->getId();
4394 if (!displayId) {
4395 continue;
4396 }
4397 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004398 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004399 continue;
4400 }
4401
Yiwei Zhang5434a782018-12-05 18:06:32 -08004402 StringAppendF(&result,
4403 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4404 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004405 uint8_t port;
4406 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004407 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004408 result.append("no identification data\n");
4409 continue;
4410 }
4411
4412 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004413 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004414 continue;
4415 }
4416
4417 const auto edid = parseEdid(data);
4418 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004419 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004420 continue;
4421 }
4422
Yiwei Zhang5434a782018-12-05 18:06:32 -08004423 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004424 result.append(edid->displayName.data(), edid->displayName.length());
4425 result.append("\"\n");
4426 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004427}
4428
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004429void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4430 std::string& result) const {
4431 hwc2_display_t hwcDisplayId;
4432 uint8_t port;
4433 DisplayIdentificationData data;
4434
4435 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4436 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4437 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4438 }
4439}
4440
Yiwei Zhang5434a782018-12-05 18:06:32 -08004441void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004442 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004443 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4444 StringAppendF(&result, "DisplayColorSetting: %s\n",
4445 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004446
4447 // TODO: print out if wide-color mode is active or not
4448
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004449 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004450 const auto displayId = display->getId();
4451 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004452 continue;
4453 }
4454
Yiwei Zhang5434a782018-12-05 18:06:32 -08004455 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004456 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004457 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004458 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004459 }
4460
Lloyd Pique32cbe282018-10-19 13:09:22 -07004461 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004462 StringAppendF(&result, " Current color mode: %s (%d)\n",
4463 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004464 }
4465 result.append("\n");
4466}
4467
Vishnu Nair8406fd72019-07-30 11:29:31 -07004468LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -08004469 Mutex::Autolock _l(mStateLock);
4470 const auto device = getDefaultDisplayDeviceLocked();
chaviw1d044282017-09-27 12:19:28 -07004471 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004472 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Alec Mouri6b9e9912020-01-21 10:50:24 -08004473 layer->writeToProto(layersProto, traceFlags, device);
chaviw08f3cb22020-01-13 13:17:21 -08004474 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004475
chaviw1d044282017-09-27 12:19:28 -07004476 return layersProto;
4477}
4478
Alec Mouri6b9e9912020-01-21 10:50:24 -08004479void SurfaceFlinger::dumpHwc(std::string& result) const {
4480 getHwComposer().dump(result);
4481}
4482
Vishnu Nair0f085c62019-08-30 08:49:12 -07004483void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4484 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4485 // it.
4486 LayerProto* rootProto = layersProto.add_layers();
4487 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4488 rootProto->set_id(offscreenRootLayerId);
4489 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004490 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004491
4492 for (Layer* offscreenLayer : mOffscreenLayers) {
4493 // Add layer as child of the fake root
4494 rootProto->add_children(offscreenLayer->sequence);
4495
4496 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004497 LayerProto* layerProto =
4498 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004499 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004500 }
4501}
4502
Vishnu Nair8406fd72019-07-30 11:29:31 -07004503LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4504 LayersProto layersProto;
4505 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4506 return layersProto;
4507}
4508
Vishnu Nair0f085c62019-08-30 08:49:12 -07004509void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4510 result.append("Offscreen Layers:\n");
4511 postMessageSync(new LambdaMessage([&]() {
4512 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004513 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004514 layer->dumpCallingUidPid(result);
4515 });
4516 }
4517 }));
4518}
4519
Dominik Laskowskic2867142019-01-21 11:33:38 -08004520void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4521 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004522 Colorizer colorizer(colorize);
4523
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004524 // figure out if we're stuck somewhere
4525 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004526 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004527 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4528
4529 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004530 * Dump library configuration.
4531 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004532
4533 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004534 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004535 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004536 appendSfConfigString(result);
4537 appendUiConfigString(result);
4538 appendGuiConfigString(result);
4539 result.append("\n");
4540
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004541 result.append("\nDisplay identification data:\n");
4542 dumpDisplayIdentificationData(result);
4543
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004544 result.append("\nWide-Color information:\n");
4545 dumpWideColorInfo(result);
4546
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004547 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004548 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004549 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004550 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004551 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004552
Andy McFadden41d67d72014-04-25 16:58:34 -07004553 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004554 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004555 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004556 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004557 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004558
Dan Stozab90cf072015-03-05 11:05:59 -08004559 dumpStaticScreenStats(result);
4560 result.append("\n");
4561
Alec Mouri40189b02019-03-05 15:07:54 -08004562 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4563 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4564 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004565
Dan Stozae77c7662016-05-13 11:37:28 -07004566 dumpBufferingStats(result);
4567
Andy McFadden4803b742012-09-24 19:07:20 -07004568 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004569 * Dump the visible layer list
4570 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004571 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004572 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004573 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4574 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004575 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004576
Chia-I Wu2f884132018-09-13 15:17:58 -07004577 {
Lloyd Pique207def92019-02-28 16:09:52 -08004578 StringAppendF(&result, "Composition layers\n");
4579 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004580 auto* compositionState = layer->getCompositionState();
4581 if (!compositionState) return;
4582
4583 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4584 layer->getDebugName() ? layer->getDebugName()
4585 : "<unknown>");
4586 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004587 });
4588 }
4589
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004590 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004591 * Dump Display state
4592 */
4593
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004594 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004595 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004596 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004597 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004598 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004599 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004600 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004601
4602 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004603 * Dump CompositionEngine state
4604 */
4605
4606 mCompositionEngine->dump(result);
4607
4608 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004609 * Dump SurfaceFlinger global state
4610 */
4611
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004612 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004613 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004614 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004615
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004616 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004617
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004618 DebugEGLImageTracker::getInstance()->dump(result);
4619
Dominik Laskowski075d3172018-05-24 15:50:06 -07004620 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004621 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4622 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004623 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4624 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004625 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004626 StringAppendF(&result,
4627 " transaction-flags : %08x\n"
4628 " gpu_to_cpu_unsupported : %d\n",
4629 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004630
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004631 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004632 displayId && getHwComposer().isConnected(*displayId)) {
4633 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004634 StringAppendF(&result,
4635 " refresh-rate : %f fps\n"
4636 " x-dpi : %f\n"
4637 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004638 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4639 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004640 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004641
Yiwei Zhang5434a782018-12-05 18:06:32 -08004642 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004643
Dan Stozae22aec72016-08-01 13:20:59 -07004644 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004645 * Tracing state
4646 */
4647 mTracing.dump(result);
4648 result.append("\n");
4649
4650 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004651 * HWC layer minidump
4652 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004653 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004654 const auto displayId = display->getId();
4655 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004656 continue;
4657 }
4658
Yiwei Zhang5434a782018-12-05 18:06:32 -08004659 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004660 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004661 const sp<DisplayDevice> displayDevice = display;
4662 mCurrentState.traverseInZOrder(
4663 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004664 result.append("\n");
4665 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004666
4667 /*
4668 * Dump HWComposer state
4669 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004670 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004671 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004672 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004673 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004674 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004675 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004676
4677 /*
4678 * Dump gralloc state
4679 */
4680 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4681 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004682
4683 /*
4684 * Dump VrFlinger state if in use.
4685 */
4686 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4687 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004688 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004689 result.append("\n");
4690 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004691
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004692 result.append(mTimeStats->miniDump());
4693 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004694}
4695
Chia-I Wu28f320b2018-05-03 11:02:56 -07004696void SurfaceFlinger::updateColorMatrixLocked() {
4697 mat4 colorMatrix;
4698 if (mGlobalSaturationFactor != 1.0f) {
4699 // Rec.709 luma coefficients
4700 float3 luminance{0.213f, 0.715f, 0.072f};
4701 luminance *= 1.0f - mGlobalSaturationFactor;
4702 mat4 saturationMatrix = mat4(
4703 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4704 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4705 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4706 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4707 );
4708 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4709 } else {
4710 colorMatrix = mClientColorMatrix * mDaltonizer();
4711 }
4712
4713 if (mCurrentState.colorMatrix != colorMatrix) {
4714 mCurrentState.colorMatrix = colorMatrix;
4715 mCurrentState.colorMatrixChanged = true;
4716 setTransactionFlags(eTransactionNeeded);
4717 }
4718}
4719
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004720status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004721#pragma clang diagnostic push
4722#pragma clang diagnostic error "-Wswitch-enum"
4723 switch (static_cast<ISurfaceComposerTag>(code)) {
4724 // These methods should at minimum make sure that the client requested
4725 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004726 case BOOT_FINISHED:
4727 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004728 case CREATE_DISPLAY:
4729 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004730 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004731 case GET_ANIMATION_FRAME_STATS:
4732 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004733 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004734 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004735 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004736 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4737 case SET_AUTO_LOW_LATENCY_MODE:
4738 case GET_GAME_CONTENT_TYPE_SUPPORT:
4739 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004740 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004741 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004742 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004743 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004744 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004745 case NOTIFY_POWER_HINT:
4746 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004747 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4748 IPCThreadState* ipc = IPCThreadState::self();
4749 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4750 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004751 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004752 }
Robert Carr1db73f62016-12-21 12:58:51 -08004753 return OK;
4754 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004755 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004756 IPCThreadState* ipc = IPCThreadState::self();
4757 const int pid = ipc->getCallingPid();
4758 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004759 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4760 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004761 return PERMISSION_DENIED;
4762 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004763 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004764 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004765 // Used by apps to hook Choreographer to SurfaceFlinger.
4766 case CREATE_DISPLAY_EVENT_CONNECTION:
4767 // The following calls are currently used by clients that do not
4768 // request necessary permissions. However, they do not expose any secret
4769 // information, so it is OK to pass them.
4770 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004771 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004772 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004773 case GET_PHYSICAL_DISPLAY_IDS:
4774 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004775 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004776 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004777 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004778 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004779 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004780 case GET_DISPLAY_STATS:
4781 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4782 // Calling setTransactionState is safe, because you need to have been
4783 // granted a reference to Client* and Handle* to do anything with it.
4784 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004785 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004786 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004787 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004788 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004789 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004790 // setFrameRate() is deliberately available for apps to call without any
4791 // special permissions.
4792 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004793 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4794 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004795 return OK;
4796 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004797 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004798 case CAPTURE_SCREEN:
4799 case ADD_REGION_SAMPLING_LISTENER:
4800 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004801 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004802 IPCThreadState* ipc = IPCThreadState::self();
4803 const int pid = ipc->getCallingPid();
4804 const int uid = ipc->getCallingUid();
4805 if ((uid != AID_GRAPHICS) &&
4806 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4807 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4808 return PERMISSION_DENIED;
4809 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004810 return OK;
4811 }
chaviw93df2ea2019-04-30 16:45:12 -07004812 case CAPTURE_SCREEN_BY_ID: {
4813 IPCThreadState* ipc = IPCThreadState::self();
4814 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004815 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004816 return OK;
4817 }
4818 return PERMISSION_DENIED;
4819 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004820 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004821
4822 // These codes are used for the IBinder protocol to either interrogate the recipient
4823 // side of the transaction for its canonical interface descriptor or to dump its state.
4824 // We let them pass by default.
4825 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4826 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4827 code == IBinder::SYSPROPS_TRANSACTION) {
4828 return OK;
4829 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004830 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004831 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004832 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004833 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4834 return OK;
4835 }
4836 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4837 return PERMISSION_DENIED;
4838#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004839}
4840
Ana Krulec13be8ad2018-08-21 02:43:56 +00004841status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4842 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004843 status_t credentialCheck = CheckTransactCodeCredentials(code);
4844 if (credentialCheck != OK) {
4845 return credentialCheck;
4846 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004847
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004848 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4849 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004850 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004851 IPCThreadState* ipc = IPCThreadState::self();
4852 const int uid = ipc->getCallingUid();
4853 if (CC_UNLIKELY(uid != AID_SYSTEM
4854 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004855 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004856 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004857 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004858 return PERMISSION_DENIED;
4859 }
4860 int n;
4861 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004862 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004863 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004864 return NO_ERROR;
4865 case 1002: // SHOW_UPDATES
4866 n = data.readInt32();
4867 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004868 invalidateHwcGeometry();
4869 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004870 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004871 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004872 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004873 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004874 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004875 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004876 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004877 setTransactionFlags(
4878 eTransactionNeeded|
4879 eDisplayTransactionNeeded|
4880 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004881 return NO_ERROR;
4882 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004883 case 1006:{ // send empty update
4884 signalRefresh();
4885 return NO_ERROR;
4886 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004887 case 1008: // toggle use of hw composer
4888 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004889 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004890 invalidateHwcGeometry();
4891 repaintEverything();
4892 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004893 case 1009: // toggle use of transform hint
4894 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004895 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004896 invalidateHwcGeometry();
4897 repaintEverything();
4898 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004899 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004900 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004901 reply->writeInt32(0);
4902 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004903 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004904 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004905 return NO_ERROR;
4906 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004907 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004908 if (!display) {
4909 return NAME_NOT_FOUND;
4910 }
4911
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004912 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004913 return NO_ERROR;
4914 }
4915 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004916 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004917 // daltonize
4918 n = data.readInt32();
4919 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004920 case 1:
4921 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4922 break;
4923 case 2:
4924 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4925 break;
4926 case 3:
4927 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4928 break;
4929 default:
4930 mDaltonizer.setType(ColorBlindnessType::None);
4931 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004932 }
4933 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004934 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004935 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004936 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004937 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004938
4939 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004940 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004941 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004942 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004943 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004944 // apply a color matrix
4945 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004946 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004947 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004948 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004949 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004950 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004951 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004952 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004953 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004954 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004955 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004956
4957 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4958 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004959 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004960 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4961 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4962 }
4963
Chia-I Wu28f320b2018-05-03 11:02:56 -07004964 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004965 return NO_ERROR;
4966 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004967 case 1016: { // Unused.
4968 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004969 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004970 case 1017: {
4971 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004972 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004973 return NO_ERROR;
4974 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004975 case 1018: { // Modify Choreographer's phase offset
4976 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004977 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004978 return NO_ERROR;
4979 }
4980 case 1019: { // Modify SurfaceFlinger's phase offset
4981 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004982 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004983 return NO_ERROR;
4984 }
Irvel468051e2016-06-13 16:44:44 -07004985 case 1020: { // Layer updates interceptor
4986 n = data.readInt32();
4987 if (n) {
4988 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004989 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004990 }
4991 else{
4992 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004993 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004994 }
4995 return NO_ERROR;
4996 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004997 case 1021: { // Disable HWC virtual displays
4998 n = data.readInt32();
4999 mUseHwcVirtualDisplays = !n;
5000 return NO_ERROR;
5001 }
Romain Guy0147a172017-06-01 13:53:56 -07005002 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005003 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005004 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005005
Chia-I Wu28f320b2018-05-03 11:02:56 -07005006 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005007 return NO_ERROR;
5008 }
Romain Guy54f154a2017-10-24 21:40:32 +01005009 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005010 int32_t colorMode;
5011
Chia-I Wu0d711262018-05-21 15:19:35 -07005012 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005013 if (data.readInt32(&colorMode) == NO_ERROR) {
5014 mForceColorMode = static_cast<ColorMode>(colorMode);
5015 }
Romain Guy54f154a2017-10-24 21:40:32 +01005016 invalidateHwcGeometry();
5017 repaintEverything();
5018 return NO_ERROR;
5019 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005020 // Deprecate, use 1030 to check whether the device is color managed.
5021 case 1024: {
5022 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005023 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005024 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005025 n = data.readInt32();
5026 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005027 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005028 Mutex::Autolock lock(mStateLock);
5029 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005030 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005031 reply->writeInt32(NO_ERROR);
5032 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005033 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005034 bool writeFile = false;
5035 {
5036 Mutex::Autolock lock(mStateLock);
5037 mTracingEnabledChanged = true;
5038 writeFile = mTracing.disable();
5039 }
5040
5041 if (writeFile) {
5042 reply->writeInt32(mTracing.writeToFile());
5043 } else {
5044 reply->writeInt32(NO_ERROR);
5045 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005046 }
5047 return NO_ERROR;
5048 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005049 case 1026: { // Get layer tracing status
5050 reply->writeBool(mTracing.isEnabled());
5051 return NO_ERROR;
5052 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005053 // Is a DisplayColorSetting supported?
5054 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005055 const auto display = getDefaultDisplayDevice();
5056 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005057 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005058 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005059
5060 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5061 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005062 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005063 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005064 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005065 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005066 reply->writeBool(true);
5067 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005068 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005069 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005070 break;
5071 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005072 reply->writeBool(
5073 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005074 break;
5075 }
5076 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005077 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005078 // Is VrFlinger active?
5079 case 1028: {
5080 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005081 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005082 return NO_ERROR;
5083 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005084 // Set buffer size for SF tracing (value in KB)
5085 case 1029: {
5086 n = data.readInt32();
5087 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5088 ALOGW("Invalid buffer size: %d KB", n);
5089 reply->writeInt32(BAD_VALUE);
5090 return BAD_VALUE;
5091 }
5092
5093 ALOGD("Updating trace buffer to %d KB", n);
5094 mTracing.setBufferSize(n * 1024);
5095 reply->writeInt32(NO_ERROR);
5096 return NO_ERROR;
5097 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005098 // Is device color managed?
5099 case 1030: {
5100 reply->writeBool(useColorManagement);
5101 return NO_ERROR;
5102 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005103 // Override default composition data space
5104 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5105 // && adb shell stop zygote && adb shell start zygote
5106 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5107 // adb shell stop zygote && adb shell start zygote
5108 case 1031: {
5109 Mutex::Autolock _l(mStateLock);
5110 n = data.readInt32();
5111 if (n) {
5112 n = data.readInt32();
5113 if (n) {
5114 Dataspace dataspace = static_cast<Dataspace>(n);
5115 if (!validateCompositionDataspace(dataspace)) {
5116 return BAD_VALUE;
5117 }
5118 mDefaultCompositionDataspace = dataspace;
5119 }
5120 n = data.readInt32();
5121 if (n) {
5122 Dataspace dataspace = static_cast<Dataspace>(n);
5123 if (!validateCompositionDataspace(dataspace)) {
5124 return BAD_VALUE;
5125 }
5126 mWideColorGamutCompositionDataspace = dataspace;
5127 }
5128 } else {
5129 // restore composition data space.
5130 mDefaultCompositionDataspace = defaultCompositionDataspace;
5131 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5132 }
5133 return NO_ERROR;
5134 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005135 // Set trace flags
5136 case 1033: {
5137 n = data.readUint32();
5138 ALOGD("Updating trace flags to 0x%x", n);
5139 mTracing.setTraceFlags(n);
5140 reply->writeInt32(NO_ERROR);
5141 return NO_ERROR;
5142 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005143 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005144 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005145 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005146 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08005147 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
5148 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005149 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005150 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005151 } else {
5152 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005153 }
5154 return NO_ERROR;
5155 }
Ady Abraham34392f72019-04-10 11:29:27 -07005156 case 1035: {
5157 n = data.readInt32();
5158 mDebugDisplayConfigSetByBackdoor = false;
5159 if (n >= 0) {
5160 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005161 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005162 if (result != NO_ERROR) {
5163 return result;
5164 }
5165 mDebugDisplayConfigSetByBackdoor = true;
5166 }
5167 return NO_ERROR;
5168 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005169 }
5170 }
5171 return err;
5172}
5173
Steven Thomas6d8110b2017-08-31 18:24:21 -07005174void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005175 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005176 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005177}
5178
Ana Krulec7d1d6832018-12-27 11:10:09 -08005179void SurfaceFlinger::repaintEverythingForHWC() {
5180 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005181 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005182 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005183}
5184
Ady Abrahama09852a2020-02-20 14:23:42 -08005185void SurfaceFlinger::kernelTimerChanged(bool expired) {
5186 static bool updateOverlay =
5187 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5188 if (!updateOverlay || !mRefreshRateOverlay) return;
5189
5190 // Update the overlay on the main thread to avoid race conditions with
5191 // mRefreshRateConfigs->getCurrentRefreshRate()
5192 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5193 if (mRefreshRateOverlay) {
5194 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5195 const bool timerExpired = kernelTimerEnabled && expired;
5196 const auto& current = [this]() {
5197 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5198 if (mDesiredActiveConfigChanged) {
5199 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5200 mDesiredActiveConfig.configId);
5201 }
5202
5203 return mRefreshRateConfigs->getCurrentRefreshRate();
5204 }();
5205 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5206
5207 if (current != min) {
5208 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5209 mEventQueue->invalidate();
5210 }
5211 }
5212 }));
5213}
5214
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005215// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5216class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005217public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005218 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5219 ~WindowDisconnector() {
5220 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005221 }
5222
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005223private:
5224 ANativeWindow* mWindow;
5225 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005226};
5227
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005228status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005229 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005230 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5231 const Rect& sourceCrop, uint32_t reqWidth,
5232 uint32_t reqHeight, bool useIdentityTransform,
5233 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005234 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005235
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005236 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005237
Dominik Laskowski718f9602019-11-09 20:01:35 -08005238 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5239 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5240 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5241 renderAreaRotation = ui::Transform::ROT_0;
5242 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005243
Chia-I Wu20261cb2018-08-23 12:55:44 -07005244 sp<DisplayDevice> display;
5245 {
5246 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005247
Chia-I Wu20261cb2018-08-23 12:55:44 -07005248 display = getDisplayDeviceLocked(displayToken);
5249 if (!display) return BAD_VALUE;
5250
Chia-I Wucb023152018-08-28 12:57:23 -07005251 // set the requested width/height to the logical display viewport size
5252 // by default
5253 if (reqWidth == 0 || reqHeight == 0) {
5254 reqWidth = uint32_t(display->getViewport().width());
5255 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005256 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005257 }
5258
Peiyong Lin0e003c92018-09-17 11:09:51 -07005259 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005260 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005261
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005262 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5263 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005264 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005265 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005266}
5267
chaviw93df2ea2019-04-30 16:45:12 -07005268static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5269 switch (colorMode) {
5270 case ColorMode::DISPLAY_P3:
5271 case ColorMode::BT2100_PQ:
5272 case ColorMode::BT2100_HLG:
5273 case ColorMode::DISPLAY_BT2020:
5274 return Dataspace::DISPLAY_P3;
5275 default:
5276 return Dataspace::V0_SRGB;
5277 }
5278}
5279
5280const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5281 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5282 if (displayToken) {
5283 return getDisplayDeviceLocked(displayToken);
5284 }
5285 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5286 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005287 return getDisplayByLayerStack(displayOrLayerStack);
5288}
5289
5290const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005291 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005292 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005293 return display;
5294 }
5295 }
5296 return nullptr;
5297}
5298
5299status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5300 sp<GraphicBuffer>* outBuffer) {
5301 sp<DisplayDevice> display;
5302 uint32_t width;
5303 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005304 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005305 {
5306 Mutex::Autolock _l(mStateLock);
5307 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5308 if (!display) {
5309 return BAD_VALUE;
5310 }
5311
5312 width = uint32_t(display->getViewport().width());
5313 height = uint32_t(display->getViewport().height());
5314
Dominik Laskowski718f9602019-11-09 20:01:35 -08005315 const auto orientation = display->getOrientation();
5316 captureOrientation = ui::Transform::toRotationFlags(orientation);
5317
5318 switch (captureOrientation) {
5319 case ui::Transform::ROT_90:
5320 captureOrientation = ui::Transform::ROT_270;
5321 break;
5322
5323 case ui::Transform::ROT_270:
5324 captureOrientation = ui::Transform::ROT_90;
5325 break;
5326
5327 case ui::Transform::ROT_INVALID:
5328 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5329 captureOrientation = ui::Transform::ROT_0;
5330 break;
5331
5332 default:
5333 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005334 }
chaviw93df2ea2019-04-30 16:45:12 -07005335 *outDataspace =
5336 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5337 }
5338
5339 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5340 false /* captureSecureLayers */);
5341
5342 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5343 std::placeholders::_1);
5344 bool ignored = false;
5345 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5346 false /* useIdentityTransform */,
5347 ignored /* outCapturedSecureLayers */);
5348}
5349
Robert Carr866455f2019-04-02 16:28:26 -07005350status_t SurfaceFlinger::captureLayers(
5351 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5352 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5353 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5354 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005355 ATRACE_CALL();
5356
5357 class LayerRenderArea : public RenderArea {
5358 public:
Robert Carr578038f2018-03-09 12:25:24 -08005359 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005360 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005361 bool childrenOnly, const Rect& displayViewport)
5362 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005363 mLayer(layer),
5364 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005365 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005366 mFlinger(flinger),
5367 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005368 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005369 Rect getBounds() const override {
5370 const Layer::State& layerState(mLayer->getDrawingState());
5371 return mLayer->getBufferSize(layerState);
5372 }
Marissa Wall61c58622018-07-18 10:12:20 -07005373 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005374 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005375 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005376 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005377 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005378 }
chaviwa76b2712017-09-20 12:02:26 -07005379 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005380 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005381 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005382 Rect getSourceCrop() const override {
5383 if (mCrop.isEmpty()) {
5384 return getBounds();
5385 } else {
5386 return mCrop;
5387 }
5388 }
Robert Carr578038f2018-03-09 12:25:24 -08005389 class ReparentForDrawing {
5390 public:
5391 const sp<Layer>& oldParent;
5392 const sp<Layer>& newParent;
5393
Vishnu Nair4351ad52019-02-11 14:13:02 -08005394 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5395 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005396 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005397 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005398 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5399 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005400 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005401 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005402 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005403 };
5404
5405 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005406 const Rect sourceCrop = getSourceCrop();
5407 // no need to check rotation because there is none
5408 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5409 sourceCrop.height() != getReqHeight();
5410
Robert Carr578038f2018-03-09 12:25:24 -08005411 if (!mChildrenOnly) {
5412 mTransform = mLayer->getTransform().inverse();
5413 drawLayers();
5414 } else {
5415 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005416 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5417 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005418 // In the "childrenOnly" case we reparent the children to a screenshot
5419 // layer which has no properties set and which does not draw.
5420 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005421 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5422 "Screenshot Parent"s, w, h, 0,
5423 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005424
Vishnu Nair4351ad52019-02-11 14:13:02 -08005425 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005426 drawLayers();
5427 }
5428 }
chaviwa76b2712017-09-20 12:02:26 -07005429
chaviwa76b2712017-09-20 12:02:26 -07005430 private:
chaviw7206d492017-11-10 16:16:12 -08005431 const sp<Layer> mLayer;
5432 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005433
Peiyong Linefefaac2018-08-17 12:27:51 -07005434 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005435 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005436
5437 SurfaceFlinger* mFlinger;
5438 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005439 };
5440
Robert Carrc0df3122019-04-11 13:18:21 -07005441 int reqWidth = 0;
5442 int reqHeight = 0;
5443 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005444 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005445 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005446 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005447 {
5448 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005449
Robert Carrc0df3122019-04-11 13:18:21 -07005450 parent = fromHandle(layerHandleBinder);
5451 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5452 ALOGE("captureLayers called with an invalid or removed parent");
5453 return NAME_NOT_FOUND;
5454 }
5455
5456 const int uid = IPCThreadState::self()->getCallingUid();
5457 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5458 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5459 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5460 return PERMISSION_DENIED;
5461 }
5462
Vishnu Nairefc42e22019-12-03 17:36:12 -08005463 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005464 if (sourceCrop.width() <= 0) {
5465 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005466 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005467 }
5468
5469 if (sourceCrop.height() <= 0) {
5470 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005471 crop.bottom = parentSourceBounds.getHeight();
5472 }
5473
5474 if (crop.isEmpty() || frameScale <= 0.0f) {
5475 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5476 // crop was not specified, or an invalid frame scale was provided.
5477 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005478 }
5479 reqWidth = crop.width() * frameScale;
5480 reqHeight = crop.height() * frameScale;
5481
5482 for (const auto& handle : excludeHandles) {
5483 sp<Layer> excludeLayer = fromHandle(handle);
5484 if (excludeLayer != nullptr) {
5485 excludeLayers.emplace(excludeLayer);
5486 } else {
5487 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5488 return NAME_NOT_FOUND;
5489 }
5490 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005491
5492 auto display = getDisplayByLayerStack(parent->getLayerStack());
5493 if (!display) {
5494 return BAD_VALUE;
5495 }
5496
5497 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005498 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005499
Chia-I Wu20261cb2018-08-23 12:55:44 -07005500 // really small crop or frameScale
5501 if (reqWidth <= 0) {
5502 reqWidth = 1;
5503 }
5504 if (reqHeight <= 0) {
5505 reqHeight = 1;
5506 }
5507
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005508 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5509 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005510 auto traverseLayers = [parent, childrenOnly,
5511 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005512 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5513 if (!layer->isVisible()) {
5514 return;
Robert Carr578038f2018-03-09 12:25:24 -08005515 } else if (childrenOnly && layer == parent.get()) {
5516 return;
chaviwa76b2712017-09-20 12:02:26 -07005517 }
Robert Carr866455f2019-04-02 16:28:26 -07005518
5519 sp<Layer> p = layer;
5520 while (p != nullptr) {
5521 if (excludeLayers.count(p) != 0) {
5522 return;
5523 }
5524 p = p->getParent();
5525 }
5526
chaviwa76b2712017-09-20 12:02:26 -07005527 visitor(layer);
5528 });
5529 };
Robert Carr108b2c72019-04-02 16:32:58 -07005530
5531 bool outCapturedSecureLayers = false;
5532 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5533 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005534}
5535
5536status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5537 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005538 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005539 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005540 bool useIdentityTransform,
5541 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005542 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005543
Peiyong Lin0e003c92018-09-17 11:09:51 -07005544 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005545 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5546 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005547 *outBuffer =
5548 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5549 static_cast<android_pixel_format>(reqPixelFormat), 1,
5550 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005551
Robert Carr108b2c72019-04-02 16:32:58 -07005552 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5553 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005554}
5555
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005556status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5557 TraverseLayersFunction traverseLayers,
5558 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005559 bool useIdentityTransform,
5560 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005561 // This mutex protects syncFd and captureResult for communication of the return values from the
5562 // main thread back to this Binder thread
5563 std::mutex captureMutex;
5564 std::condition_variable captureCondition;
5565 std::unique_lock<std::mutex> captureLock(captureMutex);
5566 int syncFd = -1;
5567 std::optional<status_t> captureResult;
5568
Robert Carr03480e22018-01-04 16:02:06 -08005569 const int uid = IPCThreadState::self()->getCallingUid();
5570 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5571
Dominik Laskowski8c001672018-05-30 16:52:06 -07005572 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005573 // If there is a refresh pending, bug out early and tell the binder thread to try again
5574 // after the refresh.
5575 if (mRefreshPending) {
5576 ATRACE_NAME("Skipping screenshot for now");
5577 std::unique_lock<std::mutex> captureLock(captureMutex);
5578 captureResult = std::make_optional<status_t>(EAGAIN);
5579 captureCondition.notify_one();
5580 return;
5581 }
5582
5583 status_t result = NO_ERROR;
5584 int fd = -1;
5585 {
5586 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005587 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005588 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005589 useIdentityTransform, forSystem, &fd,
5590 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005591 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005592 }
5593
5594 {
5595 std::unique_lock<std::mutex> captureLock(captureMutex);
5596 syncFd = fd;
5597 captureResult = std::make_optional<status_t>(result);
5598 captureCondition.notify_one();
5599 }
5600 });
5601
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005602 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005603 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005604 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005605 while (*captureResult == EAGAIN) {
5606 captureResult.reset();
5607 result = postMessageAsync(message);
5608 if (result != NO_ERROR) {
5609 return result;
5610 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005611 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005612 }
5613 result = *captureResult;
5614 }
5615
5616 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005617 sync_wait(syncFd, -1);
5618 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005619 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005620
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005621 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005622}
5623
chaviwa76b2712017-09-20 12:02:26 -07005624void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005625 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005626 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5627 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005628 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005629
chaviwa76b2712017-09-20 12:02:26 -07005630 const auto reqWidth = renderArea.getReqWidth();
5631 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005632 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005633 const auto transform = renderArea.getTransform();
5634 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005635 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005636
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005637 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005638 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005639
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005640 // assume that bounds are never offset, and that they are the same as the
5641 // buffer bounds.
5642 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005643 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005644 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005645
5646 // Now take into account the rotation flag. We append a transform that
5647 // rotates the layer stack about the origin, then translate by buffer
5648 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005649 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005650 int displacementX = 0;
5651 int displacementY = 0;
5652 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5653 switch (rotation) {
5654 case ui::Transform::ROT_90:
5655 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005656 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005657 break;
5658 case ui::Transform::ROT_180:
5659 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005660 displacementY = renderArea.getBounds().getWidth();
5661 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005662 break;
5663 case ui::Transform::ROT_270:
5664 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005665 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005666 break;
5667 default:
5668 break;
5669 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005670
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005671 // We need to transform the clipping window into the right spot.
5672 // First, rotate the clipping rectangle by the rotation hint to get the
5673 // right orientation
5674 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5675 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5676 const vec4 rotClipTL = rotMatrix * clipTL;
5677 const vec4 rotClipBR = rotMatrix * clipBR;
5678 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5679 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5680 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5681 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5682
5683 // Now reposition the clipping rectangle with the displacement vector
5684 // computed above.
5685 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005686 clientCompositionDisplay.clip =
5687 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5688 newClipRight + displacementX, newClipBottom + displacementY);
5689
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005690 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005691 clientCompositionDisplay.globalTransform =
5692 clipTransform * clientCompositionDisplay.globalTransform;
5693
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005694 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5695 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005696
chaviw50da5042018-04-09 13:49:37 -07005697 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005698
Vishnu Nair9b079a22020-01-21 14:36:08 -08005699 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005700 fillLayer.source.buffer.buffer = nullptr;
5701 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5702 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5703 fillLayer.alpha = half(alpha);
5704 clientCompositionLayers.push_back(fillLayer);
5705
5706 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005707 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005708 const bool supportProtectedContent = false;
5709 Region clip(renderArea.getBounds());
5710 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5711 clip,
5712 useIdentityTransform,
5713 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5714 renderArea.isSecure(),
5715 supportProtectedContent,
5716 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005717 displayViewport,
5718 clientCompositionDisplay.outputDataspace,
5719 true, /* realContentIsVisible */
5720 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005721 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005722 std::vector<compositionengine::LayerFE::LayerSettings> results =
5723 layer->prepareClientCompositionList(targetSettings);
5724 clientCompositionLayers.insert(clientCompositionLayers.end(),
5725 std::make_move_iterator(results.begin()),
5726 std::make_move_iterator(results.end()));
5727 results.clear();
5728
chaviwa76b2712017-09-20 12:02:26 -07005729 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005730
Vishnu Nair9b079a22020-01-21 14:36:08 -08005731 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5732 clientCompositionLayers.reserve(clientCompositionLayers.size());
5733 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5734 std::back_inserter(clientCompositionLayerPointers),
5735 [](compositionengine::LayerFE::LayerSettings& settings)
5736 -> renderengine::LayerSettings* { return &settings; });
5737
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005738 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005739 // Use an empty fence for the buffer fence, since we just created the buffer so
5740 // there is no need for synchronization with the GPU.
5741 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005742 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005743 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005744 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005745 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005746
5747 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005748}
5749
chaviwa76b2712017-09-20 12:02:26 -07005750status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5751 TraverseLayersFunction traverseLayers,
5752 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005753 bool useIdentityTransform, bool forSystem,
5754 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005755 ATRACE_CALL();
5756
chaviwa76b2712017-09-20 12:02:26 -07005757 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005758 outCapturedSecureLayers =
5759 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005760 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005761
Robert Carr03480e22018-01-04 16:02:06 -08005762 // We allow the system server to take screenshots of secure layers for
5763 // use in situations like the Screen-rotation animation and place
5764 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005765 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005766 ALOGW("FB is protected: PERMISSION_DENIED");
5767 return PERMISSION_DENIED;
5768 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005769 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005770 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005771}
5772
chaviw95ef3c42019-02-14 10:55:09 -08005773void SurfaceFlinger::setInputWindowsFinished() {
5774 Mutex::Autolock _l(mStateLock);
5775
5776 mPendingSyncInputWindows = false;
5777 mTransactionCV.broadcast();
5778}
chaviw5f21a5e2019-02-14 10:00:34 -08005779
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005780// ---------------------------------------------------------------------------
5781
Edgar Arriaga844fa672020-01-16 14:21:42 -08005782void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5783 layersSortedByZ.traverse(visitor);
5784}
5785
Dan Stoza412903f2017-04-27 13:42:17 -07005786void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5787 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005788}
5789
Dan Stoza412903f2017-04-27 13:42:17 -07005790void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5791 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005792}
5793
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005794void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005795 const LayerVector::Visitor& visitor) {
5796 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005797 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005798 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005799 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005800 continue;
5801 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005802 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005803 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005804 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005805 return;
5806 }
chaviwa76b2712017-09-20 12:02:26 -07005807 if (!layer->isVisible()) {
5808 return;
5809 }
5810 visitor(layer);
5811 });
5812 }
5813}
5814
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005815status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5816 HwcConfigIndexType defaultConfig,
5817 float minRefreshRate,
5818 float maxRefreshRate) {
5819 Mutex::Autolock lock(mStateLock);
5820
Dominik Laskowski22488f62019-03-28 09:53:04 -07005821 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005822 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5823 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5824 // it should go thru setDesiredActiveConfig, similar to primary display.
5825 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5826 const auto displayId = display->getId();
5827 LOG_ALWAYS_FATAL_IF(!displayId);
5828
5829 HWC2::VsyncPeriodChangeConstraints constraints;
5830 constraints.desiredTimeNanos = systemTime();
5831 constraints.seamlessRequired = false;
5832
5833 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005834 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5835 constraints, &timeline) < 0) {
5836 return BAD_VALUE;
5837 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005838 if (timeline.refreshRequired) {
5839 repaintEverythingForHWC();
5840 }
5841
Ady Abrahamdfa37362020-01-21 18:02:39 -08005842 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005843 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005844 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5845 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005846 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005847 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005848 }
5849
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005850 if (mDebugDisplayConfigSetByBackdoor) {
5851 // ignore this request as config is overridden by backdoor
5852 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005853 }
5854
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005855 bool policyChanged;
5856 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5857 &policyChanged) < 0) {
5858 return BAD_VALUE;
5859 }
5860 if (!policyChanged) {
5861 return NO_ERROR;
5862 }
5863
5864 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5865 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005866
5867 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5868 // that listeners that care about a change in allowed configs can get the notification.
5869 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005870 const nsecs_t vsyncPeriod =
5871 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005872 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005873 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005874
Ana Krulec3f6a2062020-01-23 15:48:01 -08005875 auto configId = mScheduler->getPreferredConfigId();
5876 auto preferredRefreshRate = configId
5877 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5878 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5879 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5880 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5881 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5882
5883 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5884 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5885 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005886 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005887 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005888 }
5889
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005890 return NO_ERROR;
5891}
5892
Ana Krulec0782b882019-10-15 17:34:54 -07005893status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005894 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005895 float maxRefreshRate) {
5896 ATRACE_CALL();
5897
5898 if (!displayToken) {
5899 return BAD_VALUE;
5900 }
5901
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005902 status_t result = NO_ERROR;
5903
Ana Krulec234bb162019-11-10 22:55:55 +01005904 postMessageSync(new LambdaMessage([&]() {
5905 const auto display = getDisplayDeviceLocked(displayToken);
5906 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005907 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005908 ALOGE("Attempt to set desired display configs for invalid display token %p",
5909 displayToken.get());
5910 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005911 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005912 ALOGW("Attempt to set desired display configs for virtual display");
5913 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005914 result =
5915 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5916 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005917 }
5918 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005919
5920 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005921}
5922
5923status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005924 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005925 float* outMinRefreshRate,
5926 float* outMaxRefreshRate) {
5927 ATRACE_CALL();
5928
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005929 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005930 return BAD_VALUE;
5931 }
5932
5933 Mutex::Autolock lock(mStateLock);
5934 const auto display = getDisplayDeviceLocked(displayToken);
5935 if (!display) {
5936 return NAME_NOT_FOUND;
5937 }
5938
5939 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005940 HwcConfigIndexType defaultConfig;
5941 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5942 *outDefaultConfig = defaultConfig.value();
5943 return NO_ERROR;
5944 } else if (display->isVirtual()) {
5945 return BAD_VALUE;
5946 } else {
5947 const auto displayId = display->getId();
5948 if (!displayId) {
5949 return BAD_VALUE;
5950 }
5951 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5952 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5953 *outMinRefreshRate = 1e9f / vsyncPeriod;
5954 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5955 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005956 }
Ana Krulec0782b882019-10-15 17:34:54 -07005957}
5958
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005959void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005960 mFlinger->setInputWindowsFinished();
5961}
5962
Robert Carrc0df3122019-04-11 13:18:21 -07005963sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005964 BBinder* b = nullptr;
5965 if (handle) {
5966 b = handle->localBinder();
5967 }
Robert Carrc0df3122019-04-11 13:18:21 -07005968 if (b == nullptr) {
5969 return nullptr;
5970 }
5971 auto it = mLayersByLocalBinderToken.find(b);
5972 if (it != mLayersByLocalBinderToken.end()) {
5973 return it->second.promote();
5974 }
5975 return nullptr;
5976}
5977
Dominik Laskowski75848362019-11-11 17:57:20 -08005978void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005979 mNumLayers++;
5980 mScheduler->registerLayer(layer);
5981}
5982
5983void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5984 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005985 removeFromOffscreenLayers(layer);
5986}
5987
5988// WARNING: ONLY CALL THIS FROM LAYER DTOR
5989// Here we add children in the current state to offscreen layers and remove the
5990// layer itself from the offscreen layer list. Since
5991// this is the dtor, it is safe to access the current state. This keeps us
5992// from dangling children layers such that they are not reachable from the
5993// Drawing state nor the offscreen layer list
5994// See b/141111965
5995void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5996 for (auto& child : layer->getCurrentChildren()) {
5997 mOffscreenLayers.emplace(child.get());
5998 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005999 mOffscreenLayers.erase(layer);
6000}
6001
Alec Mouri4545a8a2019-08-08 20:05:32 -07006002void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6003 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6004}
6005
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006006status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6007 float lightPosY, float lightPosZ,
6008 float lightRadius) {
6009 Mutex::Autolock _l(mStateLock);
6010 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6011 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6012 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6013 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6014 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6015
6016 // these values are overridden when calculating the shadow settings for a layer.
6017 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6018 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006019 return NO_ERROR;
6020}
6021
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006022const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6023 const {
6024 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6025 // on the work to remove the table in that bug rather than adding more to
6026 // it.
6027 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6028 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6029 // supported, and exposed via the
6030 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6031 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6032 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6033 };
6034 return genericLayerMetadataKeyMap;
6035}
6036
Steven Thomas62a4cf82020-01-31 12:04:03 -08006037status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6038 int8_t compatibility) {
6039 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6040 return BAD_VALUE;
6041 }
6042
6043 Mutex::Autolock lock(mStateLock);
6044 if (authenticateSurfaceTextureLocked(surface)) {
6045 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6046 if (layer->setFrameRate(
6047 Layer::FrameRate(frameRate,
6048 Layer::FrameRate::convertCompatibility(compatibility)))) {
6049 setTransactionFlags(eTraversalNeeded);
6050 }
6051 } else {
6052 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6053 return BAD_VALUE;
6054 }
6055 return NO_ERROR;
6056}
6057
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006058} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006059
Mathias Agopian3f844832013-08-07 21:24:32 -07006060#if defined(__gl_h_)
6061#error "don't include gl/gl.h in this file"
6062#endif
6063
6064#if defined(__gl2_h_)
6065#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006066#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006067
6068// TODO(b/129481165): remove the #pragma below and fix conversion issues
6069#pragma clang diagnostic pop // ignored "-Wconversion"