blob: eb624ca73709485d6180aeaac371e1ee2b8951e8 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri989ddbe2020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri989ddbe2020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri989ddbe2020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800104#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
111#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700114#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/EventControlThread.h"
116#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700117#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700118#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700119#include "Scheduler/Scheduler.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800120#include "StartPropertySetThread.h"
121#include "SurfaceFlingerProperties.h"
122#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800123#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700124#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800125#include "android-base/stringprintf.h"
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Steven Thomasb02664d2017-07-26 18:48:28 -0700143namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700144
145#pragma clang diagnostic push
146#pragma clang diagnostic error "-Wswitch-enum"
147
148bool isWideColorMode(const ColorMode colorMode) {
149 switch (colorMode) {
150 case ColorMode::DISPLAY_P3:
151 case ColorMode::ADOBE_RGB:
152 case ColorMode::DCI_P3:
153 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700154 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700155 case ColorMode::BT2100_PQ:
156 case ColorMode::BT2100_HLG:
157 return true;
158 case ColorMode::NATIVE:
159 case ColorMode::STANDARD_BT601_625:
160 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
161 case ColorMode::STANDARD_BT601_525:
162 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
163 case ColorMode::STANDARD_BT709:
164 case ColorMode::SRGB:
165 return false;
166 }
167 return false;
168}
169
170#pragma clang diagnostic pop
171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172class ConditionalLock {
173public:
174 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
175 if (lock) {
176 mMutex.lock();
177 }
178 }
179 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
180private:
181 Mutex& mMutex;
182 bool mLocked;
183};
Peiyong Linfca547f2018-07-09 13:03:33 -0700184
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800185// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
186constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
187
188float getDensityFromProperty(const char* property, bool required) {
189 char value[PROPERTY_VALUE_MAX];
190 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
191 if (!density && required) {
192 ALOGE("%s must be defined as a build property", property);
193 return FALLBACK_DENSITY;
194 }
195 return density / 160.f;
196}
197
Peiyong Lin9d846a52018-11-05 13:18:20 -0800198// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
199bool validateCompositionDataspace(Dataspace dataspace) {
200 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
201}
202
Steven Thomasb02664d2017-07-26 18:48:28 -0700203} // namespace anonymous
204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205// ---------------------------------------------------------------------------
206
Mathias Agopian99b49842011-06-27 16:05:52 -0700207const String16 sHardwareTest("android.permission.HARDWARE_TEST");
208const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
209const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
210const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800211const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700212
213// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700214int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700215bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800217bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800218bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800219int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100220uint32_t SurfaceFlinger::maxGraphicsWidth;
221uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600222bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800223ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700224bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700225bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700226Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
227ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
228Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
229ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800230bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700231
Kalle Raitaa099a242017-01-11 11:17:29 -0800232std::string getHwcServiceName() {
233 char value[PROPERTY_VALUE_MAX] = {};
234 property_get("debug.sf.hwc_service_name", value, "default");
235 ALOGI("Using HWComposer service: '%s'", value);
236 return std::string(value);
237}
238
239bool useTrebleTestingOverride() {
240 char value[PROPERTY_VALUE_MAX] = {};
241 property_get("debug.sf.treble_testing_override", value, "false");
242 ALOGI("Treble testing override: '%s'", value);
243 return std::string(value) == "true";
244}
245
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800246std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
247 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800248 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700249 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800250 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700251 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800252 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700253 return std::string("Enhanced");
254 default:
255 return std::string("Unknown ") +
256 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800258}
259
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700260SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800261
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700262SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
263 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700264 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700265 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700266 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700267 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700268 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800269 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
270 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800271
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700272SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800273 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800274
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800276
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700278
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900279 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700280
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900281 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800282
Steven Thomas050b2c82017-03-06 11:45:16 -0800283 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800287
Brian Lindahla13f2d52020-03-05 11:54:17 +0100288 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
289 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700292
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 mDefaultCompositionDataspace =
296 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700297 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
298 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 defaultCompositionDataspace = mDefaultCompositionDataspace;
300 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
301 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
302 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
303 wideColorGamutCompositionPixelFormat =
304 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700305
Yichi Chenda901bf2019-06-28 14:58:27 +0800306 mColorSpaceAgnosticDataspace =
307 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
308
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800310
Dominik Laskowski718f9602019-11-09 20:01:35 -0800311 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
312 switch (primary_display_orientation(Values::ORIENTATION_0)) {
313 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800314 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800315 case Values::ORIENTATION_90:
316 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800317 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800318 case Values::ORIENTATION_180:
319 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800320 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800321 case Values::ORIENTATION_270:
322 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800323 break;
324 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800325 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800326
Sundong Ahn85131bd2019-02-18 15:51:53 +0900327 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800328
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800329 // debugging stuff...
330 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700331
Mathias Agopianb4b17302013-03-20 18:36:41 -0700332 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700333 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700334
Alec Mouri989ddbe2020-02-06 09:26:19 -0800335 property_get("ro.build.type", value, "user");
336 mIsUserBuild = strcmp(value, "user") == 0;
337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 property_get("debug.sf.showupdates", value, "0");
339 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700340
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700341 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000342
343 // DDMS debugging deprecated (b/120782499)
344 property_get("debug.sf.ddms", value, "0");
345 int debugDdms = atoi(value);
346 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700347
348 property_get("debug.sf.disable_backpressure", value, "0");
349 mPropagateBackpressure = !atoi(value);
350 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700351
Ady Abrahamadb9a992019-09-19 21:21:55 +0000352 property_get("debug.sf.enable_gl_backpressure", value, "0");
353 mPropagateBackpressureClientComposition = atoi(value);
354 ALOGI_IF(mPropagateBackpressureClientComposition,
355 "Enabling backpressure propagation for Client Composition");
356
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800357 property_get("debug.sf.enable_hwc_vds", value, "0");
358 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800359 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800360
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800361 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800362 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800363 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700364
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800365 property_get("ro.surface_flinger.supports_background_blur", value, "0");
366 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700367 mSupportsBlur = supportsBlurs;
368 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800369 property_get("ro.sf.blurs_are_expensive", value, "0");
370 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800371
Ady Abraham0a525092020-03-03 12:51:24 -0800372 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700373 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
374 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
375
Dan Stozaec460082018-12-17 15:35:09 -0800376 property_get("debug.sf.luma_sampling", value, "1");
377 mLumaSampling = atoi(value);
378
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800379 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800380 mDisableClientCompositionCache = atoi(value);
381
Romain Guy11d63f42017-07-20 12:47:14 -0700382 // We should be reading 'persist.sys.sf.color_saturation' here
383 // but since /data may be encrypted, we need to wait until after vold
384 // comes online to attempt to read the property. The property is
385 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800386
387 if (useTrebleTestingOverride()) {
388 // Without the override SurfaceFlinger cannot connect to HIDL
389 // services that are not listed in the manifests. Considered
390 // deriving the setting from the set service name, but it
391 // would be brittle if the name that's not 'default' is used
392 // for production purposes later on.
393 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
394 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800395
396 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800397}
398
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800399void SurfaceFlinger::onFirstRef()
400{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800401 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800402}
403
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700404SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405
Dan Stozac7014012014-02-14 15:03:43 -0800406void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800407{
408 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700409 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410
Andy McFadden13a082e2012-08-24 10:16:42 -0700411 // restore initial conditions (default device unblank, etc)
412 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413
414 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700415 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416}
417
Robert Carr1db73f62016-12-21 12:58:51 -0800418static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700419 status_t err = client->initCheck();
420 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800421 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800422 }
Robert Carr1db73f62016-12-21 12:58:51 -0800423 return nullptr;
424}
425
426sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
427 return initClient(new Client(this));
428}
429
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700430sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
431 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700432{
433 class DisplayToken : public BBinder {
434 sp<SurfaceFlinger> flinger;
435 virtual ~DisplayToken() {
436 // no more references, this display must be terminated
437 Mutex::Autolock _l(flinger->mStateLock);
438 flinger->mCurrentState.displays.removeItem(this);
439 flinger->setTransactionFlags(eDisplayTransactionNeeded);
440 }
441 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700442 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700443 : flinger(flinger) {
444 }
445 };
446
447 sp<BBinder> token = new DisplayToken(this);
448
449 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700450 // Display ID is assigned when virtual display is allocated by HWC.
451 DisplayDeviceState state;
452 state.isSecure = secure;
453 state.displayName = displayName;
454 mCurrentState.displays.add(token, state);
455 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700456 return token;
457}
458
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700459void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700460 Mutex::Autolock _l(mStateLock);
461
Dominik Laskowski075d3172018-05-24 15:50:06 -0700462 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
463 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700464 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700465 return;
466 }
467
Dominik Laskowski075d3172018-05-24 15:50:06 -0700468 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
469 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700470 ALOGE("destroyDisplay called for non-virtual display");
471 return;
472 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700473 mInterceptor->saveDisplayDeletion(state.sequenceId);
474 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700475 setTransactionFlags(eDisplayTransactionNeeded);
476}
477
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800478std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
479 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800481 const auto internalDisplayId = getInternalDisplayIdLocked();
482 if (!internalDisplayId) {
483 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700484 }
485
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800486 std::vector<PhysicalDisplayId> displayIds;
487 displayIds.reserve(mPhysicalDisplayTokens.size());
488 displayIds.push_back(internalDisplayId->value);
489
490 for (const auto& [id, token] : mPhysicalDisplayTokens) {
491 if (id != *internalDisplayId) {
492 displayIds.push_back(id.value);
493 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700494 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700495
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800496 return displayIds;
497}
498
499sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
500 Mutex::Autolock lock(mStateLock);
501 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700502}
503
Ady Abraham37965d42018-11-01 13:43:32 -0700504status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
505 if (!outGetColorManagement) {
506 return BAD_VALUE;
507 }
508 *outGetColorManagement = useColorManagement;
509 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700510}
511
Lloyd Pique441d5042018-10-18 16:49:51 -0700512HWComposer& SurfaceFlinger::getHwComposer() const {
513 return mCompositionEngine->getHwComposer();
514}
515
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700516renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
517 return mCompositionEngine->getRenderEngine();
518}
519
Lloyd Pique70d91362018-10-18 16:02:55 -0700520compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
521 return *mCompositionEngine.get();
522}
523
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800524void SurfaceFlinger::bootFinished()
525{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700526 if (mBootFinished == true) {
527 ALOGE("Extra call to bootFinished");
528 return;
529 }
530 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700531 if (mStartPropertySetThread->join() != NO_ERROR) {
532 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800533 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800534 const nsecs_t now = systemTime();
535 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000536 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700537
Mikael Pessa90092f42019-08-26 17:22:04 -0700538 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000539 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700540
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700541 // wait patiently for the window manager death
542 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700543 mWindowManager = defaultServiceManager()->getService(name);
544 if (mWindowManager != 0) {
545 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546 }
Robert Carr720e5062018-07-30 17:45:14 -0700547 sp<IBinder> input(defaultServiceManager()->getService(
548 String16("inputflinger")));
549 if (input == nullptr) {
550 ALOGE("Failed to link to input service");
551 } else {
552 mInputFlinger = interface_cast<IInputFlinger>(input);
553 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700554
Steven Thomas050b2c82017-03-06 11:45:16 -0800555 if (mVrFlinger) {
556 mVrFlinger->OnBootFinished();
557 }
558
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700559 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700560 // formerly we would just kill the process, but we now ask it to exit so it
561 // can choose where to stop the animation.
562 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700563
564 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
565 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
566 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700567
Ana Krulecbd6654b2019-02-15 15:18:15 -0800568 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800569 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700570 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800571 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800572
Ady Abraham8a82ba62020-01-17 12:43:17 -0800573 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
574 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
575 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
576 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800577 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800578}
579
Dan Stoza436ccf32018-06-21 12:10:12 -0700580uint32_t SurfaceFlinger::getNewTexture() {
581 {
582 std::lock_guard lock(mTexturePoolMutex);
583 if (!mTexturePool.empty()) {
584 uint32_t name = mTexturePool.back();
585 mTexturePool.pop_back();
586 ATRACE_INT("TexturePoolSize", mTexturePool.size());
587 return name;
588 }
589
590 // The pool was too small, so increase it for the future
591 ++mTexturePoolSize;
592 }
593
594 // The pool was empty, so we need to get a new texture name directly using a
595 // blocking call to the main thread
596 uint32_t name = 0;
597 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
598 return name;
599}
600
Mathias Agopian3f844832013-08-07 21:24:32 -0700601void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700602 std::lock_guard lock(mTexturePoolMutex);
603 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
604 // to actually delete this or not based on mTexturePoolSize
605 mTexturePool.push_back(texture);
606 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700607}
608
Wei Wangf9b05ee2017-07-19 20:59:39 -0700609// Do not call property_set on main thread which will be blocked by init
610// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700611void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700612 ALOGI( "SurfaceFlinger's main thread ready to run. "
613 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700614 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800615
Steven Thomasb02664d2017-07-26 18:48:28 -0700616 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700617 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800618 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700619 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
620 renderengine::RenderEngineCreationArgs::Builder()
621 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
622 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
623 .setUseColorManagerment(useColorManagement)
624 .setEnableProtectedContext(enable_protected_contents(false))
625 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700626 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700627 .setContextPriority(useContextPriority
628 ? renderengine::RenderEngine::ContextPriority::HIGH
629 : renderengine::RenderEngine::ContextPriority::MEDIUM)
630 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800631 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700632
633 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
634 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700635 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800636 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800637 // Process any initial hotplug and resulting display changes.
638 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700639 const auto display = getDefaultDisplayDeviceLocked();
640 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700641 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700642 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800643
Steven Thomas050b2c82017-03-06 11:45:16 -0800644 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700645 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700646 // This callback is called from the vr flinger dispatch thread. We
647 // need to call signalTransaction(), which requires holding
648 // mStateLock when we're not on the main thread. Acquiring
649 // mStateLock from the vr flinger dispatch thread might trigger a
650 // deadlock in surface flinger (see b/66916578), so post a message
651 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700652 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700653 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
654 mVrFlingerRequestsDisplay = requestDisplay;
655 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700656 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800657 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700658 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
659 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700660 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700661 .value_or(0),
662 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800663 if (!mVrFlinger) {
664 ALOGE("Failed to start vrflinger");
665 }
666 }
667
Mathias Agopian92a979a2012-08-02 18:32:23 -0700668 // initialize our drawing state
669 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700670
Andy McFadden13a082e2012-08-24 10:16:42 -0700671 // set initial conditions (e.g. unblank default device)
672 initializeDisplays();
673
Steven Thomas137d4bc2019-07-25 16:55:14 -0700674 char primeShaderCache[PROPERTY_VALUE_MAX];
675 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
676 if (atoi(primeShaderCache)) {
677 getRenderEngine().primeCache();
678 }
Dan Stoza4e637772016-07-28 13:31:51 -0700679
Wei Wangf9b05ee2017-07-19 20:59:39 -0700680 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700681
682 const bool presentFenceReliable =
683 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
684 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700685
686 if (mStartPropertySetThread->Start() != NO_ERROR) {
687 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800688 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800689
Dan Stoza9e56aa02015-11-02 13:00:03 -0800690 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700691}
692
Romain Guy11d63f42017-07-20 12:47:14 -0700693void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700694 Mutex::Autolock _l(mStateLock);
695
Romain Guy11d63f42017-07-20 12:47:14 -0700696 char value[PROPERTY_VALUE_MAX];
697
698 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800699 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700700 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800701 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100702
703 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700704 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800705
706 property_get("persist.sys.sf.color_mode", value, "0");
707 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700708
709 property_get("persist.sys.sf.disable_blurs", value, "0");
710 bool disableBlurs = atoi(value);
711 mDisableBlurs = disableBlurs;
712 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700713}
714
Mathias Agopiana67e4182012-06-19 17:26:12 -0700715void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800716 // Start boot animation service by setting a property mailbox
717 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700718 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800719 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700720 if (mStartPropertySetThread->join() != NO_ERROR) {
721 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800722 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700723}
724
Mathias Agopian875d8e12013-06-07 15:35:48 -0700725size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700726 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700727}
728
Mathias Agopian875d8e12013-06-07 15:35:48 -0700729size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700730 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700731}
732
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800733// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800734
Jamie Gennis582270d2011-08-17 18:19:00 -0700735bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800736 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800737 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800738 return authenticateSurfaceTextureLocked(bufferProducer);
739}
740
741bool SurfaceFlinger::authenticateSurfaceTextureLocked(
742 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800743 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800744 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800745}
746
Brian Anderson6b376712017-04-04 10:51:39 -0700747status_t SurfaceFlinger::getSupportedFrameTimestamps(
748 std::vector<FrameEvent>* outSupported) const {
749 *outSupported = {
750 FrameEvent::REQUESTED_PRESENT,
751 FrameEvent::ACQUIRE,
752 FrameEvent::LATCH,
753 FrameEvent::FIRST_REFRESH_START,
754 FrameEvent::LAST_REFRESH_START,
755 FrameEvent::GPU_COMPOSITION_DONE,
756 FrameEvent::DEQUEUE_READY,
757 FrameEvent::RELEASE,
758 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700759 ConditionalLock _l(mStateLock,
760 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700761 if (!getHwComposer().hasCapability(
762 HWC2::Capability::PresentFenceIsNotReliable)) {
763 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
764 }
765 return NO_ERROR;
766}
767
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800768status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
769 if (!displayToken || !state) {
770 return BAD_VALUE;
771 }
772
773 Mutex::Autolock lock(mStateLock);
774
775 const auto display = getDisplayDeviceLocked(displayToken);
776 if (!display) {
777 return NAME_NOT_FOUND;
778 }
779
780 state->layerStack = display->getLayerStack();
781 state->orientation = display->getOrientation();
782
783 const Rect viewport = display->getViewport();
784 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
785
786 return NO_ERROR;
787}
788
789status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
790 if (!displayToken || !info) {
791 return BAD_VALUE;
792 }
793
794 Mutex::Autolock lock(mStateLock);
795
796 const auto display = getDisplayDeviceLocked(displayToken);
797 if (!display) {
798 return NAME_NOT_FOUND;
799 }
800
Dominik Laskowski55c85402020-01-21 16:25:47 -0800801 if (const auto connectionType = display->getConnectionType())
802 info->connectionType = *connectionType;
803 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800804 return INVALID_OPERATION;
805 }
806
807 if (mEmulatedDisplayDensity) {
808 info->density = mEmulatedDisplayDensity;
809 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800810 info->density = info->connectionType == DisplayConnectionType::Internal
811 ? mInternalDisplayDensity
812 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800813 }
814
815 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200816 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800817
818 return NO_ERROR;
819}
820
Dominik Laskowski22488f62019-03-28 09:53:04 -0700821status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800822 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700823 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700824 return BAD_VALUE;
825 }
826
Dominik Laskowski22488f62019-03-28 09:53:04 -0700827 Mutex::Autolock lock(mStateLock);
828
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800829 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700830 if (!displayId) {
831 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700832 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700833
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800834 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700835
Dan Stoza7f7da322014-05-02 15:26:25 -0700836 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700837
Dominik Laskowski075d3172018-05-24 15:50:06 -0700838 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800839 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700840
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800841 auto width = hwConfig->getWidth();
842 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700843
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800844 auto xDpi = hwConfig->getDpiX();
845 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700846
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800847 if (isInternal &&
848 (internalDisplayOrientation == ui::ROTATION_90 ||
849 internalDisplayOrientation == ui::ROTATION_270)) {
850 std::swap(width, height);
851 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700852 }
853
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800854 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800855
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800856 if (mEmulatedDisplayDensity) {
857 config.xDpi = mEmulatedDisplayDensity;
858 config.yDpi = mEmulatedDisplayDensity;
859 } else {
860 config.xDpi = xDpi;
861 config.yDpi = yDpi;
862 }
863
864 const nsecs_t period = hwConfig->getVsyncPeriod();
865 config.refreshRate = 1e9f / period;
866
867 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
868 config.appVsyncOffset = offsets.late.app;
869 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800870 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800871
Andy McFadden91b2ca82014-06-13 14:04:23 -0700872 // This is how far in advance a buffer must be queued for
873 // presentation at a given time. If you want a buffer to appear
874 // on the screen at time N, you must submit the buffer before
875 // (N - presentationDeadline).
876 //
877 // Normally it's one full refresh period (to give SF a chance to
878 // latch the buffer), but this can be reduced by configuring a
879 // DispSync offset. Any additional delays introduced by the hardware
880 // composer or panel must be accounted for here.
881 //
882 // We add an additional 1ms to allow for processing time and
883 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800884 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700885
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800886 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700887 }
888
Dan Stoza7f7da322014-05-02 15:26:25 -0700889 return NO_ERROR;
890}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700891
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700892status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
893 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700894 return BAD_VALUE;
895 }
896
Ana Krulecc2870422019-01-29 19:00:58 -0800897 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700898 return NO_ERROR;
899}
900
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700901int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
902 const auto display = getDisplayDevice(displayToken);
903 if (!display) {
904 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800905 return BAD_VALUE;
906 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700907
Steven Thomasc9098452019-09-30 17:15:05 -0700908 if (display->isPrimary()) {
909 std::lock_guard<std::mutex> lock(mActiveConfigLock);
910 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800911 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700912 }
Steven Thomasc9098452019-09-30 17:15:05 -0700913 }
Ady Abraham2139f732019-11-13 18:56:40 -0800914
915 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700916}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700917
Ady Abraham03b02dd2019-03-21 15:40:11 -0700918void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800919 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800920 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abraham2139f732019-11-13 18:56:40 -0800921 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800922
Ady Abrahamb838aed2019-02-12 15:30:16 -0800923 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800924 if (mDesiredActiveConfigChanged) {
925 // If a config change is pending, just cache the latest request in
926 // mDesiredActiveConfig
927 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
928 mDesiredActiveConfig = info;
929 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
930 } else {
931 // Check is we are already at the desired config
932 const auto display = getDefaultDisplayDeviceLocked();
933 if (!display || display->getActiveConfig() == refreshRate.configId) {
934 return;
935 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800936
Ady Abraham59db0a32020-03-02 18:04:20 -0800937 // Initiate a config change.
938 mDesiredActiveConfigChanged = true;
939 mDesiredActiveConfig = info;
940
Ady Abrahamb838aed2019-02-12 15:30:16 -0800941 // This will trigger HWC refresh without resetting the idle timer.
942 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700943 // Start receiving vsync samples now, so that we can detect a period
944 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800945 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700946 // As we called to set period, we will call to onRefreshRateChangeCompleted once
947 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700948 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800949
Ady Abraham9e16a482019-12-03 17:19:41 -0800950 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
951 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800952 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700953
954 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800955 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700956 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800957}
958
959status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
960 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800961
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100962 if (!displayToken) {
963 return BAD_VALUE;
964 }
Ady Abraham838de062019-02-04 10:24:03 -0800965
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100966 status_t result = NO_ERROR;
967
968 postMessageSync(new LambdaMessage([&]() {
969 const auto display = getDisplayDeviceLocked(displayToken);
970 if (!display) {
971 ALOGE("Attempt to set allowed display configs for invalid display token %p",
972 displayToken.get());
973 result = BAD_VALUE;
974 } else if (display->isVirtual()) {
975 ALOGW("Attempt to set allowed display configs for virtual display");
976 result = BAD_VALUE;
977 } else {
978 HwcConfigIndexType config(mode);
979 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
980 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
981 refreshRate.fps);
982 }
983 }));
984
985 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800986}
987
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800988void SurfaceFlinger::setActiveConfigInternal() {
989 ATRACE_CALL();
990
Dominik Laskowski22488f62019-03-28 09:53:04 -0700991 const auto display = getDefaultDisplayDeviceLocked();
992 if (!display) {
993 return;
994 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800995
Alec Mouri8de697e2020-03-19 10:52:01 -0700996 auto& oldRefreshRate =
997 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
998
Dominik Laskowski22488f62019-03-28 09:53:04 -0700999 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001000 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001001 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001002 display->setActiveConfig(mUpcomingActiveConfig.configId);
1003
Ady Abraham2e1dd892020-03-05 13:48:36 -08001004 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001005 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Alec Mouri8de697e2020-03-19 10:52:01 -07001006 if (refreshRate.vsyncPeriod != oldRefreshRate.vsyncPeriod) {
1007 mTimeStats->incrementRefreshRateSwitches();
1008 }
Ady Abraham9e16a482019-12-03 17:19:41 -08001009 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1010 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -08001011 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001012
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001013 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001014 const nsecs_t vsyncPeriod =
1015 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
1016 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -08001017 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001018 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001019 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001020}
1021
Ady Abraham53852a52019-05-28 18:07:44 -07001022void SurfaceFlinger::desiredActiveConfigChangeDone() {
1023 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1024 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1025 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001026
Ady Abraham2e1dd892020-03-05 13:48:36 -08001027 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001028 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001029 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001030 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1031 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001032}
1033
Dominik Laskowski22488f62019-03-28 09:53:04 -07001034bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001035 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001036 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001037 if (mCheckPendingFence) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001038 if (previousFramePending()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001039 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001040 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001041 return true;
1042 }
1043
1044 // We received the present fence from the HWC, so we assume it successfully updated
1045 // the config, hence we update SF.
1046 mCheckPendingFence = false;
1047 setActiveConfigInternal();
1048 }
1049
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001050 // Store the local variable to release the lock.
1051 ActiveConfigInfo desiredActiveConfig;
1052 {
1053 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001054 if (!mDesiredActiveConfigChanged) {
1055 return false;
1056 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001057 desiredActiveConfig = mDesiredActiveConfig;
1058 }
1059
Ady Abraham2e1dd892020-03-05 13:48:36 -08001060 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001061 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1062 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1063 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001064 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001065 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1066 // display is not valid or we are already in the requested mode
1067 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001068 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001069 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001070 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001071
Ady Abraham838de062019-02-04 10:24:03 -08001072 // Desired active config was set, it is different than the config currently in use, however
1073 // allowed configs might have change by the time we process the refresh.
1074 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001075 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001076 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001077 return false;
1078 }
Alec Mouri7f015182019-07-11 13:56:22 -07001079
Ady Abrahamb838aed2019-02-12 15:30:16 -08001080 mUpcomingActiveConfig = desiredActiveConfig;
1081 const auto displayId = display->getId();
1082 LOG_ALWAYS_FATAL_IF(!displayId);
1083
Ady Abraham2139f732019-11-13 18:56:40 -08001084 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001085
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001086 // TODO(b/142753666) use constrains
1087 HWC2::VsyncPeriodChangeConstraints constraints;
1088 constraints.desiredTimeNanos = systemTime();
1089 constraints.seamlessRequired = false;
1090
1091 HWC2::VsyncPeriodChangeTimeline outTimeline;
1092 auto status =
1093 getHwComposer().setActiveConfigWithConstraints(*displayId,
1094 mUpcomingActiveConfig.configId.value(),
1095 constraints, &outTimeline);
1096 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001097 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1098 // to be sent. We just log the error in this case.
1099 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001100 return false;
1101 }
1102
1103 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1104 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001105 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001106 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001107}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001108
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001109status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1110 Vector<ColorMode>* outColorModes) {
1111 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001112 return BAD_VALUE;
1113 }
1114
Peiyong Lina52f0292018-03-14 17:26:31 -07001115 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001116 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001117 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001118 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1119
1120 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1121 if (!displayId) {
1122 return NAME_NOT_FOUND;
1123 }
1124
Dominik Laskowski075d3172018-05-24 15:50:06 -07001125 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001126 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001127 }
Michael Wright28f24d02016-07-12 13:30:53 -07001128 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001129
1130 // If it's built-in display and the configuration claims it's not wide color capable,
1131 // filter out all wide color modes. The typical reason why this happens is that the
1132 // hardware is not good enough to support GPU composition of wide color, and thus the
1133 // OEMs choose to disable this capability.
1134 if (isInternalDisplay && !hasWideColorDisplay) {
1135 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1136 isWideColorMode);
1137 } else {
1138 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1139 }
Michael Wright28f24d02016-07-12 13:30:53 -07001140
1141 return NO_ERROR;
1142}
1143
Daniel Solomon42d04562019-01-20 21:03:19 -08001144status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1145 ui::DisplayPrimaries &primaries) {
1146 if (!displayToken) {
1147 return BAD_VALUE;
1148 }
1149
1150 // Currently we only support this API for a single internal display.
1151 if (getInternalDisplayToken() != displayToken) {
1152 return BAD_VALUE;
1153 }
1154
1155 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1156 return NO_ERROR;
1157}
1158
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001159ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1160 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001161 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001162 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001163 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001164}
1165
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001166status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001167 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001168 Vector<ColorMode> modes;
1169 getDisplayColorModes(displayToken, &modes);
1170 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1171 if (mode < ColorMode::NATIVE || !exists) {
1172 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1173 decodeColorMode(mode).c_str(), mode, displayToken.get());
1174 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001175 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001176 const auto display = getDisplayDevice(displayToken);
1177 if (!display) {
1178 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1179 decodeColorMode(mode).c_str(), mode, displayToken.get());
1180 } else if (display->isVirtual()) {
1181 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1182 decodeColorMode(mode).c_str(), mode);
1183 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001184 display->getCompositionDisplay()->setColorProfile(
1185 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1186 RenderIntent::COLORIMETRIC,
1187 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001188 }
1189 }));
1190
Michael Wright28f24d02016-07-12 13:30:53 -07001191 return NO_ERROR;
1192}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001193
Galia Peycheva5492cb52019-10-30 14:13:16 +01001194status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1195 bool* outSupport) const {
1196 Mutex::Autolock _l(mStateLock);
1197
1198 if (!displayToken) {
1199 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1200 return BAD_VALUE;
1201 }
1202 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1203 if (!displayId) {
1204 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1205 displayToken.get());
1206 return NAME_NOT_FOUND;
1207 }
1208 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1209 HWC2::DisplayCapability::AutoLowLatencyMode);
1210 return NO_ERROR;
1211}
1212
1213void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1214 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1215}
1216
1217void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1218 if (!displayToken) {
1219 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1220 return;
1221 }
1222 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1223 if (!displayId) {
1224 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1225 displayToken.get());
1226 return;
1227 }
1228
1229 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1230}
1231
1232status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1233 bool* outSupport) const {
1234 Mutex::Autolock _l(mStateLock);
1235
1236 if (!displayToken) {
1237 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1238 return BAD_VALUE;
1239 }
1240 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1241 if (!displayId) {
1242 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1243 displayToken.get());
1244 return NAME_NOT_FOUND;
1245 }
1246
1247 std::vector<HWC2::ContentType> outSupportedContentTypes;
1248 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1249 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1250 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1251 return NO_ERROR;
1252}
1253
1254void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1255 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1256}
1257
1258void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1259 if (!displayToken) {
1260 ALOGE("setGameContentType() failed. Missing display token.");
1261 return;
1262 }
1263 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1264 if (!displayId) {
1265 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1266 displayToken.get());
1267 return;
1268 }
1269
1270 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1271 getHwComposer().setContentType(*displayId, type);
1272}
1273
Svetoslavd85084b2014-03-20 10:28:31 -07001274status_t SurfaceFlinger::clearAnimationFrameStats() {
1275 Mutex::Autolock _l(mStateLock);
1276 mAnimFrameTracker.clearStats();
1277 return NO_ERROR;
1278}
1279
1280status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1281 Mutex::Autolock _l(mStateLock);
1282 mAnimFrameTracker.getStats(outStats);
1283 return NO_ERROR;
1284}
1285
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001286status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1287 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001288 Mutex::Autolock _l(mStateLock);
1289
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001290 const auto display = getDisplayDeviceLocked(displayToken);
1291 if (!display) {
1292 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001293 return BAD_VALUE;
1294 }
1295
Peiyong Linfb069302018-04-25 14:34:31 -07001296 // At this point the DisplayDeivce should already be set up,
1297 // meaning the luminance information is already queried from
1298 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001299 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001300 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1301 capabilities.getDesiredMaxLuminance(),
1302 capabilities.getDesiredMaxAverageLuminance(),
1303 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001304
1305 return NO_ERROR;
1306}
1307
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001308std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1309 const DisplayDevice& display) const {
1310 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1311 // avoid repetitive HAL IPC and EDID parsing.
1312 const auto displayId = display.getId();
1313 LOG_FATAL_IF(!displayId);
1314
1315 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1316 LOG_FATAL_IF(!hwcDisplayId);
1317
1318 uint8_t port;
1319 DisplayIdentificationData data;
1320 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1321 ALOGV("%s: No identification data.", __FUNCTION__);
1322 return {};
1323 }
1324
1325 const auto info = parseDisplayIdentificationData(port, data);
1326 if (!info) {
1327 return {};
1328 }
1329 return info->deviceProductInfo;
1330}
1331
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001332status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1333 ui::PixelFormat* outFormat,
1334 ui::Dataspace* outDataspace,
1335 uint8_t* outComponentMask) const {
1336 if (!outFormat || !outDataspace || !outComponentMask) {
1337 return BAD_VALUE;
1338 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001339 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001340 if (!display || !display->getId()) {
1341 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1342 return BAD_VALUE;
1343 }
1344 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1345 outDataspace, outComponentMask);
1346}
1347
Kevin DuBois74e53772018-11-19 10:52:38 -08001348status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1349 bool enable, uint8_t componentMask,
1350 uint64_t maxFrames) const {
1351 const auto display = getDisplayDevice(displayToken);
1352 if (!display || !display->getId()) {
1353 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1354 return BAD_VALUE;
1355 }
1356
1357 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1358 componentMask, maxFrames);
1359}
1360
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001361status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1362 uint64_t maxFrames, uint64_t timestamp,
1363 DisplayedFrameStats* outStats) const {
1364 const auto display = getDisplayDevice(displayToken);
1365 if (!display || !display->getId()) {
1366 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1367 return BAD_VALUE;
1368 }
1369
1370 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1371 outStats);
1372}
1373
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001374status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1375 if (!outSupported) {
1376 return BAD_VALUE;
1377 }
1378 *outSupported = getRenderEngine().supportsProtectedContent();
1379 return NO_ERROR;
1380}
1381
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001382status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1383 bool* outIsWideColorDisplay) const {
1384 if (!displayToken || !outIsWideColorDisplay) {
1385 return BAD_VALUE;
1386 }
1387 Mutex::Autolock _l(mStateLock);
1388 const auto display = getDisplayDeviceLocked(displayToken);
1389 if (!display) {
1390 return BAD_VALUE;
1391 }
Peiyong Linff84a152019-05-17 18:36:19 -07001392
1393 // Use hasWideColorDisplay to override built-in display.
1394 const auto displayId = display->getId();
1395 if (displayId && displayId == getInternalDisplayIdLocked()) {
1396 *outIsWideColorDisplay = hasWideColorDisplay;
1397 return NO_ERROR;
1398 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001399 *outIsWideColorDisplay = display->hasWideColorGamut();
1400 return NO_ERROR;
1401}
1402
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001403status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001404 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001405 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001406
Dominik Laskowski6505f792019-09-18 11:10:05 -07001407 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1408 mEventQueue->setEventConnection(
1409 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001410 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001411 }));
1412
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001413 return NO_ERROR;
1414}
1415
1416status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001417 Mutex::Autolock lock(mStateLock);
1418 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001419}
1420
Lloyd Pique755e3192018-01-31 16:46:15 -08001421status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1422 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001423 // Try to acquire a lock for 1s, fail gracefully
1424 const status_t err = mStateLock.timedLock(s2ns(1));
1425 const bool locked = (err == NO_ERROR);
1426 if (!locked) {
1427 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1428 return TIMED_OUT;
1429 }
1430
1431 outLayers->clear();
1432 mCurrentState.traverseInZOrder([&](Layer* layer) {
1433 outLayers->push_back(layer->getLayerDebugInfo());
1434 });
1435
1436 mStateLock.unlock();
1437 return NO_ERROR;
1438}
1439
Peiyong Linc6780972018-10-28 15:24:08 -07001440status_t SurfaceFlinger::getCompositionPreference(
1441 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1442 Dataspace* outWideColorGamutDataspace,
1443 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001444 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001445 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001446 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001447 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001448 return NO_ERROR;
1449}
1450
Dan Stozaec460082018-12-17 15:35:09 -08001451status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1452 const sp<IBinder>& stopLayerHandle,
1453 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001454 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001455 return BAD_VALUE;
1456 }
1457 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001458 return NO_ERROR;
1459}
1460
Dan Stozaec460082018-12-17 15:35:09 -08001461status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001462 if (!listener) {
1463 return BAD_VALUE;
1464 }
Dan Stozaec460082018-12-17 15:35:09 -08001465 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001466 return NO_ERROR;
1467}
Dan Gittik57e63c52019-01-18 16:37:54 +00001468
1469status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1470 bool* outSupport) const {
1471 if (!displayToken || !outSupport) {
1472 return BAD_VALUE;
1473 }
1474 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1475 if (!displayId) {
1476 return NAME_NOT_FOUND;
1477 }
1478 *outSupport =
1479 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1480 return NO_ERROR;
1481}
1482
1483status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1484 float brightness) const {
1485 if (!displayToken) {
1486 return BAD_VALUE;
1487 }
1488 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1489 if (!displayId) {
1490 return NAME_NOT_FOUND;
1491 }
1492 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1493}
1494
Ady Abraham8532d012019-05-08 14:50:56 -07001495status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1496 PowerHint powerHint = static_cast<PowerHint>(hintId);
1497
1498 if (powerHint == PowerHint::INTERACTION) {
1499 mScheduler->notifyTouchEvent();
1500 }
1501
1502 return NO_ERROR;
1503}
1504
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001505// ----------------------------------------------------------------------------
1506
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001507sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001508 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001509 const auto& handle =
1510 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001511
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001512 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001513}
1514
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001515// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001516
1517void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001518 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001519}
1520
1521void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001522 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001523 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001524 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001525}
1526
1527void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001528 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001529 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001530 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001531}
1532
1533void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001534 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001535 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001536}
1537
1538status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001539 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001540 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001541}
1542
1543status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001544 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001545 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001546 if (res == NO_ERROR) {
1547 msg->wait();
1548 }
1549 return res;
1550}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001551
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001552void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001553 do {
1554 waitForEvent();
1555 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001556}
1557
Dominik Laskowski83b88212018-12-11 13:34:06 -08001558nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001559 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001560 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1561 return 0;
1562 }
1563
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001564 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001565}
1566
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001567void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001568 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001569 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001570 ATRACE_NAME("SF onVsync");
1571
Steven Thomas3cfac282017-02-06 12:29:30 -08001572 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001573 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001574 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001575 return;
1576 }
1577
Dominik Laskowski075d3172018-05-24 15:50:06 -07001578 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001579 return;
1580 }
1581
Dominik Laskowski075d3172018-05-24 15:50:06 -07001582 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001583 // For now, we don't do anything with external display vsyncs.
1584 return;
1585 }
1586
Alec Mourif8e689c2019-05-20 18:32:22 -07001587 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001588 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001589 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001590 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001591 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001592}
1593
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001594void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001595 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1596 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001597}
1598
Ady Abraham2139f732019-11-13 18:56:40 -08001599bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001600 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001601}
1602
Ady Abraham2139f732019-11-13 18:56:40 -08001603void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1604 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001605 const auto display = getDefaultDisplayDeviceLocked();
1606 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001607 return;
1608 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001609 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001610
Ana Krulec7d1d6832018-12-27 11:10:09 -08001611 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001612 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1613 ALOGV("Skipping config %d as it is not part of allowed configs",
1614 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001615 return;
1616 }
1617
Ady Abraham2139f732019-11-13 18:56:40 -08001618 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001619}
1620
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001621void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001622 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001623 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001624 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001625
Lloyd Piqueba04e622017-12-14 17:11:26 -08001626 // Ignore events that do not have the right sequenceId.
1627 if (sequenceId != getBE().mComposerSequenceId) {
1628 return;
1629 }
1630
Steven Thomasb02664d2017-07-26 18:48:28 -07001631 // Only lock if we're not on the main thread. This function is normally
1632 // called on a hwbinder thread, but for the primary display it's called on
1633 // the main thread with the state lock already held, so don't attempt to
1634 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001635 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001636
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001637 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001638
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001639 if (std::this_thread::get_id() == mMainThreadId) {
1640 // Process all pending hot plug events immediately if we are on the main thread.
1641 processDisplayHotplugEventsLocked();
1642 }
1643
Lloyd Piqueba04e622017-12-14 17:11:26 -08001644 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001645}
1646
Ady Abraham7159f572019-10-11 11:10:18 -07001647void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001648 int32_t sequenceId, hwc2_display_t /*display*/,
1649 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1650 Mutex::Autolock lock(mStateLock);
1651 if (sequenceId != getBE().mComposerSequenceId) {
1652 return;
1653 }
1654 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001655}
1656
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001657void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1658 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1659 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1660}
1661
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001662void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001663 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001664 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001665 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001666 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001667 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001668}
1669
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001670void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001671 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001672
1673 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1674 // display power state.
1675 postMessageAsync(new LambdaMessage(
1676 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1677}
1678
1679void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1680 ATRACE_CALL();
1681
Ady Abraham27c70212019-06-11 10:52:26 -07001682 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1683
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001684 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001685 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1686 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001687 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001688 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001689 }
Mathias Agopian86303202012-07-24 22:46:10 -07001690}
1691
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001692// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001693void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001694 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001695 // Clear the drawing state so that the logic inside of
1696 // handleTransactionLocked will fire. It will determine the delta between
1697 // mCurrentState and mDrawingState and re-apply all changes when we make the
1698 // transition.
1699 mDrawingState.displays.clear();
1700 mDisplays.clear();
1701}
1702
Steven Thomas050b2c82017-03-06 11:45:16 -08001703void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001704 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001705 if (!mVrFlinger)
1706 return;
1707 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001708 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001709 return;
1710 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001711
Lloyd Pique441d5042018-10-18 16:49:51 -07001712 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001713 ALOGE("Vr flinger is only supported for remote hardware composer"
1714 " service connections. Ignoring request to transition to vr"
1715 " flinger.");
1716 mVrFlingerRequestsDisplay = false;
1717 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001718 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001719
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001720 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001721
Steven Thomas0123ac62018-07-12 11:32:34 -07001722 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001723 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001724
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001725 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001726
1727 // Clear out all the output layers from the composition engine for all
1728 // displays before destroying the hardware composer interface. This ensures
1729 // any HWC layers are destroyed through that interface before it becomes
1730 // invalid.
1731 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001732 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001733 }
1734
Steven Thomas0123ac62018-07-12 11:32:34 -07001735 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1736 // called below. Clear the reference now so we don't accidentally use it
1737 // later.
1738 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001739
Steven Thomasb02664d2017-07-26 18:48:28 -07001740 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001741 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001742 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001743
Steven Thomasb02664d2017-07-26 18:48:28 -07001744 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001745 // Delete the current instance before creating the new one
1746 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1747 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1748 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001749 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001750
Lloyd Pique441d5042018-10-18 16:49:51 -07001751 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001752 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001753
1754 if (vrFlingerRequestsDisplay) {
1755 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001756 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001757
1758 mVisibleRegionsDirty = true;
1759 invalidateHwcGeometry();
1760
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001761 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001762 display = getDefaultDisplayDeviceLocked();
1763 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001764 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001765
Steven Thomasb02664d2017-07-26 18:48:28 -07001766 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001767 const nsecs_t vsyncPeriod = getVsyncPeriod();
1768 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001769
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001770 // The present fences returned from vr_hwc are not an accurate
1771 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001772 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001773
Steven Thomasb02664d2017-07-26 18:48:28 -07001774 // Use phase of 0 since phase is not known.
1775 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001776 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001777 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001778
Ana Krulecc2870422019-01-29 19:00:58 -08001779 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001780
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001781 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001782 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001783}
1784
Alec Mouri6d414b52020-03-17 11:18:05 -07001785sp<Fence> SurfaceFlinger::previousFrameFence() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001786 // We are storing the last 2 present fences. If sf's phase offset is to be
1787 // woken up before the actual vsync but targeting the next vsync, we need to check
1788 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001789 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1790 : mPreviousPresentFences[1];
1791}
1792
1793bool SurfaceFlinger::previousFramePending(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1794 ATRACE_CALL();
1795 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001796
Ady Abraham11579302019-09-19 12:35:58 -07001797 if (fence == Fence::NO_FENCE) {
1798 return false;
1799 }
1800
1801 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1802 fence->wait(graceTimeMs);
1803 }
1804
1805 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001806}
1807
Alec Mouri6d414b52020-03-17 11:18:05 -07001808nsecs_t SurfaceFlinger::previousFramePresentTime() NO_THREAD_SAFETY_ANALYSIS {
1809 const sp<Fence>& fence = previousFrameFence();
1810
1811 if (fence == Fence::NO_FENCE) {
1812 return Fence::SIGNAL_TIME_INVALID;
1813 }
1814
1815 return fence->getSignalTime();
1816}
1817
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001818void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001819 DisplayStatInfo stats;
1820 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001821 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001822 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001823 mExpectedPresentTime.store(
1824 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001825}
1826
Dominik Laskowski22488f62019-03-28 09:53:04 -07001827void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001828 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001829 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001830 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001831 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001832 // calculate the expected present time once and use the cached
1833 // value throughout this frame to make sure all layers are
1834 // seeing this same value.
Alec Mouri6d414b52020-03-17 11:18:05 -07001835 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001836 populateExpectedPresentTime();
1837
Ady Abraham11579302019-09-19 12:35:58 -07001838 // When Backpressure propagation is enabled we want to give a small grace period
1839 // for the present fence to fire instead of just giving up on this frame to handle cases
1840 // where present fence is just about to get signaled.
1841 const int graceTimeForPresentFenceMs =
1842 (mPropagateBackpressure &&
1843 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1844 ? 1
1845 : 0;
Alec Mouri6d414b52020-03-17 11:18:05 -07001846
1847 // Pending frames may trigger backpressure propagation.
1848 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1849 previousFramePending(
1850 graceTimeForPresentFenceMs)};
1851
1852 // Frame missed counts for metrics tracking.
1853 // A frame is missed if the prior frame is still pending. If no longer pending,
1854 // then we still count the frame as missed if the predicted present time
1855 // was further in the past than when the fence actually fired.
1856
1857 // Add some slop to correct for drift. This should generally be
1858 // smaller than a typical frame duration, but should not be so small
1859 // that it reports reasonable drift as a missed frame.
1860 DisplayStatInfo stats;
1861 mScheduler->getDisplayStatInfo(&stats);
1862 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1863 const nsecs_t previousPresentTime = previousFramePresentTime();
1864 const TracedOrdinal<bool> frameMissed =
1865 {"PrevFrameMissed",
1866 framePending ||
1867 (previousPresentTime >= 0 &&
1868 (lastExpectedPresentTime < previousPresentTime - frameMissedSlop))};
1869 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001870 mHadDeviceComposition && frameMissed};
Alec Mouri6d414b52020-03-17 11:18:05 -07001871 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001872 mHadClientComposition && frameMissed};
1873
Alec Mouricc0fc602019-02-26 21:45:19 -08001874 if (frameMissed) {
1875 mFrameMissedCount++;
1876 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001877 if (mMissedFrameJankCount == 0) {
1878 mMissedFrameJankStart = systemTime();
1879 }
1880 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001881 }
1882
Alec Mouri40189b02019-03-05 15:07:54 -08001883 if (hwcFrameMissed) {
1884 mHwcFrameMissedCount++;
1885 }
1886
1887 if (gpuFrameMissed) {
1888 mGpuFrameMissedCount++;
1889 }
1890
Alec Mouri6d414b52020-03-17 11:18:05 -07001891 if (framePending && mPropagateBackpressure) {
Ady Abrahamadb9a992019-09-19 21:21:55 +00001892 if ((hwcFrameMissed && !gpuFrameMissed) ||
1893 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001894 signalLayerUpdate();
1895 break;
1896 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001897 }
Dan Stoza50182882016-07-08 12:02:20 -07001898
Alec Mouri989ddbe2020-02-06 09:26:19 -08001899 // Our jank window is always at least 100ms since we missed a
1900 // frame...
1901 static constexpr nsecs_t kMinJankyDuration =
1902 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1903 // ...but if it's larger than 1s then we missed the trace cutoff.
1904 static constexpr nsecs_t kMaxJankyDuration =
1905 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1906 // If we're in a user build then don't push any atoms
1907 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1908 const auto displayDevice = getDefaultDisplayDeviceLocked();
1909 // Only report jank when the display is on, as displays in DOZE
1910 // power mode may operate at a different frame rate than is
1911 // reported in their config, which causes noticeable (but less
1912 // severe) jank.
1913 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1914 const nsecs_t currentTime = systemTime();
1915 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1916 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1917 ATRACE_NAME("Jank detected");
1918 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1919 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1920 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1921 jankyDurationMillis, mMissedFrameJankCount);
1922 }
1923
1924 // We either reported a jank event or we missed the trace
1925 // window, so clear counters here.
1926 if (jankDuration > kMinJankyDuration) {
1927 mMissedFrameJankCount = 0;
1928 mMissedFrameJankStart = 0;
1929 }
1930 }
1931 }
1932
Steven Thomas050b2c82017-03-06 11:45:16 -08001933 // Now that we're going to make it to the handleMessageTransaction()
1934 // call below it's safe to call updateVrFlinger(), which will
1935 // potentially trigger a display handoff.
1936 updateVrFlinger();
1937
Vishnu Nair60db8c02020-04-02 11:55:16 -07001938 bool refreshNeeded;
1939 withTracingLock([&]() {
1940 refreshNeeded = handleMessageTransaction();
1941 refreshNeeded |= handleMessageInvalidate();
1942 if (mTracingEnabled) {
1943 mAddCompositionStateToTrace =
1944 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1945 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1946 mTracing.notifyLocked("visibleRegionsDirty");
1947 }
1948 }
1949 });
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001950
Ana Krulecc84d09b2019-11-02 23:10:29 +01001951 // Layers need to get updated (in the previous line) before we can use them for
1952 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001953 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1954 // and may eventually call to ~Layer() if it holds the last reference
1955 {
1956 Mutex::Autolock _l(mStateLock);
1957 mScheduler->chooseRefreshRateForContent();
1958 }
1959
Ana Krulecc84d09b2019-11-02 23:10:29 +01001960 if (performSetActiveConfig()) {
1961 break;
1962 }
1963
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001964 updateCursorAsync();
1965 updateInputFlinger();
1966
Dan Stoza58784442014-12-02 16:58:17 -08001967 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001968 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001969 // Signal a refresh if a transaction modified the window state,
1970 // a new buffer was latched, or if HWC has requested a full
1971 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001972 if (mFrameStartTime <= 0) {
1973 // We should only use the time of the first invalidate
1974 // message that signals a refresh as the beginning of the
1975 // frame. Otherwise the real frame time will be
1976 // underestimated.
1977 mFrameStartTime = frameStart;
1978 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001979 signalRefresh();
1980 }
1981 break;
1982 }
1983 case MessageQueue::REFRESH: {
1984 handleMessageRefresh();
1985 break;
1986 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001987 }
1988}
1989
Dan Stoza6b9454d2014-11-07 16:00:59 -08001990bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001991 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001992 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001993
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001994 bool flushedATransaction = flushTransactionQueues();
1995
1996 bool runHandleTransaction = transactionFlags &&
1997 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1998
1999 if (runHandleTransaction) {
2000 handleTransaction(eTransactionMask);
2001 } else {
2002 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002003 }
2004
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002005 if (transactionFlushNeeded()) {
2006 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002007 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002008
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002009 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002010}
2011
Mathias Agopian4fec8732012-06-29 14:12:52 -07002012void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002013 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002014
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002015 mRefreshPending = false;
2016
Lloyd Piqueab039b52019-02-13 14:22:42 -08002017 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002018 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002019 for (const auto& [_, display] : mDisplays) {
2020 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2021 }
2022 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002023 if (auto layerFE = layer->getCompositionEngineLayerFE())
2024 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002025 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002026 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2027 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002028 if (auto layerFE = layer->getCompositionEngineLayerFE())
2029 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002030 }
2031
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002032 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002033 refreshArgs.outputColorSetting = useColorManagement
2034 ? mDisplayColorSetting
2035 : compositionengine::OutputColorSetting::kUnmanaged;
2036 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2037 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002038
2039 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2040 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002041 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002042
2043 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2044 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2045 mDrawingState.colorMatrixChanged = false;
2046 }
2047
2048 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2049
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002050 if (mDebugRegion != 0) {
2051 refreshArgs.devOptFlashDirtyRegionsDelay =
2052 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2053 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002054
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002055 mGeometryInvalid = false;
2056
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002057 // Store the present time just before calling to the composition engine so we could notify
2058 // the scheduler.
2059 const auto presentTime = systemTime();
2060
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002061 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002062 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2063 // Reset the frame start time now that we've recorded this frame.
2064 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002065
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002066 mScheduler->onDisplayRefreshed(presentTime);
2067
David Sodmanfa9b2af2017-12-24 13:28:59 -08002068 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002069 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002070
Lloyd Pique66d68602019-02-13 14:23:31 -08002071 mHadClientComposition =
2072 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2073 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002074 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2075 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002076 });
2077 mHadDeviceComposition =
2078 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2079 auto& displayDevice = tokenDisplayPair.second;
2080 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2081 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002082 mReusedClientComposition =
2083 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2084 auto& displayDevice = tokenDisplayPair.second;
2085 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2086 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002087
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002088 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002089
David Sodman7e4ae112018-02-09 15:02:28 -08002090 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002091 if (mVisibleRegionsDirty) {
2092 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002093 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002094 mTracing.notify("visibleRegionsDirty");
2095 }
2096 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002097
2098 if (mCompositionEngine->needsAnotherUpdate()) {
2099 signalLayerUpdate();
2100 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002101}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002102
David Sodmanfa9b2af2017-12-24 13:28:59 -08002103
2104bool SurfaceFlinger::handleMessageInvalidate() {
2105 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002106 bool refreshNeeded = handlePageFlip();
2107
Vishnu Nair4351ad52019-02-11 14:13:02 -08002108 if (mVisibleRegionsDirty) {
2109 computeLayerBounds();
2110 }
2111
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002112 for (auto& layer : mLayersPendingRefresh) {
2113 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002114 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002115 invalidateLayerStack(layer, visibleReg);
2116 }
2117 mLayersPendingRefresh.clear();
2118 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002119}
2120
Ana Krulece588e312018-09-18 12:32:24 -07002121void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2122 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002123 // Update queue of past composite+present times and determine the
2124 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002125 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002126 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002127 while (!getBE().mCompositePresentTimes.empty()) {
2128 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002129 // Cached values should have been updated before calling this method,
2130 // which helps avoid duplicate syscalls.
2131 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2132 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2133 break;
2134 }
2135 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002136 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002137 }
2138
2139 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002140 while (getBE().mCompositePresentTimes.size() > 16) {
2141 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002142 }
2143
Ana Krulece588e312018-09-18 12:32:24 -07002144 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002145}
2146
Ana Krulece588e312018-09-18 12:32:24 -07002147void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2148 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002149 // Integer division and modulo round toward 0 not -inf, so we need to
2150 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002151 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2152 ? (stats.vsyncPeriod -
2153 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2154 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002155
Ady Abraham9e16a482019-12-03 17:19:41 -08002156 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002157 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002158 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002159 }
2160
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002161 // Snap the latency to a value that removes scheduling jitter from the
2162 // composition and present times, which often have >1ms of jitter.
2163 // Reducing jitter is important if an app attempts to extrapolate
2164 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002165 // Snapping also allows an app to precisely calculate
2166 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002167 nsecs_t bias = stats.vsyncPeriod / 2;
2168 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2169 nsecs_t snappedCompositeToPresentLatency =
2170 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002171
David Sodman99974d22017-11-28 12:04:33 -08002172 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002173 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2174 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002175 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002176}
2177
David Sodman2b406362017-12-15 13:33:47 -08002178void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002179{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002180 ATRACE_CALL();
2181 ALOGV("postComposition");
2182
Brian Andersonf6386862016-10-31 16:34:13 -07002183 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002184 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002185 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002186 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002187 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002188 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002189
David Sodman73beded2017-11-15 11:56:06 -08002190 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002191 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002192 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002193 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002194 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2195 ->getRenderSurface()
2196 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002197 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002198 } else {
2199 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2200 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002201
David Sodman73beded2017-11-15 11:56:06 -08002202 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002203 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2204 mPreviousPresentFences[0] = displayDevice
2205 ? getHwComposer().getPresentFence(*displayDevice->getId())
2206 : Fence::NO_FENCE;
2207 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002208 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002209
Ana Krulece588e312018-09-18 12:32:24 -07002210 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002211 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002212
Lloyd Piqueab039b52019-02-13 14:22:42 -08002213 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2214 // be sampled a little later than when we started doing work for this frame,
2215 // but that should be okay since updateCompositorTiming has snapping logic.
2216 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2217 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002218 CompositorTiming compositorTiming;
2219 {
David Sodman99974d22017-11-28 12:04:33 -08002220 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2221 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002222 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002223
Edgar Arriaga844fa672020-01-16 14:21:42 -08002224 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002225 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2226 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002227 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002228 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002229 }
Robert Carr2047fae2016-11-28 14:09:09 -08002230 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002231
Ady Abraham92fa2f42020-02-11 15:33:56 -08002232 if (displayDevice && displayDevice->isPrimary() &&
2233 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002234 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002235 }
2236
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002237 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002238 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2239 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002240 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002241 }
2242 }
2243
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002244 if (mAnimCompositionPending) {
2245 mAnimCompositionPending = false;
2246
Brian Anderson4e606e32017-03-16 15:34:57 -07002247 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002248 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002249 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002250 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002251 // The HWC doesn't support present fences, so use the refresh
2252 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002253 const nsecs_t presentTime =
2254 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002255 mAnimFrameTracker.setActualPresentTime(presentTime);
2256 }
2257 mAnimFrameTracker.advanceFrame();
2258 }
Dan Stozab90cf072015-03-05 11:05:59 -08002259
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002260 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002261 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002262 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002263 }
2264
Vishnu Nair9b079a22020-01-21 14:36:08 -08002265 if (mReusedClientComposition) {
2266 mTimeStats->incrementClientCompositionReusedFrames();
2267 }
2268
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002269 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002270
Alec Mouri717bcb62020-02-10 17:07:19 -08002271 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2272 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2273 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2274
Lloyd Pique32cbe282018-10-19 13:09:22 -07002275 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2276 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002277 return;
2278 }
2279
2280 nsecs_t currentTime = systemTime();
2281 if (mHasPoweredOff) {
2282 mHasPoweredOff = false;
2283 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002284 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002285 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002286 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2287 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002288 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002289 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002290 }
David Sodman4a36e932017-11-07 14:29:47 -08002291 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002292 }
David Sodman4a36e932017-11-07 14:29:47 -08002293 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002294
2295 {
2296 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002297 if (mTexturePool.size() < mTexturePoolSize) {
2298 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002299 const size_t offset = mTexturePool.size();
2300 mTexturePool.resize(mTexturePoolSize);
2301 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2302 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002303 } else if (mTexturePool.size() > mTexturePoolSize) {
2304 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2305 const size_t offset = mTexturePoolSize;
2306 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2307 mTexturePool.resize(mTexturePoolSize);
2308 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002309 }
2310 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002311
Ady Abrahambe0f9482019-04-24 15:41:53 -07002312 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002313 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002314
Kevin DuBois413287f2019-02-25 08:46:47 -08002315 if (mLumaSampling && mRegionSamplingThread) {
2316 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002317 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002318
2319 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2320 // side-effect of getTotalSize(), so we check that again here
2321 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002322 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002323 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2324 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002325}
2326
Vishnu Nair4351ad52019-02-11 14:13:02 -08002327void SurfaceFlinger::computeLayerBounds() {
2328 for (const auto& pair : mDisplays) {
2329 const auto& displayDevice = pair.second;
2330 const auto display = displayDevice->getCompositionDisplay();
2331 for (const auto& layer : mDrawingState.layersSortedByZ) {
2332 // only consider the layers on the given layer stack
2333 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002334 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002335 }
2336
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002337 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2338 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002339 }
2340 }
2341}
2342
David Sodmanfa9b2af2017-12-24 13:28:59 -08002343void SurfaceFlinger::postFrame()
2344{
2345 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002346 const auto display = getDefaultDisplayDeviceLocked();
2347 if (display && getHwComposer().isConnected(*display->getId())) {
2348 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002349 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2350 logFrameStats();
2351 }
2352 }
2353}
2354
Mathias Agopian87baae12012-07-31 12:38:26 -07002355void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002356{
Mathias Agopian841cde52012-03-01 15:44:37 -08002357 ATRACE_CALL();
2358
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002359 // here we keep a copy of the drawing state (that is the state that's
2360 // going to be overwritten by handleTransactionLocked()) outside of
2361 // mStateLock so that the side-effects of the State assignment
2362 // don't happen with mStateLock held (which can cause deadlocks).
2363 State drawingState(mDrawingState);
2364
Mathias Agopianca4d3602011-05-19 15:38:14 -07002365 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002366 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002367
Mathias Agopianca4d3602011-05-19 15:38:14 -07002368 // Here we're guaranteed that some transaction flags are set
2369 // so we can call handleTransactionLocked() unconditionally.
2370 // We call getTransactionFlags(), which will also clear the flags,
2371 // with mStateLock held to guarantee that mCurrentState won't change
2372 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002373
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002374 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002375 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002376 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002377
Mathias Agopianca4d3602011-05-19 15:38:14 -07002378 mDebugInTransaction = 0;
2379 invalidateHwcGeometry();
2380 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002381}
2382
Lloyd Piqueba04e622017-12-14 17:11:26 -08002383void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2384 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002385 const std::optional<DisplayIdentificationInfo> info =
2386 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002387
Dominik Laskowski075d3172018-05-24 15:50:06 -07002388 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002389 continue;
2390 }
2391
Dominik Laskowski55c85402020-01-21 16:25:47 -08002392 const DisplayId displayId = info->id;
2393 const auto it = mPhysicalDisplayTokens.find(displayId);
2394
Lloyd Piqueba04e622017-12-14 17:11:26 -08002395 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002396 if (it == mPhysicalDisplayTokens.end()) {
2397 ALOGV("Creating display %s", to_string(displayId).c_str());
2398
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002399 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002400 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002401 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002402
Dominik Laskowski075d3172018-05-24 15:50:06 -07002403 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002404 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2405 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002406 state.isSecure = true; // All physical displays are currently considered secure.
2407 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002408
2409 sp<IBinder> token = new BBinder();
2410 mCurrentState.displays.add(token, state);
2411 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2412
Dominik Laskowski075d3172018-05-24 15:50:06 -07002413 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002414 } else {
2415 ALOGV("Recreating display %s", to_string(displayId).c_str());
2416
2417 const auto token = it->second;
2418 auto& state = mCurrentState.displays.editValueFor(token);
2419 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002420 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002421 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002422 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002423
Dominik Laskowski55c85402020-01-21 16:25:47 -08002424 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002425 if (index >= 0) {
2426 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2427 mInterceptor->saveDisplayDeletion(state.sequenceId);
2428 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002429 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002430 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002431 }
2432
2433 processDisplayChangesLocked();
2434 }
2435
2436 mPendingHotplugEvents.clear();
2437}
2438
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002439void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002440 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2441 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002442}
2443
Lloyd Pique99d3da52018-01-22 17:48:03 -08002444sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002445 const wp<IBinder>& displayToken,
2446 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002447 const DisplayDeviceState& state,
2448 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002449 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002450 auto displayId = compositionDisplay->getDisplayId();
2451 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002452 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002453 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002454 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002455 creationArgs.hasWideColorGamut = false;
2456 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002457
Dominik Laskowski55c85402020-01-21 16:25:47 -08002458 if (const auto& physical = state.physical) {
2459 creationArgs.connectionType = physical->type;
2460 }
2461
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002462 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002463 creationArgs.isPrimary = isInternalDisplay;
2464
2465 if (useColorManagement && displayId) {
2466 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002467 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002468 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002469 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002470 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002471
Dominik Laskowski7e045462018-05-30 13:02:02 -07002472 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002473 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002474 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002475 }
tangrobin6753a022018-08-10 10:58:54 +08002476 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002477
Dominik Laskowski075d3172018-05-24 15:50:06 -07002478 if (displayId) {
2479 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002480 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002481 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002482 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002483
Lloyd Pique90c115d2018-09-18 21:39:42 -07002484 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002485 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002486 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002487
Lloyd Pique99d3da52018-01-22 17:48:03 -08002488 // Make sure that composition can never be stalled by a virtual display
2489 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002490 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002491 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002492 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2493 }
2494
Dominik Laskowski718f9602019-11-09 20:01:35 -08002495 creationArgs.physicalOrientation =
2496 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002497
Lloyd Pique99d3da52018-01-22 17:48:03 -08002498 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002499 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002500
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002501 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002502
2503 if (maxFrameBufferAcquiredBuffers >= 3) {
2504 nativeWindowSurface->preallocateBuffers();
2505 }
2506
2507 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002508 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002509 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002510 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002511 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002512 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002513 display->getCompositionDisplay()->setColorProfile(
2514 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2515 RenderIntent::COLORIMETRIC,
2516 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002517 if (!state.isVirtual()) {
2518 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002519 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2520 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002521 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002522
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002523 display->setLayerStack(state.layerStack);
2524 display->setProjection(state.orientation, state.viewport, state.frame);
2525 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002526
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002527 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002528}
2529
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002530void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2531 const DisplayDeviceState& state) {
2532 int width = 0;
2533 int height = 0;
2534 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2535 if (state.physical) {
2536 const auto& activeConfig =
2537 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2538 width = activeConfig->getWidth();
2539 height = activeConfig->getHeight();
2540 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2541 } else if (state.surface != nullptr) {
2542 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2543 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2544 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2545 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2546 int intPixelFormat;
2547 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2548 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2549 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2550 } else {
2551 // Virtual displays without a surface are dormant:
2552 // they have external state (layer stack, projection,
2553 // etc.) but no internal state (i.e. a DisplayDevice).
2554 return;
2555 }
2556
2557 compositionengine::DisplayCreationArgsBuilder builder;
2558 if (const auto& physical = state.physical) {
2559 builder.setPhysical({physical->id, physical->type});
2560 }
2561 builder.setPixels(ui::Size(width, height));
2562 builder.setPixelFormat(pixelFormat);
2563 builder.setIsSecure(state.isSecure);
2564 builder.setLayerStackId(state.layerStack);
2565 builder.setPowerAdvisor(&mPowerAdvisor);
2566 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2567 builder.setName(state.displayName);
2568 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2569
2570 sp<compositionengine::DisplaySurface> displaySurface;
2571 sp<IGraphicBufferProducer> producer;
2572 sp<IGraphicBufferProducer> bqProducer;
2573 sp<IGraphicBufferConsumer> bqConsumer;
2574 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2575
2576 std::optional<DisplayId> displayId = compositionDisplay->getId();
2577
2578 if (state.isVirtual()) {
2579 sp<VirtualDisplaySurface> vds =
2580 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2581 bqConsumer, state.displayName);
2582
2583 displaySurface = vds;
2584 producer = vds;
2585 } else {
2586 ALOGE_IF(state.surface != nullptr,
2587 "adding a supported display, but rendering "
2588 "surface is provided (%p), ignoring it",
2589 state.surface.get());
2590
2591 LOG_ALWAYS_FATAL_IF(!displayId);
2592 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2593 maxGraphicsWidth, maxGraphicsHeight);
2594 producer = bqProducer;
2595 }
2596
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002597 LOG_FATAL_IF(!displaySurface);
2598 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2599 displaySurface, producer);
2600 mDisplays.emplace(displayToken, display);
2601 if (!state.isVirtual()) {
2602 LOG_FATAL_IF(!displayId);
2603 dispatchDisplayHotplugEvent(displayId->value, true);
2604 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002605
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002606 if (display->isPrimary()) {
2607 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002608 }
2609}
2610
2611void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2612 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2613 // Save display ID before disconnecting.
2614 const auto displayId = display->getId();
2615 display->disconnect();
2616
2617 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002618 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002619 dispatchDisplayHotplugEvent(displayId->value, false);
2620 }
2621 }
2622
2623 mDisplays.erase(displayToken);
2624}
2625
2626void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2627 const DisplayDeviceState& currentState,
2628 const DisplayDeviceState& drawingState) {
2629 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2630 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002631 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002632 // changing the surface is like destroying and recreating the DisplayDevice
2633 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2634 display->disconnect();
2635 }
2636 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002637 if (const auto& physical = currentState.physical) {
2638 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2639 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002640 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002641 if (currentState.physical) {
2642 initializeDisplays();
2643 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002644 return;
2645 }
2646
2647 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2648 if (currentState.layerStack != drawingState.layerStack) {
2649 display->setLayerStack(currentState.layerStack);
2650 }
2651 if ((currentState.orientation != drawingState.orientation) ||
2652 (currentState.viewport != drawingState.viewport) ||
2653 (currentState.frame != drawingState.frame)) {
2654 display->setProjection(currentState.orientation, currentState.viewport,
2655 currentState.frame);
2656 }
2657 if (currentState.width != drawingState.width ||
2658 currentState.height != drawingState.height) {
2659 display->setDisplaySize(currentState.width, currentState.height);
2660 if (display->isPrimary()) {
2661 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2662 }
2663 }
2664 }
2665}
2666
Lloyd Pique347200f2017-12-14 17:00:15 -08002667void SurfaceFlinger::processDisplayChangesLocked() {
2668 // here we take advantage of Vector's copy-on-write semantics to
2669 // improve performance by skipping the transaction entirely when
2670 // know that the lists are identical
2671 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2672 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2673 if (!curr.isIdenticalTo(draw)) {
2674 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002675
2676 // find the displays that were removed
2677 // (ie: in drawing state but not in current state)
2678 // also handle displays that changed
2679 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002680 for (size_t i = 0; i < draw.size(); i++) {
2681 const wp<IBinder>& displayToken = draw.keyAt(i);
2682 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002683 if (j < 0) {
2684 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002685 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002686 } else {
2687 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002688 const DisplayDeviceState& currentState = curr[j];
2689 const DisplayDeviceState& drawingState = draw[i];
2690 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002691 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002692 }
2693
2694 // find displays that were added
2695 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002696 for (size_t i = 0; i < curr.size(); i++) {
2697 const wp<IBinder>& displayToken = curr.keyAt(i);
2698 if (draw.indexOfKey(displayToken) < 0) {
2699 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002700 }
2701 }
2702 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002703
2704 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002705}
2706
Mathias Agopian87baae12012-07-31 12:38:26 -07002707void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002708{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002709 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2710
Dan Stoza7dde5992015-05-22 09:51:44 -07002711 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002712 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002713 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002714 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002715
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716 /*
2717 * Traversal of the children
2718 * (perform the transaction for each of them if needed)
2719 */
2720
Marissa Wall06255332019-03-27 13:48:27 -07002721 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002722 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002723 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002724 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725
2726 const uint32_t flags = layer->doTransaction(0);
2727 if (flags & Layer::eVisibleRegion)
2728 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002729
2730 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002731 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002732 }
Robert Carr2047fae2016-11-28 14:09:09 -08002733 });
Marissa Wall06255332019-03-27 13:48:27 -07002734 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735 }
2736
2737 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002738 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002739 */
2740
Mathias Agopiane57f2922012-08-09 16:29:12 -07002741 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002742 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002743 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002744 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002745
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002746 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002747 // The transform hint might have changed for some layers
2748 // (either because a display has changed, or because a layer
2749 // as changed).
2750 //
2751 // Walk through all the layers in currentLayers,
2752 // and update their transform hint.
2753 //
2754 // If a layer is visible only on a single display, then that
2755 // display is used to calculate the hint, otherwise we use the
2756 // default display.
2757 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002758 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002759 // the hint is set before we acquire a buffer from the surface texture.
2760 //
2761 // NOTE: layer transactions have taken place already, so we use their
2762 // drawing state. However, SurfaceFlinger's own transaction has not
2763 // happened yet, so we must use the current state layer list
2764 // (soon to become the drawing state list).
2765 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002766 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002767 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002768 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002769 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002770 // NOTE: we rely on the fact that layers are sorted by
2771 // layerStack first (so we don't have to traverse the list
2772 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002773 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002774 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002775 currentlayerStack = layerStack;
2776 // figure out if this layerstack is mirrored
2777 // (more than one display) if so, pick the default display,
2778 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002779 hintDisplay = nullptr;
2780 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002781 if (display->getCompositionDisplay()
2782 ->belongsInOutput(layer->getLayerStack(),
2783 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002784 if (hintDisplay) {
2785 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002786 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002787 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002788 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002789 }
2790 }
2791 }
2792 }
Chet Haase91d25932013-04-11 15:24:55 -07002793
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002794 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002795 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2796 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002797
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002798 // could be null when this layer is using a layerStack
2799 // that is not visible on any display. Also can occur at
2800 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002801 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002802 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002803
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002804 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002805 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002806 if (hintDisplay) {
2807 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002808 }
Robert Carr2047fae2016-11-28 14:09:09 -08002809
2810 first = false;
2811 });
Mathias Agopian84300952012-11-21 16:02:13 -08002812 }
2813
2814
Mathias Agopian3559b072012-08-15 13:46:03 -07002815 /*
2816 * Perform our own transaction if needed
2817 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002818
2819 if (mLayersAdded) {
2820 mLayersAdded = false;
2821 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002822 mVisibleRegionsDirty = true;
2823 }
2824
2825 // some layers might have been removed, so
2826 // we need to update the regions they're exposing.
2827 if (mLayersRemoved) {
2828 mLayersRemoved = false;
2829 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002830 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002831 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002832 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002833 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002834 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002835 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002836 }
Robert Carr2047fae2016-11-28 14:09:09 -08002837 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838 }
2839
Vishnu Nairec0ab382019-02-13 15:32:56 -08002840 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002841 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002842}
2843
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002844void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002845 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002846 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002847 return;
2848 }
2849
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002850 if (mVisibleRegionsDirty || mInputInfoChanged) {
2851 mInputInfoChanged = false;
2852 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002853 } else if (mInputWindowCommands.syncInputWindows) {
2854 // If the caller requested to sync input windows, but there are no
2855 // changes to input windows, notify immediately.
2856 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002857 }
2858
Arthur Hung6cbb9752019-09-05 16:38:18 +08002859 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002860}
2861
2862void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002863 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002864
Robert Carra1257842020-01-31 13:48:28 -08002865 // We use a simple caching algorithm here. mInputDirty begins as true,
2866 // after we call setInputWindows we set it to false, so
2867 // in the future we wont call it again.. We set input dirty to true again
2868 // when any layer that hasInput() has a transaction performed on it
2869 // or when any parent or relative parent of such a layer has a transaction
2870 // performed on it. Not all of these transactions will really result in
2871 // input changes but all input changes will spring from these transactions
2872 // so the cache is safe but not optimal. It seems like it might be annoyingly
2873 // costly to cache and comapre the actual InputWindowHandle vector though.
Robert Carr0854b992020-03-11 12:09:42 -07002874 if (!mInputDirty && !mInputWindowCommands.syncInputWindows) {
Robert Carra1257842020-01-31 13:48:28 -08002875 return;
2876 }
2877
Robert Carr720e5062018-07-30 17:45:14 -07002878 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2879 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002880 // When calculating the screen bounds we ignore the transparent region since it may
2881 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002882 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002883 }
2884 });
chaviw291d88a2019-02-14 10:33:58 -08002885
2886 mInputFlinger->setInputWindows(inputHandles,
2887 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2888 : nullptr);
Robert Carra1257842020-01-31 13:48:28 -08002889
2890 mInputDirty = false;
Robert Carr720e5062018-07-30 17:45:14 -07002891}
2892
Vishnu Nairec0ab382019-02-13 15:32:56 -08002893void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002894 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002895 mPendingInputWindowCommands.clear();
2896}
2897
Riley Andrews03414a12014-07-01 14:22:59 -07002898void SurfaceFlinger::updateCursorAsync()
2899{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002900 compositionengine::CompositionRefreshArgs refreshArgs;
2901 for (const auto& [_, display] : mDisplays) {
2902 if (display->getId()) {
2903 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002904 }
2905 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002906
2907 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002908}
2909
Ady Abraham2139f732019-11-13 18:56:40 -08002910void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002911 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2912 // If this is called from the main thread mStateLock must be locked before
2913 // Currently the only way to call this function from the main thread is from
2914 // Sheduler::chooseRefreshRateForContent
2915
2916 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002917 changeRefreshRateLocked(refreshRate, event);
2918}
2919
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002920void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2921 if (mScheduler) {
2922 // In practice it's not allowed to hotplug in/out the primary display once it's been
2923 // connected during startup, but some tests do it, so just warn and return.
2924 ALOGW("Can't re-init scheduler");
2925 return;
2926 }
2927
Ady Abraham2139f732019-11-13 18:56:40 -08002928 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002929 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002930 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002931 primaryDisplayId),
2932 currentConfig);
2933 mRefreshRateStats =
2934 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2935 currentConfig, HWC_POWER_MODE_OFF);
2936 mRefreshRateStats->setConfigMode(currentConfig);
2937
Ady Abraham9e16a482019-12-03 17:19:41 -08002938 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2939
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002940 // start the EventThread
2941 mScheduler =
2942 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002943 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002944 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002945 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002946 impl::EventThread::InterceptVSyncsCallback());
2947 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002948 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002949 [this](nsecs_t timestamp) {
2950 mInterceptor->saveVSyncEvent(timestamp);
2951 });
2952
2953 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2954 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002955 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002956
2957 mRegionSamplingThread =
2958 new RegionSamplingThread(*this, *mScheduler,
2959 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002960 // Dispatch a config change request for the primary display on scheduler
2961 // initialization, so that the EventThreads always contain a reference to a
2962 // prior configuration.
2963 //
2964 // This is a bit hacky, but this avoids a back-pointer into the main SF
2965 // classes from EventThread, and there should be no run-time binder cost
2966 // anyway since there are no connected apps at this point.
2967 const nsecs_t vsyncPeriod =
2968 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2969 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2970 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002971}
2972
Mathias Agopian4fec8732012-06-29 14:12:52 -07002973void SurfaceFlinger::commitTransaction()
2974{
Vishnu Nair60db8c02020-04-02 11:55:16 -07002975 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002976 mTransactionPending = false;
2977 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002978 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002979}
2980
Lloyd Pique58e24a32019-08-01 15:50:14 -07002981void SurfaceFlinger::commitTransactionLocked() {
2982 if (!mLayersPendingRemoval.isEmpty()) {
2983 // Notify removed layers now that they can't be drawn from
2984 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002985 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002986
2987 // Ensure any buffers set to display on any children are released.
2988 if (l->isRemovedFromCurrentState()) {
2989 l->latchAndReleaseBuffer();
2990 }
2991
2992 // If the layer has been removed and has no parent, then it will not be reachable
2993 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2994 // ensure we can copy its current to drawing state.
2995 if (!l->getParent()) {
2996 mOffscreenLayers.emplace(l.get());
2997 }
2998 }
2999 mLayersPendingRemoval.clear();
3000 }
3001
3002 // If this transaction is part of a window animation then the next frame
3003 // we composite should be considered an animation as well.
3004 mAnimCompositionPending = mAnimTransactionPending;
3005
3006 mDrawingState = mCurrentState;
3007 // clear the "changed" flags in current state
3008 mCurrentState.colorMatrixChanged = false;
3009
Edgar Arriaga844fa672020-01-16 14:21:42 -08003010 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003011 layer->commitChildList();
3012
3013 // If the layer can be reached when traversing mDrawingState, then the layer is no
3014 // longer offscreen. Remove the layer from the offscreenLayer set.
3015 if (mOffscreenLayers.count(layer)) {
3016 mOffscreenLayers.erase(layer);
3017 }
3018 });
3019
3020 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003021 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003022}
3023
Nataniel Borges2b796da2019-02-15 13:32:18 -08003024void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3025 if (mTracingEnabledChanged) {
3026 mTracingEnabled = mTracing.isEnabled();
3027 mTracingEnabledChanged = false;
3028 }
3029
3030 // Synchronize with Tracing thread
3031 std::unique_lock<std::mutex> lock;
3032 if (mTracingEnabled) {
3033 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3034 }
3035
3036 lockedOperation();
3037
3038 // Synchronize with Tracing thread
3039 if (mTracingEnabled) {
3040 lock.unlock();
3041 }
3042}
3043
chaviw74d90ad2019-04-26 14:45:26 -07003044void SurfaceFlinger::commitOffscreenLayers() {
3045 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003046 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003047 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3048 if (!trFlags) return;
3049
3050 layer->doTransaction(0);
3051 layer->commitChildList();
3052 });
3053 }
3054}
3055
Chia-I Wuab0c3192017-08-01 11:29:00 -07003056void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003057 for (const auto& [token, displayDevice] : mDisplays) {
3058 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003059 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003060 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003061 }
3062 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003063}
3064
Dan Stoza6b9454d2014-11-07 16:00:59 -08003065bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003066{
Ady Abraham09bd3922019-04-08 10:44:56 -07003067 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003068 ALOGV("handlePageFlip");
3069
Brian Andersond6927fb2016-07-23 23:37:30 -07003070 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003071
Mathias Agopian4fec8732012-06-29 14:12:52 -07003072 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003073 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003074 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003075
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003076 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3077
Eric Penner51c59cd2014-07-28 19:51:58 -07003078 // Store the set of layers that need updates. This set must not change as
3079 // buffers are being latched, as this could result in a deadlock.
3080 // Example: Two producers share the same command stream and:
3081 // 1.) Layer 0 is latched
3082 // 2.) Layer 0 gets a new frame
3083 // 2.) Layer 1 gets a new frame
3084 // 3.) Layer 1 is latched.
3085 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3086 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003087 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003088 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003089 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003090 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003091 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003092 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003093 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003094 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003095 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003096 } else {
3097 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003098 }
Robert Carr2047fae2016-11-28 14:09:09 -08003099 });
3100
chaviw49a108c2019-08-12 11:23:06 -07003101 // The client can continue submitting buffers for offscreen layers, but they will not
3102 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3103 // layers to ensure dequeueBuffer doesn't block indefinitely.
3104 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003105 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003106 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3107 }
3108
Lloyd Piquef2c79392018-12-20 16:23:33 -08003109 if (!mLayersWithQueuedFrames.empty()) {
3110 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3111 // writes to Layer current state. See also b/119481871
3112 Mutex::Autolock lock(mStateLock);
3113
3114 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003115 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003116 mLayersPendingRefresh.push_back(layer);
3117 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003118 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003119 if (layer->isBufferLatched()) {
3120 newDataLatched = true;
3121 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003122 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003123 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003124
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003125 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003126
3127 // If we will need to wake up at some time in the future to deal with a
3128 // queued frame that shouldn't be displayed during this vsync period, wake
3129 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003130 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003131 signalLayerUpdate();
3132 }
3133
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003134 // enter boot animation on first buffer latch
3135 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3136 ALOGI("Enter boot animation");
3137 mBootStage = BootStage::BOOTANIMATION;
3138 }
3139
Edgar Arriaga844fa672020-01-16 14:21:42 -08003140 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003141
Dan Stoza6b9454d2014-11-07 16:00:59 -08003142 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003143 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003144}
3145
Mathias Agopianad456f92011-01-13 17:53:01 -08003146void SurfaceFlinger::invalidateHwcGeometry()
3147{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003148 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003149}
3150
Robert Carrc0df3122019-04-11 13:18:21 -07003151status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3152 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3153 const sp<IBinder>& parentHandle,
3154 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003155 // add this layer to the current state list
3156 {
3157 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003158 sp<Layer> parent;
3159 if (parentHandle != nullptr) {
3160 parent = fromHandle(parentHandle);
3161 if (parent == nullptr) {
3162 return NAME_NOT_FOUND;
3163 }
3164 } else {
3165 parent = parentLayer;
3166 }
3167
Ady Abraham0a525092020-03-03 12:51:24 -08003168 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003169 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003170 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003171 return NO_MEMORY;
3172 }
Robert Carrc0df3122019-04-11 13:18:21 -07003173
3174 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3175
Robert Carrb89ea9d2018-12-10 13:01:14 -08003176 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003177 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003178 } else if (parent == nullptr) {
3179 lbc->onRemovedFromCurrentState();
3180 } else if (parent->isRemovedFromCurrentState()) {
3181 parent->addChild(lbc);
3182 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003183 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003184 parent->addChild(lbc);
3185 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003186
Yiwei Zhang243b3782018-05-15 17:40:04 -07003187 if (gbc != nullptr) {
3188 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3189 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3190 mMaxGraphicBufferProducerListSize,
3191 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3192 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003193 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003194 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003195 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003196 }
3197
Mathias Agopian96f08192010-06-02 23:28:45 -07003198 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003199 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003200
Dan Stoza7d89d062015-04-30 13:29:25 -07003201 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003202}
3203
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003204uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003205 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003206}
3207
Mathias Agopian3f844832013-08-07 21:24:32 -07003208uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003209 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003210}
3211
Mathias Agopian3f844832013-08-07 21:24:32 -07003212uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003213 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003214}
3215
3216uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003217 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003218 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003219 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003220 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003221 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003222 }
3223 return old;
3224}
3225
Marissa Wall713b63f2018-10-17 15:42:43 -07003226bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003227 // to prevent onHandleDestroyed from being called while the lock is held,
3228 // we must keep a copy of the transactions (specifically the composer
3229 // states) around outside the scope of the lock
3230 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003231 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003232 {
3233 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003234
Valerie Haufce31b82019-04-30 16:41:14 -07003235 auto it = mTransactionQueues.begin();
3236 while (it != mTransactionQueues.end()) {
3237 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003238
Valerie Haufce31b82019-04-30 16:41:14 -07003239 while (!transactionQueue.empty()) {
3240 const auto& transaction = transactionQueue.front();
3241 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003242 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003243 transaction.states)) {
3244 setTransactionFlags(eTransactionFlushNeeded);
3245 break;
3246 }
3247 transactions.push_back(transaction);
3248 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3249 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003250 transaction.buffer, transaction.postTime,
3251 transaction.privileged, transaction.hasListenerCallbacks,
3252 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003253 transactionQueue.pop();
3254 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003255 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003256
Valerie Haufce31b82019-04-30 16:41:14 -07003257 if (transactionQueue.empty()) {
3258 it = mTransactionQueues.erase(it);
3259 mTransactionCV.broadcast();
3260 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003261 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003262 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003263 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003264 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003265 return flushedATransaction;
3266}
3267
3268bool SurfaceFlinger::transactionFlushNeeded() {
3269 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003270}
3271
chaviwca27f252018-02-06 16:46:39 -08003272
Marissa Wall17b4e452018-12-26 16:32:34 -08003273bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003274 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003275 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003276 if (!useCachedExpectedPresentTime)
3277 populateExpectedPresentTime();
3278
3279 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003280 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3281 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3282 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3283 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3284 return false;
3285 }
3286
Marissa Wall713b63f2018-10-17 15:42:43 -07003287 for (const ComposerState& state : states) {
3288 const layer_state_t& s = state.state;
3289 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3290 continue;
3291 }
3292 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003293 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003294 }
3295 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003296 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003297}
3298
Valerie Hau9dab9732019-08-20 09:29:25 -07003299void SurfaceFlinger::setTransactionState(
3300 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3301 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3302 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3303 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003304 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003305
Valerie Haubc6ddb12019-03-08 11:10:15 -08003306 const int64_t postTime = systemTime();
3307
Robert Carr14167e02019-02-13 13:50:55 -08003308 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3309
Mathias Agopian698c0872011-06-28 19:09:31 -07003310 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003311
Marissa Wall713b63f2018-10-17 15:42:43 -07003312 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003313 auto itr = mTransactionQueues.find(applyToken);
3314 // if this is an animation frame, wait until prior animation frame has
3315 // been applied by SF
3316 if (flags & eAnimation) {
3317 while (itr != mTransactionQueues.end()) {
3318 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3319 if (CC_UNLIKELY(err != NO_ERROR)) {
3320 ALOGW_IF(err == TIMED_OUT,
3321 "setTransactionState timed out "
3322 "waiting for animation frame to apply");
3323 break;
3324 }
3325 itr = mTransactionQueues.find(applyToken);
3326 }
3327 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003328
3329 // Expected present time is computed and cached on invalidate, so it may be stale.
3330 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3331 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003332 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003333 uncacheBuffer, postTime, privileged,
3334 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003335 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003336 return;
3337 }
3338
Valerie Haubc6ddb12019-03-08 11:10:15 -08003339 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003340 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3341 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003342}
3343
Valerie Hau9dab9732019-08-20 09:29:25 -07003344void SurfaceFlinger::applyTransactionState(
3345 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3346 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3347 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3348 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3349 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003350 uint32_t transactionFlags = 0;
3351
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003352 if (flags & eAnimation) {
3353 // For window updates that are part of an animation we must wait for
3354 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003355 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003356 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003357 if (CC_UNLIKELY(err != NO_ERROR)) {
3358 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003359 // caller after a few seconds.
3360 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3361 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003362 mAnimTransactionPending = false;
3363 break;
3364 }
3365 }
3366 }
3367
chaviwca27f252018-02-06 16:46:39 -08003368 for (const DisplayState& display : displays) {
3369 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003370 }
3371
Valerie Hau9dab9732019-08-20 09:29:25 -07003372 // start and end registration for listeners w/ no surface so they can get their callback. Note
3373 // that listeners with SurfaceControls will start registration during setClientStateLocked
3374 // below.
3375 for (const auto& listener : listenerCallbacks) {
3376 mTransactionCompletedThread.startRegistration(listener);
3377 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003378 }
3379
Valerie Hau9dab9732019-08-20 09:29:25 -07003380 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003381 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003382 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003383 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3384 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003385 }
3386
Valerie Hau9dab9732019-08-20 09:29:25 -07003387 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003388 mTransactionCompletedThread.endRegistration(listenerCallback);
3389 }
3390
Marissa Walle2ffb422018-10-12 11:33:52 -07003391 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003392 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003393 mTransactionCompletedThread.sendCallbacks();
3394 }
3395 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003396
chaviw273171b2018-12-26 11:46:30 -08003397 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3398
Marissa Wall947d34e2019-03-29 14:03:53 -07003399 if (uncacheBuffer.isValid()) {
3400 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003401 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003402 }
3403
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003404 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3405 // anyway. This can be used as a flush mechanism for previous async transactions.
3406 // Empty animation transaction can be used to simulate back-pressure, so also force a
3407 // transaction for empty animation transactions.
3408 if (transactionFlags == 0 &&
3409 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003410 transactionFlags = eTransactionNeeded;
3411 }
3412
Marissa Wall06255332019-03-27 13:48:27 -07003413 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3414 // so we don't have to wake up again next frame to preform an uneeded traversal.
3415 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3416 transactionFlags = transactionFlags & (~eTraversalNeeded);
3417 mTraversalNeededMainThread = true;
3418 }
3419
Mathias Agopian386aa982011-11-07 21:58:03 -08003420 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003421 if (mInterceptor->isEnabled()) {
3422 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003423 }
Irvel468051e2016-06-13 16:44:44 -07003424
Mathias Agopian386aa982011-11-07 21:58:03 -08003425 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003426 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3427 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003428 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003429
3430 // if this is a synchronous transaction, wait for it to take effect
3431 // before returning.
3432 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003433 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003434 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003435 if (flags & eAnimation) {
3436 mAnimTransactionPending = true;
3437 }
chaviw4fe36852019-04-15 16:25:49 -07003438 if (mPendingInputWindowCommands.syncInputWindows) {
3439 mPendingSyncInputWindows = true;
3440 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003441
3442 // applyTransactionState can be called by either the main SF thread or by
3443 // another process through setTransactionState. While a given process may wish
3444 // to wait on synchronous transactions, the main SF thread should never
3445 // be blocked. Therefore, we only wait if isMainThread is false.
3446 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003447 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3448 if (CC_UNLIKELY(err != NO_ERROR)) {
3449 // just in case something goes wrong in SF, return to the
3450 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003451 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3452 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003453 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003454 break;
3455 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003456 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003457 }
3458}
3459
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003460uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3461 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3462 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003463
Mathias Agopiane57f2922012-08-09 16:29:12 -07003464 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003465 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3466
3467 const uint32_t what = s.what;
3468 if (what & DisplayState::eSurfaceChanged) {
3469 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3470 state.surface = s.surface;
3471 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003472 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003473 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003474 if (what & DisplayState::eLayerStackChanged) {
3475 if (state.layerStack != s.layerStack) {
3476 state.layerStack = s.layerStack;
3477 flags |= eDisplayTransactionNeeded;
3478 }
3479 }
3480 if (what & DisplayState::eDisplayProjectionChanged) {
3481 if (state.orientation != s.orientation) {
3482 state.orientation = s.orientation;
3483 flags |= eDisplayTransactionNeeded;
3484 }
3485 if (state.frame != s.frame) {
3486 state.frame = s.frame;
3487 flags |= eDisplayTransactionNeeded;
3488 }
3489 if (state.viewport != s.viewport) {
3490 state.viewport = s.viewport;
3491 flags |= eDisplayTransactionNeeded;
3492 }
3493 }
3494 if (what & DisplayState::eDisplaySizeChanged) {
3495 if (state.width != s.width) {
3496 state.width = s.width;
3497 flags |= eDisplayTransactionNeeded;
3498 }
3499 if (state.height != s.height) {
3500 state.height = s.height;
3501 flags |= eDisplayTransactionNeeded;
3502 }
3503 }
3504
Mathias Agopiane57f2922012-08-09 16:29:12 -07003505 return flags;
3506}
3507
Robert Carr14167e02019-02-13 13:50:55 -08003508bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003509 IPCThreadState* ipc = IPCThreadState::self();
3510 const int pid = ipc->getCallingPid();
3511 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003512 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003513 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003514 return false;
3515 }
3516 return true;
3517}
3518
Marissa Wall3dad52d2019-03-22 14:03:19 -07003519uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003520 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3521 bool privileged,
3522 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003523 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003524
Valerie Hau9dab9732019-08-20 09:29:25 -07003525 for (auto& listener : s.listeners) {
3526 // note that startRegistration will not re-register if the listener has
3527 // already be registered for a prior surface control
3528 mTransactionCompletedThread.startRegistration(listener);
3529 listenerCallbacks.insert(listener);
3530 }
3531
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003532 sp<Layer> layer = nullptr;
3533 if (s.surface) {
3534 layer = fromHandle(s.surface);
3535 } else {
3536 // The client may provide us a null handle. Treat it as if the layer was removed.
3537 ALOGW("Attempt to set client state with a null layer handle");
3538 }
chaviw8b3871a2017-11-01 17:41:01 -07003539 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003540 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003541 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003542 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003543 }
chaviw8b3871a2017-11-01 17:41:01 -07003544 return 0;
3545 }
3546
chaviw8b3871a2017-11-01 17:41:01 -07003547 uint32_t flags = 0;
3548
Garfield Tan8a3083e2018-12-03 13:21:07 -08003549 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003550
3551 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3552 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003553 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003554 layer->pushPendingState();
3555 }
3556
Valerie Hau871d6352020-01-29 08:44:02 -08003557 // Only set by BLAST adapter layers
3558 if (what & layer_state_t::eProducerDisconnect) {
3559 layer->onDisconnect();
3560 }
3561
chaviw8b3871a2017-11-01 17:41:01 -07003562 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003563 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003564 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003565 }
chaviw8b3871a2017-11-01 17:41:01 -07003566 }
3567 if (what & layer_state_t::eLayerChanged) {
3568 // NOTE: index needs to be calculated before we update the state
3569 const auto& p = layer->getParent();
3570 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003571 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003572 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003573 mCurrentState.layersSortedByZ.removeAt(idx);
3574 mCurrentState.layersSortedByZ.add(layer);
3575 // we need traversal (state changed)
3576 // AND transaction (list changed)
3577 flags |= eTransactionNeeded|eTraversalNeeded;
3578 }
chaviw8b3871a2017-11-01 17:41:01 -07003579 } else {
3580 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003581 flags |= eTransactionNeeded|eTraversalNeeded;
3582 }
3583 }
chaviw8b3871a2017-11-01 17:41:01 -07003584 }
3585 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003586 // NOTE: index needs to be calculated before we update the state
3587 const auto& p = layer->getParent();
3588 if (p == nullptr) {
3589 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3590 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3591 mCurrentState.layersSortedByZ.removeAt(idx);
3592 mCurrentState.layersSortedByZ.add(layer);
3593 // we need traversal (state changed)
3594 // AND transaction (list changed)
3595 flags |= eTransactionNeeded|eTraversalNeeded;
3596 }
3597 } else {
3598 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3599 flags |= eTransactionNeeded|eTraversalNeeded;
3600 }
chaviw8b3871a2017-11-01 17:41:01 -07003601 }
3602 }
3603 if (what & layer_state_t::eSizeChanged) {
3604 if (layer->setSize(s.w, s.h)) {
3605 flags |= eTraversalNeeded;
3606 }
3607 }
3608 if (what & layer_state_t::eAlphaChanged) {
3609 if (layer->setAlpha(s.alpha))
3610 flags |= eTraversalNeeded;
3611 }
3612 if (what & layer_state_t::eColorChanged) {
3613 if (layer->setColor(s.color))
3614 flags |= eTraversalNeeded;
3615 }
Peiyong Lind3788632018-09-18 16:01:31 -07003616 if (what & layer_state_t::eColorTransformChanged) {
3617 if (layer->setColorTransform(s.colorTransform)) {
3618 flags |= eTraversalNeeded;
3619 }
3620 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003621 if (what & layer_state_t::eBackgroundColorChanged) {
3622 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3623 flags |= eTraversalNeeded;
3624 }
3625 }
chaviw8b3871a2017-11-01 17:41:01 -07003626 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003627 // TODO: b/109894387
3628 //
3629 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3630 // rotation. To see the problem observe that if we have a square parent, and a child
3631 // of the same size, then we rotate the child 45 degrees around it's center, the child
3632 // must now be cropped to a non rectangular 8 sided region.
3633 //
3634 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3635 // private API, and the WindowManager only uses rotation in one case, which is on a top
3636 // level layer in which cropping is not an issue.
3637 //
3638 // However given that abuse of rotation matrices could lead to surfaces extending outside
3639 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3640 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3641 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003642 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003643 flags |= eTraversalNeeded;
3644 }
3645 if (what & layer_state_t::eTransparentRegionChanged) {
3646 if (layer->setTransparentRegionHint(s.transparentRegion))
3647 flags |= eTraversalNeeded;
3648 }
3649 if (what & layer_state_t::eFlagsChanged) {
3650 if (layer->setFlags(s.flags, s.mask))
3651 flags |= eTraversalNeeded;
3652 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003653 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003654 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003655 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003656 if (what & layer_state_t::eCornerRadiusChanged) {
3657 if (layer->setCornerRadius(s.cornerRadius))
3658 flags |= eTraversalNeeded;
3659 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003660 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003661 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3662 }
chaviw8b3871a2017-11-01 17:41:01 -07003663 if (what & layer_state_t::eLayerStackChanged) {
3664 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3665 // We only allow setting layer stacks for top level layers,
3666 // everything else inherits layer stack from its parent.
3667 if (layer->hasParent()) {
3668 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003669 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003670 } else if (idx < 0) {
3671 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003672 "that also does not appear in the top level layer list. Something"
3673 " has gone wrong.",
3674 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003675 } else if (layer->setLayerStack(s.layerStack)) {
3676 mCurrentState.layersSortedByZ.removeAt(idx);
3677 mCurrentState.layersSortedByZ.add(layer);
3678 // we need traversal (state changed)
3679 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003680 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003681 }
3682 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003683 if (what & layer_state_t::eDeferTransaction_legacy) {
3684 if (s.barrierHandle_legacy != nullptr) {
3685 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3686 } else if (s.barrierGbp_legacy != nullptr) {
3687 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003688 if (authenticateSurfaceTextureLocked(gbp)) {
3689 const auto& otherLayer =
3690 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003691 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003692 } else {
3693 ALOGE("Attempt to defer transaction to to an"
3694 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003695 }
3696 }
chaviw8b3871a2017-11-01 17:41:01 -07003697 // We don't trigger a traversal here because if no other state is
3698 // changed, we don't want this to cause any more work
3699 }
chaviw8b3871a2017-11-01 17:41:01 -07003700 if (what & layer_state_t::eReparentChildren) {
3701 if (layer->reparentChildren(s.reparentHandle)) {
3702 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003703 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003704 }
chaviw8b3871a2017-11-01 17:41:01 -07003705 if (what & layer_state_t::eDetachChildren) {
3706 layer->detachChildren();
3707 }
3708 if (what & layer_state_t::eOverrideScalingModeChanged) {
3709 layer->setOverrideScalingMode(s.overrideScalingMode);
3710 // We don't trigger a traversal here because if no other state is
3711 // changed, we don't want this to cause any more work
3712 }
Marissa Wall61c58622018-07-18 10:12:20 -07003713 if (what & layer_state_t::eTransformChanged) {
3714 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3715 }
3716 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3717 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3718 flags |= eTraversalNeeded;
3719 }
3720 if (what & layer_state_t::eCropChanged) {
3721 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3722 }
Marissa Wall861616d2018-10-22 12:52:23 -07003723 if (what & layer_state_t::eFrameChanged) {
3724 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3725 }
Marissa Wall61c58622018-07-18 10:12:20 -07003726 if (what & layer_state_t::eAcquireFenceChanged) {
3727 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3728 }
3729 if (what & layer_state_t::eDataspaceChanged) {
3730 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3731 }
3732 if (what & layer_state_t::eHdrMetadataChanged) {
3733 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3734 }
3735 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3736 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3737 }
3738 if (what & layer_state_t::eApiChanged) {
3739 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3740 }
3741 if (what & layer_state_t::eSidebandStreamChanged) {
3742 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3743 }
Robert Carr720e5062018-07-30 17:45:14 -07003744 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003745 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003746 layer->setInputInfo(s.inputInfo);
3747 flags |= eTraversalNeeded;
3748 } else {
3749 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3750 }
Robert Carr720e5062018-07-30 17:45:14 -07003751 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003752 if (what & layer_state_t::eMetadataChanged) {
3753 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3754 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003755 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3756 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3757 flags |= eTraversalNeeded;
3758 }
3759 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003760 if (what & layer_state_t::eShadowRadiusChanged) {
3761 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3762 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003763 if (what & layer_state_t::eFrameRateSelectionPriority) {
3764 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3765 flags |= eTraversalNeeded;
3766 }
3767 }
Steven Thomas3172e202020-01-06 19:25:30 -08003768 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003769 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3770 "SurfaceFlinger::setClientStateLocked") &&
3771 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3772 Layer::FrameRate::convertCompatibility(
3773 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003774 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003775 }
Steven Thomas3172e202020-01-06 19:25:30 -08003776 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003777 // This has to happen after we reparent children because when we reparent to null we remove
3778 // child layers from current state and remove its relative z. If the children are reparented in
3779 // the same transaction, then we have to make sure we reparent the children first so we do not
3780 // lose its relative z order.
3781 if (what & layer_state_t::eReparent) {
3782 bool hadParent = layer->hasParent();
3783 if (layer->reparent(s.parentHandleForChild)) {
3784 if (!hadParent) {
3785 mCurrentState.layersSortedByZ.remove(layer);
3786 }
3787 flags |= eTransactionNeeded | eTraversalNeeded;
3788 }
3789 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003790 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003791 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3792 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003793 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3794 }
3795 }
Marissa Wall78b72202019-03-15 14:58:34 -07003796 bool bufferChanged = what & layer_state_t::eBufferChanged;
3797 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3798 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003799 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003800 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003801 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3802 if (success) {
3803 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3804 success = ClientCache::getInstance()
3805 .registerErasedRecipient(s.cachedBuffer,
3806 wp<ClientCache::ErasedRecipient>(this));
3807 if (!success) {
3808 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3809 }
3810 }
Marissa Wall78b72202019-03-15 14:58:34 -07003811 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003812 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003813 } else if (bufferChanged) {
3814 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003815 }
Marissa Wall78b72202019-03-15 14:58:34 -07003816 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003817 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3818 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003819 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003820 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003821 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003822 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3823 // Do not put anything that updates layer state or modifies flags after
3824 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003825 return flags;
3826}
3827
chaviw273171b2018-12-26 11:46:30 -08003828uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3829 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003830 if (inputWindowCommands.syncInputWindows) {
3831 flags |= eTraversalNeeded;
3832 }
3833
Vishnu Nairec0ab382019-02-13 15:32:56 -08003834 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003835 return flags;
3836}
3837
chaviwfe94a222019-08-21 13:52:59 -07003838status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3839 sp<IBinder>* outHandle) {
3840 if (!mirrorFromHandle) {
3841 return NAME_NOT_FOUND;
3842 }
3843
3844 sp<Layer> mirrorLayer;
3845 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003846 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003847
3848 {
3849 Mutex::Autolock _l(mStateLock);
3850 mirrorFrom = fromHandle(mirrorFromHandle);
3851 if (!mirrorFrom) {
3852 return NAME_NOT_FOUND;
3853 }
3854
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003855 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3856 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003857 if (result != NO_ERROR) {
3858 return result;
3859 }
3860
3861 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3862 }
3863
3864 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3865}
3866
Marissa Wall2d814fb2019-04-09 18:52:57 +00003867status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3868 uint32_t h, PixelFormat format, uint32_t flags,
3869 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003870 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003871 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3872 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003873 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003874 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003875 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003876 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003877 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003878
Robert Carrc0df3122019-04-11 13:18:21 -07003879 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3880 "Expected only one of parentLayer or parentHandle to be non-null. "
3881 "Programmer error?");
3882
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003883 status_t result = NO_ERROR;
3884
3885 sp<Layer> layer;
3886
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003887 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003888
Evan Roskya1f1e152019-01-24 16:17:46 -08003889 bool primaryDisplayOnly = false;
3890
3891 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3892 // TODO b/64227542
3893 if (metadata.has(METADATA_WINDOW_TYPE)) {
3894 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3895 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003896 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003897 primaryDisplayOnly = true;
3898 }
3899 }
3900
Mathias Agopian3165cc22012-08-08 19:42:09 -07003901 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003902 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003903 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3904 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003905
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003906 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003907 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003908 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003909 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003910 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003911 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003912 // check if buffer size is set for color layer.
3913 if (w > 0 || h > 0) {
3914 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3915 int(w), int(h));
3916 return BAD_VALUE;
3917 }
3918
Vishnu Nairfa247b12020-02-11 08:58:26 -08003919 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3920 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003921 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003922 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003923 // check if buffer size is set for container layer.
3924 if (w > 0 || h > 0) {
3925 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3926 int(w), int(h));
3927 return BAD_VALUE;
3928 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003929 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3930 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003931 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003932 default:
3933 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003934 break;
3935 }
3936
Dan Stoza7d89d062015-04-30 13:29:25 -07003937 if (result != NO_ERROR) {
3938 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003939 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003940
Evan Roskya1f1e152019-01-24 16:17:46 -08003941 if (primaryDisplayOnly) {
3942 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003943 }
3944
Robert Carrb89ea9d2018-12-10 13:01:14 -08003945 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003946 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3947 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003948 if (result != NO_ERROR) {
3949 return result;
3950 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003951 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003952
3953 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003954 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003955}
3956
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003957std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3958 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003959
3960 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003961 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003962
Dan Stoza436ccf32018-06-21 12:10:12 -07003963 // Grab the state lock since we're accessing mCurrentState
3964 Mutex::Autolock lock(mStateLock);
3965
Cody Northropbc755282017-03-31 12:00:08 -06003966 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003967 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003968 while (matchFound) {
3969 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003970 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003971 if (layer->getName() == uniqueName) {
3972 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003973 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003974 }
3975 });
3976 }
3977
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003978 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003979 return uniqueName;
3980}
3981
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003982status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003983 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003984 LayerMetadata metadata, PixelFormat& format,
3985 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003986 sp<IGraphicBufferProducer>* gbp,
3987 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003988 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003989 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003990 case PIXEL_FORMAT_TRANSPARENT:
3991 case PIXEL_FORMAT_TRANSLUCENT:
3992 format = PIXEL_FORMAT_RGBA_8888;
3993 break;
3994 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003995 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003996 break;
3997 }
3998
chaviwb4c6e582019-08-16 14:35:07 -07003999 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004000 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004001 args.textureName = getNewTexture();
4002 {
4003 // Grab the SF state lock during this since it's the only safe way to access
4004 // RenderEngine when creating a BufferLayerConsumer
4005 // TODO: Check if this lock is still needed here
4006 Mutex::Autolock lock(mStateLock);
4007 layer = getFactory().createBufferQueueLayer(args);
4008 }
4009
Marissa Wallfd668622018-05-10 10:21:13 -07004010 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004011 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004012 *handle = layer->getHandle();
4013 *gbp = layer->getProducer();
4014 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004015 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004016
Marissa Wallfd668622018-05-10 10:21:13 -07004017 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004018 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004019}
4020
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004021status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004022 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004023 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07004024 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004025 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004026 args.displayDevice = getDefaultDisplayDevice();
4027 args.textureName = getNewTexture();
4028 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07004029 if (outTransformHint) {
4030 *outTransformHint = layer->getTransformHint();
4031 }
Marissa Wall61c58622018-07-18 10:12:20 -07004032 *handle = layer->getHandle();
4033 *outLayer = layer;
4034
4035 return NO_ERROR;
4036}
4037
Vishnu Nairfa247b12020-02-11 08:58:26 -08004038status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4039 uint32_t h, uint32_t flags, LayerMetadata metadata,
4040 sp<IBinder>* handle, sp<Layer>* outLayer) {
4041 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004042 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004043 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004044 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004045}
4046
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004047status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004048 uint32_t w, uint32_t h, uint32_t flags,
4049 LayerMetadata metadata, sp<IBinder>* handle,
4050 sp<Layer>* outLayer) {
4051 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004052 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004053 *handle = (*outLayer)->getHandle();
4054 return NO_ERROR;
4055}
4056
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004057void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004058 mLayersPendingRemoval.add(layer);
4059 mLayersRemoved = true;
4060 setTransactionFlags(eTransactionNeeded);
4061}
4062
Robert Carr695d5282018-12-18 15:27:58 -08004063void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004064{
Robert Carr2e102c92018-10-23 12:11:15 -07004065 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004066 // If a layer has a parent, we allow it to out-live it's handle
4067 // with the idea that the parent holds a reference and will eventually
4068 // be cleaned up. However no one cleans up the top-level so we do so
4069 // here.
4070 if (layer->getParent() == nullptr) {
4071 mCurrentState.layersSortedByZ.remove(layer);
4072 }
4073 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004074
4075 auto it = mLayersByLocalBinderToken.begin();
4076 while (it != mLayersByLocalBinderToken.end()) {
4077 if (it->second == layer) {
4078 it = mLayersByLocalBinderToken.erase(it);
4079 } else {
4080 it++;
4081 }
4082 }
4083
Robert Carr695d5282018-12-18 15:27:58 -08004084 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004085}
4086
Mathias Agopianb60314a2012-04-10 22:09:54 -07004087// ---------------------------------------------------------------------------
4088
Andy McFadden13a082e2012-08-24 10:16:42 -07004089void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004090 const auto display = getDefaultDisplayDeviceLocked();
4091 if (!display) return;
4092
4093 const sp<IBinder> token = display->getDisplayToken().promote();
4094 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004095
Jesse Hall01e29052013-02-19 16:13:35 -08004096 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004097 Vector<ComposerState> state;
4098 Vector<DisplayState> displays;
4099 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004100 d.what = DisplayState::eDisplayProjectionChanged |
4101 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004102 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004103 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004104 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004105 d.frame.makeInvalid();
4106 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004107 d.width = 0;
4108 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004109 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004110 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4111 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004112
Dominik Laskowskie9774092018-12-11 10:04:24 -08004113 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004114
Dominik Laskowski83b88212018-12-11 13:34:06 -08004115 const nsecs_t vsyncPeriod = getVsyncPeriod();
4116 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004117
Brian Andersond0010582017-03-07 13:20:31 -08004118 // Use phase of 0 since phase is not known.
4119 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004120 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004121 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004122}
4123
4124void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004125 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004126 postMessageAsync(
4127 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004128}
4129
Ady Abraham27c70212019-06-11 10:52:26 -07004130void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4131 if (mHWCVsyncState != enabled) {
4132 getHwComposer().setVsyncEnabled(displayId, enabled);
4133 mHWCVsyncState = enabled;
4134 }
4135}
4136
Dominik Laskowskie9774092018-12-11 10:04:24 -08004137void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004138 if (display->isVirtual()) {
4139 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004140 return;
4141 }
4142
Dominik Laskowski075d3172018-05-24 15:50:06 -07004143 const auto displayId = display->getId();
4144 LOG_ALWAYS_FATAL_IF(!displayId);
4145
Dominik Laskowski34157762018-10-31 13:07:19 -07004146 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004147
4148 int currentMode = display->getPowerMode();
4149 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004150 return;
4151 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004152
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004153 display->setPowerMode(mode);
4154
Lloyd Pique4dccc412018-01-22 17:21:36 -08004155 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004156 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004157 }
4158
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004159 if (currentMode == HWC_POWER_MODE_OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004160 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4161 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4162 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004163 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004164 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004165 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004166 mScheduler->onScreenAcquired(mAppConnectionHandle);
4167 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004168 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004169
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004170 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004171 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004172 repaintEverything();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004173 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004174 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004175 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4176 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004177 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004178 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004179 mScheduler->disableHardwareVsync(true);
4180 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004181 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004182
Ady Abraham27c70212019-06-11 10:52:26 -07004183 // Make sure HWVsync is disabled before turning off the display
4184 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4185
Dominik Laskowski075d3172018-05-24 15:50:06 -07004186 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004187 mVisibleRegionsDirty = true;
4188 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004189 } else if (mode == HWC_POWER_MODE_DOZE ||
4190 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004191 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004192 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004193 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004194 mScheduler->onScreenAcquired(mAppConnectionHandle);
4195 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004196 }
4197 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4198 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004199 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004200 mScheduler->disableHardwareVsync(true);
4201 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004202 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004203 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004204 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004205 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004206 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004207 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004208
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004209 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004210 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004211 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004212 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004213 }
4214
Dominik Laskowski34157762018-10-31 13:07:19 -07004215 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004216}
4217
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004218void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004219 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004220 const auto display = getDisplayDevice(displayToken);
4221 if (!display) {
4222 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4223 displayToken.get());
4224 } else if (display->isVirtual()) {
4225 ALOGW("Attempt to set power mode %d for virtual display", mode);
4226 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004227 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004228 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004229 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004230}
4231
4232// ---------------------------------------------------------------------------
4233
Dominik Laskowskic2867142019-01-21 11:33:38 -08004234status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4235 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004236 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004237
Mathias Agopianbd115332013-04-18 16:41:04 -07004238 IPCThreadState* ipc = IPCThreadState::self();
4239 const int pid = ipc->getCallingPid();
4240 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004241
Mathias Agopianbd115332013-04-18 16:41:04 -07004242 if ((uid != AID_SHELL) &&
4243 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004244 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4245 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004246 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004247 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004248 // (this would indicate SF is stuck, but we want to be able to
4249 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004250 status_t err = mStateLock.timedLock(s2ns(1));
4251 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004252 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004253 StringAppendF(&result,
4254 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4255 "(no locks held)\n",
4256 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004257 }
4258
Dominik Laskowskic2867142019-01-21 11:33:38 -08004259 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004260 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004261 {"--dispsync"s,
4262 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004263 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004264 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4265 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4266 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4267 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4268 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4269 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004270 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004271 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4272 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004273
Dominik Laskowskic2867142019-01-21 11:33:38 -08004274 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004275
Dominik Laskowski46470112019-08-02 13:13:11 -07004276 const auto it = dumpers.find(flag);
4277 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004278 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004279 } else if (!asProto) {
4280 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004281 }
4282
Mathias Agopian9795c422009-08-26 16:36:26 -07004283 if (locked) {
4284 mStateLock.unlock();
4285 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004286
Dominik Laskowski46470112019-08-02 13:13:11 -07004287 if (it == dumpers.end()) {
4288 const LayersProto layersProto = dumpProtoFromMainThread();
4289 if (asProto) {
4290 result.append(layersProto.SerializeAsString());
4291 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004292 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004293 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4294 result.append(LayerProtoParser::layerTreeToString(layerTree));
4295 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004296 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004297 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004298 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004299 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004300 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004301 return NO_ERROR;
4302}
4303
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004304status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4305 if (asProto && mTracing.isEnabled()) {
4306 mTracing.writeToFileAsync();
4307 }
4308
4309 return doDump(fd, DumpArgs(), asProto);
4310}
4311
Dominik Laskowskic2867142019-01-21 11:33:38 -08004312void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004313 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004314 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004315}
4316
Dominik Laskowskic2867142019-01-21 11:33:38 -08004317void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004318 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004319
Dominik Laskowskic2867142019-01-21 11:33:38 -08004320 if (args.size() > 1) {
4321 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004322 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004323 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004324 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004325 }
Robert Carr2047fae2016-11-28 14:09:09 -08004326 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004327 } else {
4328 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004329 }
4330}
4331
Dominik Laskowskic2867142019-01-21 11:33:38 -08004332void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004333 const bool clearAll = args.size() < 2;
4334 const auto name = clearAll ? String8() : String8(args[1]);
4335
Edgar Arriaga844fa672020-01-16 14:21:42 -08004336 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004337 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004338 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004339 }
Robert Carr2047fae2016-11-28 14:09:09 -08004340 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004341
Svetoslavd85084b2014-03-20 10:28:31 -07004342 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004343}
4344
Dominik Laskowskic2867142019-01-21 11:33:38 -08004345void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4346 mTimeStats->parseArgs(asProto, args, result);
4347}
4348
Jamie Gennis6547ff42013-07-16 20:12:42 -07004349// This should only be called from the main thread. Otherwise it would need
4350// the lock and should use mCurrentState rather than mDrawingState.
4351void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004352 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004353 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004354 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004355
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004356 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004357}
4358
Yiwei Zhang5434a782018-12-05 18:06:32 -08004359void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004360 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004361
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004362 if (isLayerTripleBufferingDisabled())
4363 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004364
Yiwei Zhang5434a782018-12-05 18:06:32 -08004365 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4366 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4367 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4368 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4369 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4370 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004371 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004372}
4373
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004374void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004375 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004376
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004377 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004378 result.append("\n");
4379
Ady Abraham9e16a482019-12-03 17:19:41 -08004380 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004381 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004382 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004383 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004384
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004385 HwcConfigIndexType defaultConfig;
4386 float minFps, maxFps;
4387 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004388 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004389 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004390 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004391 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004392 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4393 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004394
Ana Krulecc2870422019-01-29 19:00:58 -08004395 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004396}
4397
Yiwei Zhang5434a782018-12-05 18:06:32 -08004398void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4399 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004400 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4401 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004402 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004403 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004404 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004405 }
David Sodman4a36e932017-11-07 14:29:47 -08004406 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004407 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004408 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004409 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4410 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004411}
4412
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004413void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4414 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004415 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4416 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004417 for (const auto& segment : history) {
4418 if (!segment.usedThirdBuffer) {
4419 stats.twoBufferTime += segment.totalTime;
4420 }
4421 if (segment.occupancyAverage < 1.0f) {
4422 stats.doubleBufferedTime += segment.totalTime;
4423 } else if (segment.occupancyAverage < 2.0f) {
4424 stats.tripleBufferedTime += segment.totalTime;
4425 }
4426 ++stats.numSegments;
4427 stats.totalTime += segment.totalTime;
4428 }
4429}
4430
Yiwei Zhang5434a782018-12-05 18:06:32 -08004431void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4432 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004433
4434 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4435 const size_t count = currentLayers.size();
4436 for (size_t i=0 ; i<count ; i++) {
4437 currentLayers[i]->dumpFrameEvents(result);
4438 }
4439}
4440
Yiwei Zhang5434a782018-12-05 18:06:32 -08004441void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004442 result.append("Buffering stats:\n");
4443 result.append(" [Layer name] <Active time> <Two buffer> "
4444 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004445 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004446 typedef std::tuple<std::string, float, float, float> BufferTuple;
4447 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004448 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004449 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004450 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004451 if (stats.numSegments == 0) {
4452 continue;
4453 }
4454 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4455 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4456 stats.totalTime;
4457 float doubleBufferRatio = static_cast<float>(
4458 stats.doubleBufferedTime) / stats.totalTime;
4459 float tripleBufferRatio = static_cast<float>(
4460 stats.tripleBufferedTime) / stats.totalTime;
4461 sorted.insert({activeTime, {name, twoBufferRatio,
4462 doubleBufferRatio, tripleBufferRatio}});
4463 }
4464 for (const auto& sortedPair : sorted) {
4465 float activeTime = sortedPair.first;
4466 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004467 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4468 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004469 }
4470 result.append("\n");
4471}
4472
Yiwei Zhang5434a782018-12-05 18:06:32 -08004473void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004474 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004475 const auto displayId = display->getId();
4476 if (!displayId) {
4477 continue;
4478 }
4479 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004480 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004481 continue;
4482 }
4483
Yiwei Zhang5434a782018-12-05 18:06:32 -08004484 StringAppendF(&result,
4485 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4486 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004487 uint8_t port;
4488 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004489 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004490 result.append("no identification data\n");
4491 continue;
4492 }
4493
4494 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004495 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004496 continue;
4497 }
4498
4499 const auto edid = parseEdid(data);
4500 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004501 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004502 continue;
4503 }
4504
Yiwei Zhang5434a782018-12-05 18:06:32 -08004505 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004506 result.append(edid->displayName.data(), edid->displayName.length());
4507 result.append("\"\n");
4508 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004509}
4510
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004511void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4512 std::string& result) const {
4513 hwc2_display_t hwcDisplayId;
4514 uint8_t port;
4515 DisplayIdentificationData data;
4516
4517 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4518 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4519 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4520 }
4521}
4522
Yiwei Zhang5434a782018-12-05 18:06:32 -08004523void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004524 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004525 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4526 StringAppendF(&result, "DisplayColorSetting: %s\n",
4527 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004528
4529 // TODO: print out if wide-color mode is active or not
4530
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004531 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004532 const auto displayId = display->getId();
4533 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004534 continue;
4535 }
4536
Yiwei Zhang5434a782018-12-05 18:06:32 -08004537 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004538 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004539 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004540 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004541 }
4542
Lloyd Pique32cbe282018-10-19 13:09:22 -07004543 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004544 StringAppendF(&result, " Current color mode: %s (%d)\n",
4545 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004546 }
4547 result.append("\n");
4548}
4549
Alec Mouri5793c7d2020-03-10 19:55:50 -07004550LayersProto SurfaceFlinger::dumpDrawingStateProto(
4551 uint32_t traceFlags, const sp<const DisplayDevice>& displayDevice) const {
chaviw1d044282017-09-27 12:19:28 -07004552 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004553 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Alec Mouri5793c7d2020-03-10 19:55:50 -07004554 layer->writeToProto(layersProto, traceFlags, displayDevice);
chaviw08f3cb22020-01-13 13:17:21 -08004555 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004556
chaviw1d044282017-09-27 12:19:28 -07004557 return layersProto;
4558}
4559
Alec Mouri6b9e9912020-01-21 10:50:24 -08004560void SurfaceFlinger::dumpHwc(std::string& result) const {
4561 getHwComposer().dump(result);
4562}
4563
Vishnu Nair0f085c62019-08-30 08:49:12 -07004564void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4565 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4566 // it.
4567 LayerProto* rootProto = layersProto.add_layers();
4568 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4569 rootProto->set_id(offscreenRootLayerId);
4570 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004571 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004572
4573 for (Layer* offscreenLayer : mOffscreenLayers) {
4574 // Add layer as child of the fake root
4575 rootProto->add_children(offscreenLayer->sequence);
4576
4577 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004578 LayerProto* layerProto =
4579 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004580 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004581 }
4582}
4583
Vishnu Nair8406fd72019-07-30 11:29:31 -07004584LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4585 LayersProto layersProto;
Alec Mouri5793c7d2020-03-10 19:55:50 -07004586 postMessageSync(new LambdaMessage([&]() {
4587 const auto& displayDevice = getDefaultDisplayDeviceLocked();
4588 layersProto = dumpDrawingStateProto(traceFlags, displayDevice);
4589 }));
Vishnu Nair8406fd72019-07-30 11:29:31 -07004590 return layersProto;
4591}
4592
Vishnu Nair0f085c62019-08-30 08:49:12 -07004593void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4594 result.append("Offscreen Layers:\n");
4595 postMessageSync(new LambdaMessage([&]() {
4596 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004597 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004598 layer->dumpCallingUidPid(result);
4599 });
4600 }
4601 }));
4602}
4603
Dominik Laskowskic2867142019-01-21 11:33:38 -08004604void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4605 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004606 Colorizer colorizer(colorize);
4607
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004608 // figure out if we're stuck somewhere
4609 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004610 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004611 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4612
4613 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004614 * Dump library configuration.
4615 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004616
4617 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004618 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004619 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004620 appendSfConfigString(result);
4621 appendUiConfigString(result);
4622 appendGuiConfigString(result);
4623 result.append("\n");
4624
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004625 result.append("\nDisplay identification data:\n");
4626 dumpDisplayIdentificationData(result);
4627
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004628 result.append("\nWide-Color information:\n");
4629 dumpWideColorInfo(result);
4630
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004631 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004632 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004633 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004634 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004635 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004636
Andy McFadden41d67d72014-04-25 16:58:34 -07004637 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004638 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004639 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004640 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004641 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004642
Dan Stozab90cf072015-03-05 11:05:59 -08004643 dumpStaticScreenStats(result);
4644 result.append("\n");
4645
Alec Mouri40189b02019-03-05 15:07:54 -08004646 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4647 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4648 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004649
Dan Stozae77c7662016-05-13 11:37:28 -07004650 dumpBufferingStats(result);
4651
Andy McFadden4803b742012-09-24 19:07:20 -07004652 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004653 * Dump the visible layer list
4654 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004655 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004656 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004657 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4658 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004659 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004660
Chia-I Wu2f884132018-09-13 15:17:58 -07004661 {
Lloyd Pique207def92019-02-28 16:09:52 -08004662 StringAppendF(&result, "Composition layers\n");
4663 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004664 auto* compositionState = layer->getCompositionState();
4665 if (!compositionState) return;
4666
4667 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4668 layer->getDebugName() ? layer->getDebugName()
4669 : "<unknown>");
4670 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004671 });
4672 }
4673
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004674 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004675 * Dump Display state
4676 */
4677
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004678 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004679 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004680 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004681 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004682 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004683 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004684 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004685
4686 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004687 * Dump CompositionEngine state
4688 */
4689
4690 mCompositionEngine->dump(result);
4691
4692 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004693 * Dump SurfaceFlinger global state
4694 */
4695
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004696 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004697 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004698 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004699
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004700 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004701
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004702 DebugEGLImageTracker::getInstance()->dump(result);
4703
Dominik Laskowski075d3172018-05-24 15:50:06 -07004704 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004705 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4706 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004707 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4708 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004709 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004710 StringAppendF(&result,
4711 " transaction-flags : %08x\n"
4712 " gpu_to_cpu_unsupported : %d\n",
4713 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004714
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004715 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004716 displayId && getHwComposer().isConnected(*displayId)) {
4717 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004718 StringAppendF(&result,
4719 " refresh-rate : %f fps\n"
4720 " x-dpi : %f\n"
4721 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004722 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4723 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004724 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004725
Yiwei Zhang5434a782018-12-05 18:06:32 -08004726 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004727
Dan Stozae22aec72016-08-01 13:20:59 -07004728 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004729 * Tracing state
4730 */
4731 mTracing.dump(result);
4732 result.append("\n");
4733
4734 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004735 * HWC layer minidump
4736 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004737 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004738 const auto displayId = display->getId();
4739 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004740 continue;
4741 }
4742
Yiwei Zhang5434a782018-12-05 18:06:32 -08004743 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004744 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004745 const sp<DisplayDevice> displayDevice = display;
4746 mCurrentState.traverseInZOrder(
4747 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004748 result.append("\n");
4749 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004750
4751 /*
4752 * Dump HWComposer state
4753 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004754 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004755 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004756 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004757 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004758 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004759 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004760
4761 /*
4762 * Dump gralloc state
4763 */
4764 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4765 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004766
4767 /*
4768 * Dump VrFlinger state if in use.
4769 */
4770 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4771 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004772 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004773 result.append("\n");
4774 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004775
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004776 result.append(mTimeStats->miniDump());
4777 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004778}
4779
Chia-I Wu28f320b2018-05-03 11:02:56 -07004780void SurfaceFlinger::updateColorMatrixLocked() {
4781 mat4 colorMatrix;
4782 if (mGlobalSaturationFactor != 1.0f) {
4783 // Rec.709 luma coefficients
4784 float3 luminance{0.213f, 0.715f, 0.072f};
4785 luminance *= 1.0f - mGlobalSaturationFactor;
4786 mat4 saturationMatrix = mat4(
4787 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4788 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4789 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4790 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4791 );
4792 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4793 } else {
4794 colorMatrix = mClientColorMatrix * mDaltonizer();
4795 }
4796
4797 if (mCurrentState.colorMatrix != colorMatrix) {
4798 mCurrentState.colorMatrix = colorMatrix;
4799 mCurrentState.colorMatrixChanged = true;
4800 setTransactionFlags(eTransactionNeeded);
4801 }
4802}
4803
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004804status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004805#pragma clang diagnostic push
4806#pragma clang diagnostic error "-Wswitch-enum"
4807 switch (static_cast<ISurfaceComposerTag>(code)) {
4808 // These methods should at minimum make sure that the client requested
4809 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004810 case BOOT_FINISHED:
4811 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004812 case CREATE_DISPLAY:
4813 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004814 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004815 case GET_ANIMATION_FRAME_STATS:
4816 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004817 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004818 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004819 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004820 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4821 case SET_AUTO_LOW_LATENCY_MODE:
4822 case GET_GAME_CONTENT_TYPE_SUPPORT:
4823 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004824 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004825 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004826 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004827 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004828 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004829 case NOTIFY_POWER_HINT:
4830 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004831 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4832 IPCThreadState* ipc = IPCThreadState::self();
4833 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4834 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004835 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004836 }
Robert Carr1db73f62016-12-21 12:58:51 -08004837 return OK;
4838 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004839 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004840 IPCThreadState* ipc = IPCThreadState::self();
4841 const int pid = ipc->getCallingPid();
4842 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004843 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4844 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004845 return PERMISSION_DENIED;
4846 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004847 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004848 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004849 // Used by apps to hook Choreographer to SurfaceFlinger.
4850 case CREATE_DISPLAY_EVENT_CONNECTION:
4851 // The following calls are currently used by clients that do not
4852 // request necessary permissions. However, they do not expose any secret
4853 // information, so it is OK to pass them.
4854 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004855 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004856 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004857 case GET_PHYSICAL_DISPLAY_IDS:
4858 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004859 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004860 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004861 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004862 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004863 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004864 case GET_DISPLAY_STATS:
4865 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4866 // Calling setTransactionState is safe, because you need to have been
4867 // granted a reference to Client* and Handle* to do anything with it.
4868 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004869 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004870 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004871 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004872 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004873 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004874 // setFrameRate() is deliberately available for apps to call without any
4875 // special permissions.
4876 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004877 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4878 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004879 return OK;
4880 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004881 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004882 case CAPTURE_SCREEN:
4883 case ADD_REGION_SAMPLING_LISTENER:
4884 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004885 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004886 IPCThreadState* ipc = IPCThreadState::self();
4887 const int pid = ipc->getCallingPid();
4888 const int uid = ipc->getCallingUid();
4889 if ((uid != AID_GRAPHICS) &&
4890 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4891 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4892 return PERMISSION_DENIED;
4893 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004894 return OK;
4895 }
chaviw93df2ea2019-04-30 16:45:12 -07004896 case CAPTURE_SCREEN_BY_ID: {
4897 IPCThreadState* ipc = IPCThreadState::self();
4898 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004899 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004900 return OK;
4901 }
4902 return PERMISSION_DENIED;
4903 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004904 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004905
4906 // These codes are used for the IBinder protocol to either interrogate the recipient
4907 // side of the transaction for its canonical interface descriptor or to dump its state.
4908 // We let them pass by default.
4909 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4910 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4911 code == IBinder::SYSPROPS_TRANSACTION) {
4912 return OK;
4913 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004914 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004915 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004916 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004917 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4918 return OK;
4919 }
4920 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4921 return PERMISSION_DENIED;
4922#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004923}
4924
Ana Krulec13be8ad2018-08-21 02:43:56 +00004925status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4926 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004927 status_t credentialCheck = CheckTransactCodeCredentials(code);
4928 if (credentialCheck != OK) {
4929 return credentialCheck;
4930 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004931
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004932 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4933 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004934 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004935 IPCThreadState* ipc = IPCThreadState::self();
4936 const int uid = ipc->getCallingUid();
4937 if (CC_UNLIKELY(uid != AID_SYSTEM
4938 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004939 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004940 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004941 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004942 return PERMISSION_DENIED;
4943 }
4944 int n;
4945 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004946 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004947 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004948 return NO_ERROR;
4949 case 1002: // SHOW_UPDATES
4950 n = data.readInt32();
4951 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004952 invalidateHwcGeometry();
4953 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004954 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004955 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004956 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004957 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004958 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004959 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004960 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004961 setTransactionFlags(
4962 eTransactionNeeded|
4963 eDisplayTransactionNeeded|
4964 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004965 return NO_ERROR;
4966 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004967 case 1006:{ // send empty update
4968 signalRefresh();
4969 return NO_ERROR;
4970 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004971 case 1008: // toggle use of hw composer
4972 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004973 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004974 invalidateHwcGeometry();
4975 repaintEverything();
4976 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004977 case 1009: // toggle use of transform hint
4978 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004979 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004980 invalidateHwcGeometry();
4981 repaintEverything();
4982 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004983 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004984 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004985 reply->writeInt32(0);
4986 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004987 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004988 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004989 return NO_ERROR;
4990 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004991 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004992 if (!display) {
4993 return NAME_NOT_FOUND;
4994 }
4995
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004996 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004997 return NO_ERROR;
4998 }
4999 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005000 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005001 // daltonize
5002 n = data.readInt32();
5003 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005004 case 1:
5005 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5006 break;
5007 case 2:
5008 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5009 break;
5010 case 3:
5011 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5012 break;
5013 default:
5014 mDaltonizer.setType(ColorBlindnessType::None);
5015 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005016 }
5017 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005018 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005019 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005020 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005021 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005022
5023 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005024 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005025 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005026 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005027 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005028 // apply a color matrix
5029 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005030 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005031 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005032 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005033 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005034 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005035 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005036 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005037 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005038 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005039 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005040
5041 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5042 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005043 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005044 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5045 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5046 }
5047
Chia-I Wu28f320b2018-05-03 11:02:56 -07005048 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005049 return NO_ERROR;
5050 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005051 case 1016: { // Unused.
5052 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005053 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005054 case 1017: {
5055 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005056 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005057 return NO_ERROR;
5058 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005059 case 1018: { // Modify Choreographer's phase offset
5060 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005061 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005062 return NO_ERROR;
5063 }
5064 case 1019: { // Modify SurfaceFlinger's phase offset
5065 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005066 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005067 return NO_ERROR;
5068 }
Irvel468051e2016-06-13 16:44:44 -07005069 case 1020: { // Layer updates interceptor
5070 n = data.readInt32();
5071 if (n) {
5072 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005073 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005074 }
5075 else{
5076 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005077 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005078 }
5079 return NO_ERROR;
5080 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005081 case 1021: { // Disable HWC virtual displays
5082 n = data.readInt32();
5083 mUseHwcVirtualDisplays = !n;
5084 return NO_ERROR;
5085 }
Romain Guy0147a172017-06-01 13:53:56 -07005086 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005087 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005088 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005089
Chia-I Wu28f320b2018-05-03 11:02:56 -07005090 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005091 return NO_ERROR;
5092 }
Romain Guy54f154a2017-10-24 21:40:32 +01005093 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005094 int32_t colorMode;
5095
Chia-I Wu0d711262018-05-21 15:19:35 -07005096 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005097 if (data.readInt32(&colorMode) == NO_ERROR) {
5098 mForceColorMode = static_cast<ColorMode>(colorMode);
5099 }
Romain Guy54f154a2017-10-24 21:40:32 +01005100 invalidateHwcGeometry();
5101 repaintEverything();
5102 return NO_ERROR;
5103 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005104 // Deprecate, use 1030 to check whether the device is color managed.
5105 case 1024: {
5106 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005107 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005108 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005109 n = data.readInt32();
5110 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005111 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005112 Mutex::Autolock lock(mStateLock);
5113 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005114 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005115 reply->writeInt32(NO_ERROR);
5116 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005117 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005118 bool writeFile = false;
5119 {
5120 Mutex::Autolock lock(mStateLock);
5121 mTracingEnabledChanged = true;
5122 writeFile = mTracing.disable();
5123 }
5124
5125 if (writeFile) {
5126 reply->writeInt32(mTracing.writeToFile());
5127 } else {
5128 reply->writeInt32(NO_ERROR);
5129 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005130 }
5131 return NO_ERROR;
5132 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005133 case 1026: { // Get layer tracing status
5134 reply->writeBool(mTracing.isEnabled());
5135 return NO_ERROR;
5136 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005137 // Is a DisplayColorSetting supported?
5138 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005139 const auto display = getDefaultDisplayDevice();
5140 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005141 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005142 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005143
5144 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5145 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005146 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005147 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005148 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005149 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005150 reply->writeBool(true);
5151 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005152 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005153 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005154 break;
5155 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005156 reply->writeBool(
5157 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005158 break;
5159 }
5160 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005161 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005162 // Is VrFlinger active?
5163 case 1028: {
5164 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005165 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005166 return NO_ERROR;
5167 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005168 // Set buffer size for SF tracing (value in KB)
5169 case 1029: {
5170 n = data.readInt32();
5171 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5172 ALOGW("Invalid buffer size: %d KB", n);
5173 reply->writeInt32(BAD_VALUE);
5174 return BAD_VALUE;
5175 }
5176
5177 ALOGD("Updating trace buffer to %d KB", n);
5178 mTracing.setBufferSize(n * 1024);
5179 reply->writeInt32(NO_ERROR);
5180 return NO_ERROR;
5181 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005182 // Is device color managed?
5183 case 1030: {
5184 reply->writeBool(useColorManagement);
5185 return NO_ERROR;
5186 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005187 // Override default composition data space
5188 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5189 // && adb shell stop zygote && adb shell start zygote
5190 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5191 // adb shell stop zygote && adb shell start zygote
5192 case 1031: {
5193 Mutex::Autolock _l(mStateLock);
5194 n = data.readInt32();
5195 if (n) {
5196 n = data.readInt32();
5197 if (n) {
5198 Dataspace dataspace = static_cast<Dataspace>(n);
5199 if (!validateCompositionDataspace(dataspace)) {
5200 return BAD_VALUE;
5201 }
5202 mDefaultCompositionDataspace = dataspace;
5203 }
5204 n = data.readInt32();
5205 if (n) {
5206 Dataspace dataspace = static_cast<Dataspace>(n);
5207 if (!validateCompositionDataspace(dataspace)) {
5208 return BAD_VALUE;
5209 }
5210 mWideColorGamutCompositionDataspace = dataspace;
5211 }
5212 } else {
5213 // restore composition data space.
5214 mDefaultCompositionDataspace = defaultCompositionDataspace;
5215 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5216 }
5217 return NO_ERROR;
5218 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005219 // Set trace flags
5220 case 1033: {
5221 n = data.readUint32();
5222 ALOGD("Updating trace flags to 0x%x", n);
5223 mTracing.setTraceFlags(n);
5224 reply->writeInt32(NO_ERROR);
5225 return NO_ERROR;
5226 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005227 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005228 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005229 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005230 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005231 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005232 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005233 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005234 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005235 } else {
5236 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005237 }
5238 return NO_ERROR;
5239 }
Ady Abraham34392f72019-04-10 11:29:27 -07005240 case 1035: {
5241 n = data.readInt32();
5242 mDebugDisplayConfigSetByBackdoor = false;
5243 if (n >= 0) {
5244 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005245 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005246 if (result != NO_ERROR) {
5247 return result;
5248 }
5249 mDebugDisplayConfigSetByBackdoor = true;
5250 }
5251 return NO_ERROR;
5252 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005253 }
5254 }
5255 return err;
5256}
5257
Steven Thomas6d8110b2017-08-31 18:24:21 -07005258void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005259 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005260 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005261}
5262
Ana Krulec7d1d6832018-12-27 11:10:09 -08005263void SurfaceFlinger::repaintEverythingForHWC() {
5264 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005265 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005266 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005267}
5268
Ady Abrahama09852a2020-02-20 14:23:42 -08005269void SurfaceFlinger::kernelTimerChanged(bool expired) {
5270 static bool updateOverlay =
5271 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5272 if (!updateOverlay || !mRefreshRateOverlay) return;
5273
5274 // Update the overlay on the main thread to avoid race conditions with
5275 // mRefreshRateConfigs->getCurrentRefreshRate()
5276 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5277 if (mRefreshRateOverlay) {
5278 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5279 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005280 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005281 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5282 if (mDesiredActiveConfigChanged) {
5283 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5284 mDesiredActiveConfig.configId);
5285 }
5286
5287 return mRefreshRateConfigs->getCurrentRefreshRate();
5288 }();
5289 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5290
5291 if (current != min) {
5292 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5293 mEventQueue->invalidate();
5294 }
5295 }
5296 }));
5297}
5298
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005299// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5300class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005301public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005302 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5303 ~WindowDisconnector() {
5304 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005305 }
5306
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005307private:
5308 ANativeWindow* mWindow;
5309 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005310};
5311
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005312status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005313 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005314 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5315 const Rect& sourceCrop, uint32_t reqWidth,
5316 uint32_t reqHeight, bool useIdentityTransform,
5317 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005318 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005319
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005320 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005321
Dominik Laskowski718f9602019-11-09 20:01:35 -08005322 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5323 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5324 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5325 renderAreaRotation = ui::Transform::ROT_0;
5326 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005327
Chia-I Wu20261cb2018-08-23 12:55:44 -07005328 sp<DisplayDevice> display;
5329 {
5330 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005331
Chia-I Wu20261cb2018-08-23 12:55:44 -07005332 display = getDisplayDeviceLocked(displayToken);
5333 if (!display) return BAD_VALUE;
5334
Chia-I Wucb023152018-08-28 12:57:23 -07005335 // set the requested width/height to the logical display viewport size
5336 // by default
5337 if (reqWidth == 0 || reqHeight == 0) {
5338 reqWidth = uint32_t(display->getViewport().width());
5339 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005340 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005341 }
5342
Peiyong Lin0e003c92018-09-17 11:09:51 -07005343 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005344 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005345
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005346 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5347 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005348 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005349 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005350}
5351
chaviw93df2ea2019-04-30 16:45:12 -07005352static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5353 switch (colorMode) {
5354 case ColorMode::DISPLAY_P3:
5355 case ColorMode::BT2100_PQ:
5356 case ColorMode::BT2100_HLG:
5357 case ColorMode::DISPLAY_BT2020:
5358 return Dataspace::DISPLAY_P3;
5359 default:
5360 return Dataspace::V0_SRGB;
5361 }
5362}
5363
Martin Liu4a322352020-03-24 21:30:38 +08005364status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5365 static constexpr int kFifoPriority = 2;
5366 static constexpr int kOtherPriority = 0;
5367
5368 struct sched_param param = {0};
5369 int sched_policy;
5370 if (enabled) {
5371 sched_policy = SCHED_FIFO;
5372 param.sched_priority = kFifoPriority;
5373 } else {
5374 sched_policy = SCHED_OTHER;
5375 param.sched_priority = kOtherPriority;
5376 }
5377
5378 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5379 return -errno;
5380 }
5381 return NO_ERROR;
5382}
5383
chaviw93df2ea2019-04-30 16:45:12 -07005384const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5385 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5386 if (displayToken) {
5387 return getDisplayDeviceLocked(displayToken);
5388 }
5389 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5390 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005391 return getDisplayByLayerStack(displayOrLayerStack);
5392}
5393
5394const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005395 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005396 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005397 return display;
5398 }
5399 }
5400 return nullptr;
5401}
5402
5403status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5404 sp<GraphicBuffer>* outBuffer) {
5405 sp<DisplayDevice> display;
5406 uint32_t width;
5407 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005408 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005409 {
5410 Mutex::Autolock _l(mStateLock);
5411 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5412 if (!display) {
5413 return BAD_VALUE;
5414 }
5415
5416 width = uint32_t(display->getViewport().width());
5417 height = uint32_t(display->getViewport().height());
5418
Dominik Laskowski718f9602019-11-09 20:01:35 -08005419 const auto orientation = display->getOrientation();
5420 captureOrientation = ui::Transform::toRotationFlags(orientation);
5421
5422 switch (captureOrientation) {
5423 case ui::Transform::ROT_90:
5424 captureOrientation = ui::Transform::ROT_270;
5425 break;
5426
5427 case ui::Transform::ROT_270:
5428 captureOrientation = ui::Transform::ROT_90;
5429 break;
5430
5431 case ui::Transform::ROT_INVALID:
5432 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5433 captureOrientation = ui::Transform::ROT_0;
5434 break;
5435
5436 default:
5437 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005438 }
chaviw93df2ea2019-04-30 16:45:12 -07005439 *outDataspace =
5440 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5441 }
5442
5443 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5444 false /* captureSecureLayers */);
5445
5446 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5447 std::placeholders::_1);
5448 bool ignored = false;
5449 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5450 false /* useIdentityTransform */,
5451 ignored /* outCapturedSecureLayers */);
5452}
5453
Robert Carr866455f2019-04-02 16:28:26 -07005454status_t SurfaceFlinger::captureLayers(
5455 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5456 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5457 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5458 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005459 ATRACE_CALL();
5460
5461 class LayerRenderArea : public RenderArea {
5462 public:
Robert Carr578038f2018-03-09 12:25:24 -08005463 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005464 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005465 bool childrenOnly, const Rect& displayViewport)
5466 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005467 mLayer(layer),
5468 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005469 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005470 mFlinger(flinger),
5471 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005472 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005473 Rect getBounds() const override {
5474 const Layer::State& layerState(mLayer->getDrawingState());
5475 return mLayer->getBufferSize(layerState);
5476 }
Marissa Wall61c58622018-07-18 10:12:20 -07005477 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005478 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005479 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005480 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005481 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005482 }
chaviwa76b2712017-09-20 12:02:26 -07005483 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005484 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005485 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005486 Rect getSourceCrop() const override {
5487 if (mCrop.isEmpty()) {
5488 return getBounds();
5489 } else {
5490 return mCrop;
5491 }
5492 }
Robert Carr578038f2018-03-09 12:25:24 -08005493 class ReparentForDrawing {
5494 public:
5495 const sp<Layer>& oldParent;
5496 const sp<Layer>& newParent;
5497
Vishnu Nair4351ad52019-02-11 14:13:02 -08005498 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5499 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005500 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005501 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005502 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5503 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005504 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005505 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005506 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005507 };
5508
5509 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005510 const Rect sourceCrop = getSourceCrop();
5511 // no need to check rotation because there is none
5512 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5513 sourceCrop.height() != getReqHeight();
5514
Robert Carr578038f2018-03-09 12:25:24 -08005515 if (!mChildrenOnly) {
5516 mTransform = mLayer->getTransform().inverse();
5517 drawLayers();
5518 } else {
5519 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005520 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5521 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005522 // In the "childrenOnly" case we reparent the children to a screenshot
5523 // layer which has no properties set and which does not draw.
5524 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005525 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5526 "Screenshot Parent"s, w, h, 0,
5527 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005528
Vishnu Nair4351ad52019-02-11 14:13:02 -08005529 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005530 drawLayers();
5531 }
5532 }
chaviwa76b2712017-09-20 12:02:26 -07005533
chaviwa76b2712017-09-20 12:02:26 -07005534 private:
chaviw7206d492017-11-10 16:16:12 -08005535 const sp<Layer> mLayer;
5536 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005537
Peiyong Linefefaac2018-08-17 12:27:51 -07005538 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005539 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005540
5541 SurfaceFlinger* mFlinger;
5542 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005543 };
5544
Robert Carrc0df3122019-04-11 13:18:21 -07005545 int reqWidth = 0;
5546 int reqHeight = 0;
5547 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005548 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005549 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005550 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005551 {
5552 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005553
Robert Carrc0df3122019-04-11 13:18:21 -07005554 parent = fromHandle(layerHandleBinder);
5555 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5556 ALOGE("captureLayers called with an invalid or removed parent");
5557 return NAME_NOT_FOUND;
5558 }
5559
5560 const int uid = IPCThreadState::self()->getCallingUid();
5561 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5562 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5563 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5564 return PERMISSION_DENIED;
5565 }
5566
Vishnu Nairefc42e22019-12-03 17:36:12 -08005567 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005568 if (sourceCrop.width() <= 0) {
5569 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005570 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005571 }
5572
5573 if (sourceCrop.height() <= 0) {
5574 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005575 crop.bottom = parentSourceBounds.getHeight();
5576 }
5577
5578 if (crop.isEmpty() || frameScale <= 0.0f) {
5579 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5580 // crop was not specified, or an invalid frame scale was provided.
5581 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005582 }
5583 reqWidth = crop.width() * frameScale;
5584 reqHeight = crop.height() * frameScale;
5585
5586 for (const auto& handle : excludeHandles) {
5587 sp<Layer> excludeLayer = fromHandle(handle);
5588 if (excludeLayer != nullptr) {
5589 excludeLayers.emplace(excludeLayer);
5590 } else {
5591 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5592 return NAME_NOT_FOUND;
5593 }
5594 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005595
5596 auto display = getDisplayByLayerStack(parent->getLayerStack());
5597 if (!display) {
5598 return BAD_VALUE;
5599 }
5600
5601 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005602 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005603
Chia-I Wu20261cb2018-08-23 12:55:44 -07005604 // really small crop or frameScale
5605 if (reqWidth <= 0) {
5606 reqWidth = 1;
5607 }
5608 if (reqHeight <= 0) {
5609 reqHeight = 1;
5610 }
5611
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005612 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5613 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005614 auto traverseLayers = [parent, childrenOnly,
5615 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005616 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5617 if (!layer->isVisible()) {
5618 return;
Robert Carr578038f2018-03-09 12:25:24 -08005619 } else if (childrenOnly && layer == parent.get()) {
5620 return;
chaviwa76b2712017-09-20 12:02:26 -07005621 }
Robert Carr866455f2019-04-02 16:28:26 -07005622
5623 sp<Layer> p = layer;
5624 while (p != nullptr) {
5625 if (excludeLayers.count(p) != 0) {
5626 return;
5627 }
5628 p = p->getParent();
5629 }
5630
chaviwa76b2712017-09-20 12:02:26 -07005631 visitor(layer);
5632 });
5633 };
Robert Carr108b2c72019-04-02 16:32:58 -07005634
5635 bool outCapturedSecureLayers = false;
5636 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5637 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005638}
5639
5640status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5641 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005642 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005643 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005644 bool useIdentityTransform,
5645 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005646 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005647
Peiyong Lin0e003c92018-09-17 11:09:51 -07005648 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005649 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5650 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005651 *outBuffer =
5652 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5653 static_cast<android_pixel_format>(reqPixelFormat), 1,
5654 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005655
Robert Carr108b2c72019-04-02 16:32:58 -07005656 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5657 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005658}
5659
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005660status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5661 TraverseLayersFunction traverseLayers,
5662 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005663 bool useIdentityTransform,
5664 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005665 // This mutex protects syncFd and captureResult for communication of the return values from the
5666 // main thread back to this Binder thread
5667 std::mutex captureMutex;
5668 std::condition_variable captureCondition;
5669 std::unique_lock<std::mutex> captureLock(captureMutex);
5670 int syncFd = -1;
5671 std::optional<status_t> captureResult;
5672
Robert Carr03480e22018-01-04 16:02:06 -08005673 const int uid = IPCThreadState::self()->getCallingUid();
5674 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5675
Dominik Laskowski8c001672018-05-30 16:52:06 -07005676 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005677 // If there is a refresh pending, bug out early and tell the binder thread to try again
5678 // after the refresh.
5679 if (mRefreshPending) {
5680 ATRACE_NAME("Skipping screenshot for now");
5681 std::unique_lock<std::mutex> captureLock(captureMutex);
5682 captureResult = std::make_optional<status_t>(EAGAIN);
5683 captureCondition.notify_one();
5684 return;
5685 }
5686
5687 status_t result = NO_ERROR;
5688 int fd = -1;
5689 {
5690 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005691 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005692 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005693 useIdentityTransform, forSystem, &fd,
5694 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005695 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005696 }
5697
5698 {
5699 std::unique_lock<std::mutex> captureLock(captureMutex);
5700 syncFd = fd;
5701 captureResult = std::make_optional<status_t>(result);
5702 captureCondition.notify_one();
5703 }
5704 });
5705
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005706 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005707 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005708 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005709 while (*captureResult == EAGAIN) {
5710 captureResult.reset();
5711 result = postMessageAsync(message);
5712 if (result != NO_ERROR) {
5713 return result;
5714 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005715 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005716 }
5717 result = *captureResult;
5718 }
5719
5720 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005721 sync_wait(syncFd, -1);
5722 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005723 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005724
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005725 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005726}
5727
chaviwa76b2712017-09-20 12:02:26 -07005728void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005729 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005730 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5731 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005732 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005733
chaviwa76b2712017-09-20 12:02:26 -07005734 const auto reqWidth = renderArea.getReqWidth();
5735 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005736 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005737 const auto transform = renderArea.getTransform();
5738 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005739 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005740
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005741 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005742 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005743
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005744 // assume that bounds are never offset, and that they are the same as the
5745 // buffer bounds.
5746 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005747 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005748 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005749
5750 // Now take into account the rotation flag. We append a transform that
5751 // rotates the layer stack about the origin, then translate by buffer
5752 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005753 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005754 int displacementX = 0;
5755 int displacementY = 0;
5756 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5757 switch (rotation) {
5758 case ui::Transform::ROT_90:
5759 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005760 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005761 break;
5762 case ui::Transform::ROT_180:
5763 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005764 displacementY = renderArea.getBounds().getWidth();
5765 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005766 break;
5767 case ui::Transform::ROT_270:
5768 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005769 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005770 break;
5771 default:
5772 break;
5773 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005774
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005775 // We need to transform the clipping window into the right spot.
5776 // First, rotate the clipping rectangle by the rotation hint to get the
5777 // right orientation
5778 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5779 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5780 const vec4 rotClipTL = rotMatrix * clipTL;
5781 const vec4 rotClipBR = rotMatrix * clipBR;
5782 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5783 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5784 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5785 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5786
5787 // Now reposition the clipping rectangle with the displacement vector
5788 // computed above.
5789 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005790 clientCompositionDisplay.clip =
5791 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5792 newClipRight + displacementX, newClipBottom + displacementY);
5793
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005794 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005795 clientCompositionDisplay.globalTransform =
5796 clipTransform * clientCompositionDisplay.globalTransform;
5797
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005798 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5799 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005800
chaviw50da5042018-04-09 13:49:37 -07005801 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005802
Vishnu Nair9b079a22020-01-21 14:36:08 -08005803 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005804 fillLayer.source.buffer.buffer = nullptr;
5805 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5806 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5807 fillLayer.alpha = half(alpha);
5808 clientCompositionLayers.push_back(fillLayer);
5809
5810 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005811 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005812 const bool supportProtectedContent = false;
5813 Region clip(renderArea.getBounds());
5814 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5815 clip,
5816 useIdentityTransform,
5817 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5818 renderArea.isSecure(),
5819 supportProtectedContent,
5820 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005821 displayViewport,
5822 clientCompositionDisplay.outputDataspace,
5823 true, /* realContentIsVisible */
5824 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005825 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005826 std::vector<compositionengine::LayerFE::LayerSettings> results =
5827 layer->prepareClientCompositionList(targetSettings);
5828 clientCompositionLayers.insert(clientCompositionLayers.end(),
5829 std::make_move_iterator(results.begin()),
5830 std::make_move_iterator(results.end()));
5831 results.clear();
5832
chaviwa76b2712017-09-20 12:02:26 -07005833 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005834
Vishnu Nair9b079a22020-01-21 14:36:08 -08005835 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5836 clientCompositionLayers.reserve(clientCompositionLayers.size());
5837 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5838 std::back_inserter(clientCompositionLayerPointers),
5839 [](compositionengine::LayerFE::LayerSettings& settings)
5840 -> renderengine::LayerSettings* { return &settings; });
5841
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005842 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005843 // Use an empty fence for the buffer fence, since we just created the buffer so
5844 // there is no need for synchronization with the GPU.
5845 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005846 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005847 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005848 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005849 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005850
5851 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005852}
5853
chaviwa76b2712017-09-20 12:02:26 -07005854status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5855 TraverseLayersFunction traverseLayers,
5856 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005857 bool useIdentityTransform, bool forSystem,
5858 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005859 ATRACE_CALL();
5860
chaviwa76b2712017-09-20 12:02:26 -07005861 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005862 outCapturedSecureLayers =
5863 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005864 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005865
Robert Carr03480e22018-01-04 16:02:06 -08005866 // We allow the system server to take screenshots of secure layers for
5867 // use in situations like the Screen-rotation animation and place
5868 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005869 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005870 ALOGW("FB is protected: PERMISSION_DENIED");
5871 return PERMISSION_DENIED;
5872 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005873 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005874 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005875}
5876
chaviw95ef3c42019-02-14 10:55:09 -08005877void SurfaceFlinger::setInputWindowsFinished() {
5878 Mutex::Autolock _l(mStateLock);
5879
5880 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005881
chaviw95ef3c42019-02-14 10:55:09 -08005882 mTransactionCV.broadcast();
5883}
chaviw5f21a5e2019-02-14 10:00:34 -08005884
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005885// ---------------------------------------------------------------------------
5886
Edgar Arriaga844fa672020-01-16 14:21:42 -08005887void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5888 layersSortedByZ.traverse(visitor);
5889}
5890
Dan Stoza412903f2017-04-27 13:42:17 -07005891void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5892 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005893}
5894
Dan Stoza412903f2017-04-27 13:42:17 -07005895void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5896 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005897}
5898
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005899void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005900 const LayerVector::Visitor& visitor) {
5901 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005902 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005903 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005904 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005905 continue;
5906 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005907 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005908 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005909 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005910 return;
5911 }
chaviwa76b2712017-09-20 12:02:26 -07005912 if (!layer->isVisible()) {
5913 return;
5914 }
5915 visitor(layer);
5916 });
5917 }
5918}
5919
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005920status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5921 HwcConfigIndexType defaultConfig,
5922 float minRefreshRate,
5923 float maxRefreshRate) {
5924 Mutex::Autolock lock(mStateLock);
5925
Dominik Laskowski22488f62019-03-28 09:53:04 -07005926 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005927 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5928 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5929 // it should go thru setDesiredActiveConfig, similar to primary display.
5930 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5931 const auto displayId = display->getId();
5932 LOG_ALWAYS_FATAL_IF(!displayId);
5933
5934 HWC2::VsyncPeriodChangeConstraints constraints;
5935 constraints.desiredTimeNanos = systemTime();
5936 constraints.seamlessRequired = false;
5937
5938 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005939 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5940 constraints, &timeline) < 0) {
5941 return BAD_VALUE;
5942 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005943 if (timeline.refreshRequired) {
5944 repaintEverythingForHWC();
5945 }
5946
Ady Abrahamdfa37362020-01-21 18:02:39 -08005947 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005948 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005949 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5950 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005951 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005952 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005953 }
5954
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005955 if (mDebugDisplayConfigSetByBackdoor) {
5956 // ignore this request as config is overridden by backdoor
5957 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005958 }
5959
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005960 bool policyChanged;
5961 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5962 &policyChanged) < 0) {
5963 return BAD_VALUE;
5964 }
5965 if (!policyChanged) {
5966 return NO_ERROR;
5967 }
5968
5969 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5970 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005971
5972 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5973 // that listeners that care about a change in allowed configs can get the notification.
5974 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005975 const nsecs_t vsyncPeriod =
5976 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005977 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005978 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005979
Ana Krulec3f6a2062020-01-23 15:48:01 -08005980 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005981 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005982 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5983 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5984 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5985 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5986 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5987
5988 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5989 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5990 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005991 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005992 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005993 }
5994
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005995 return NO_ERROR;
5996}
5997
Ana Krulec0782b882019-10-15 17:34:54 -07005998status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005999 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07006000 float maxRefreshRate) {
6001 ATRACE_CALL();
6002
6003 if (!displayToken) {
6004 return BAD_VALUE;
6005 }
6006
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006007 status_t result = NO_ERROR;
6008
Ana Krulec234bb162019-11-10 22:55:55 +01006009 postMessageSync(new LambdaMessage([&]() {
6010 const auto display = getDisplayDeviceLocked(displayToken);
6011 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006012 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01006013 ALOGE("Attempt to set desired display configs for invalid display token %p",
6014 displayToken.get());
6015 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006016 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01006017 ALOGW("Attempt to set desired display configs for virtual display");
6018 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006019 result =
6020 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
6021 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01006022 }
6023 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006024
6025 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01006026}
6027
6028status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006029 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01006030 float* outMinRefreshRate,
6031 float* outMaxRefreshRate) {
6032 ATRACE_CALL();
6033
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006034 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01006035 return BAD_VALUE;
6036 }
6037
6038 Mutex::Autolock lock(mStateLock);
6039 const auto display = getDisplayDeviceLocked(displayToken);
6040 if (!display) {
6041 return NAME_NOT_FOUND;
6042 }
6043
6044 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006045 HwcConfigIndexType defaultConfig;
6046 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
6047 *outDefaultConfig = defaultConfig.value();
6048 return NO_ERROR;
6049 } else if (display->isVirtual()) {
6050 return BAD_VALUE;
6051 } else {
6052 const auto displayId = display->getId();
6053 if (!displayId) {
6054 return BAD_VALUE;
6055 }
6056 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6057 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6058 *outMinRefreshRate = 1e9f / vsyncPeriod;
6059 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6060 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006061 }
Ana Krulec0782b882019-10-15 17:34:54 -07006062}
6063
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006064void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006065 mFlinger->setInputWindowsFinished();
6066}
6067
Robert Carrc0df3122019-04-11 13:18:21 -07006068sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006069 BBinder* b = nullptr;
6070 if (handle) {
6071 b = handle->localBinder();
6072 }
Robert Carrc0df3122019-04-11 13:18:21 -07006073 if (b == nullptr) {
6074 return nullptr;
6075 }
6076 auto it = mLayersByLocalBinderToken.find(b);
6077 if (it != mLayersByLocalBinderToken.end()) {
6078 return it->second.promote();
6079 }
6080 return nullptr;
6081}
6082
Dominik Laskowski75848362019-11-11 17:57:20 -08006083void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006084 mNumLayers++;
6085 mScheduler->registerLayer(layer);
6086}
6087
6088void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6089 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006090 removeFromOffscreenLayers(layer);
6091}
6092
6093// WARNING: ONLY CALL THIS FROM LAYER DTOR
6094// Here we add children in the current state to offscreen layers and remove the
6095// layer itself from the offscreen layer list. Since
6096// this is the dtor, it is safe to access the current state. This keeps us
6097// from dangling children layers such that they are not reachable from the
6098// Drawing state nor the offscreen layer list
6099// See b/141111965
6100void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6101 for (auto& child : layer->getCurrentChildren()) {
6102 mOffscreenLayers.emplace(child.get());
6103 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006104 mOffscreenLayers.erase(layer);
6105}
6106
Alec Mouri4545a8a2019-08-08 20:05:32 -07006107void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6108 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6109}
6110
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006111status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6112 float lightPosY, float lightPosZ,
6113 float lightRadius) {
6114 Mutex::Autolock _l(mStateLock);
6115 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6116 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6117 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6118 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6119 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6120
6121 // these values are overridden when calculating the shadow settings for a layer.
6122 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6123 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006124 return NO_ERROR;
6125}
6126
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006127const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6128 const {
6129 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6130 // on the work to remove the table in that bug rather than adding more to
6131 // it.
6132 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6133 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6134 // supported, and exposed via the
6135 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6136 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6137 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6138 };
6139 return genericLayerMetadataKeyMap;
6140}
6141
Steven Thomas62a4cf82020-01-31 12:04:03 -08006142status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6143 int8_t compatibility) {
6144 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6145 return BAD_VALUE;
6146 }
6147
Ady Abraham60e42ea2020-03-09 19:17:31 -07006148 postMessageAsync(new LambdaMessage([=]() NO_THREAD_SAFETY_ANALYSIS {
6149 Mutex::Autolock lock(mStateLock);
6150 if (authenticateSurfaceTextureLocked(surface)) {
6151 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6152 if (layer->setFrameRate(
6153 Layer::FrameRate(frameRate,
6154 Layer::FrameRate::convertCompatibility(compatibility)))) {
6155 setTransactionFlags(eTraversalNeeded);
6156 }
6157 } else {
6158 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6159 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006160 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006161 return NO_ERROR;
6162 }));
6163
Steven Thomas62a4cf82020-01-31 12:04:03 -08006164 return NO_ERROR;
6165}
6166
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006167} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006168
Mathias Agopian3f844832013-08-07 21:24:32 -07006169#if defined(__gl_h_)
6170#error "don't include gl/gl.h in this file"
6171#endif
6172
6173#if defined(__gl2_h_)
6174#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006175#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006176
6177// TODO(b/129481165): remove the #pragma below and fix conversion issues
6178#pragma clang diagnostic pop // ignored "-Wconversion"