blob: c47bf94a12033ae38bc97e40f67ae664157f11b8 [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 Thomasd4071902020-03-24 16:02:53 -0700203class FrameRateFlexibilityToken : public BBinder {
204public:
205 FrameRateFlexibilityToken(std::function<void()> callback) : mCallback(callback) {}
206 virtual ~FrameRateFlexibilityToken() { mCallback(); }
207
208private:
209 std::function<void()> mCallback;
210};
211
Steven Thomasb02664d2017-07-26 18:48:28 -0700212} // namespace anonymous
213
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800214// ---------------------------------------------------------------------------
215
Mathias Agopian99b49842011-06-27 16:05:52 -0700216const String16 sHardwareTest("android.permission.HARDWARE_TEST");
217const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
218const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
219const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800220const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700221
222// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700223int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700224bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800225uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800226bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800227bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800228int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Brian Lindahla13f2d52020-03-05 11:54:17 +0100229uint32_t SurfaceFlinger::maxGraphicsWidth;
230uint32_t SurfaceFlinger::maxGraphicsHeight;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600231bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800232ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700233bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700234bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700235Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
236ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
237Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
238ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800239bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700240
Kalle Raitaa099a242017-01-11 11:17:29 -0800241std::string getHwcServiceName() {
242 char value[PROPERTY_VALUE_MAX] = {};
243 property_get("debug.sf.hwc_service_name", value, "default");
244 ALOGI("Using HWComposer service: '%s'", value);
245 return std::string(value);
246}
247
248bool useTrebleTestingOverride() {
249 char value[PROPERTY_VALUE_MAX] = {};
250 property_get("debug.sf.treble_testing_override", value, "false");
251 ALOGI("Treble testing override: '%s'", value);
252 return std::string(value) == "true";
253}
254
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800255std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
256 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800257 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700258 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800259 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700260 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800261 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700262 return std::string("Enhanced");
263 default:
264 return std::string("Unknown ") +
265 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800266 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800267}
268
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700269SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800270
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700271SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
272 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700273 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700274 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700275 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700276 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700277 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800278 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
279 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800280
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700281SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800282 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800291
Steven Thomas050b2c82017-03-06 11:45:16 -0800292 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900293 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800294
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800296
Brian Lindahla13f2d52020-03-05 11:54:17 +0100297 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
298 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600303
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 mDefaultCompositionDataspace =
305 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700306 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
307 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 defaultCompositionDataspace = mDefaultCompositionDataspace;
309 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
310 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
311 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
312 wideColorGamutCompositionPixelFormat =
313 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700314
Yichi Chenda901bf2019-06-28 14:58:27 +0800315 mColorSpaceAgnosticDataspace =
316 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
317
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900318 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800319
Dominik Laskowski718f9602019-11-09 20:01:35 -0800320 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
321 switch (primary_display_orientation(Values::ORIENTATION_0)) {
322 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800323 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800324 case Values::ORIENTATION_90:
325 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800326 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800327 case Values::ORIENTATION_180:
328 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800329 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800330 case Values::ORIENTATION_270:
331 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800332 break;
333 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800334 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800335
Sundong Ahn85131bd2019-02-18 15:51:53 +0900336 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800337
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800338 // debugging stuff...
339 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700340
Mathias Agopianb4b17302013-03-20 18:36:41 -0700341 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700342 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700343
Alec Mouri989ddbe2020-02-06 09:26:19 -0800344 property_get("ro.build.type", value, "user");
345 mIsUserBuild = strcmp(value, "user") == 0;
346
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800347 property_get("debug.sf.showupdates", value, "0");
348 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700349
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700350 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000351
352 // DDMS debugging deprecated (b/120782499)
353 property_get("debug.sf.ddms", value, "0");
354 int debugDdms = atoi(value);
355 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700356
357 property_get("debug.sf.disable_backpressure", value, "0");
358 mPropagateBackpressure = !atoi(value);
359 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700360
Ady Abrahamadb9a992019-09-19 21:21:55 +0000361 property_get("debug.sf.enable_gl_backpressure", value, "0");
362 mPropagateBackpressureClientComposition = atoi(value);
363 ALOGI_IF(mPropagateBackpressureClientComposition,
364 "Enabling backpressure propagation for Client Composition");
365
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800366 property_get("debug.sf.enable_hwc_vds", value, "0");
367 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800368 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800369
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800370 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800371 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800372 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700373
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800374 property_get("ro.surface_flinger.supports_background_blur", value, "0");
375 bool supportsBlurs = atoi(value);
Lucas Dupin00f16422020-03-11 11:33:04 -0700376 mSupportsBlur = supportsBlurs;
377 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800378 property_get("ro.sf.blurs_are_expensive", value, "0");
379 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800380
Ady Abraham0a525092020-03-03 12:51:24 -0800381 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700382 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
383 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
384
Dan Stozaec460082018-12-17 15:35:09 -0800385 property_get("debug.sf.luma_sampling", value, "1");
386 mLumaSampling = atoi(value);
387
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800388 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800389 mDisableClientCompositionCache = atoi(value);
390
Romain Guy11d63f42017-07-20 12:47:14 -0700391 // We should be reading 'persist.sys.sf.color_saturation' here
392 // but since /data may be encrypted, we need to wait until after vold
393 // comes online to attempt to read the property. The property is
394 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800395
396 if (useTrebleTestingOverride()) {
397 // Without the override SurfaceFlinger cannot connect to HIDL
398 // services that are not listed in the manifests. Considered
399 // deriving the setting from the set service name, but it
400 // would be brittle if the name that's not 'default' is used
401 // for production purposes later on.
402 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
403 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800404
405 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800406}
407
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800408void SurfaceFlinger::onFirstRef()
409{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800410 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800411}
412
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700413SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800414
Dan Stozac7014012014-02-14 15:03:43 -0800415void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800416{
417 // the window manager died on us. prepare its eulogy.
Rob Carr2aa78cb2020-03-10 14:27:49 -0700418 mBootFinished = false;
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800419
Andy McFadden13a082e2012-08-24 10:16:42 -0700420 // restore initial conditions (default device unblank, etc)
421 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800422
423 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700424 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800425}
426
Robert Carr1db73f62016-12-21 12:58:51 -0800427static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700428 status_t err = client->initCheck();
429 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800430 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800431 }
Robert Carr1db73f62016-12-21 12:58:51 -0800432 return nullptr;
433}
434
435sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
436 return initClient(new Client(this));
437}
438
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700439sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
440 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700441{
442 class DisplayToken : public BBinder {
443 sp<SurfaceFlinger> flinger;
444 virtual ~DisplayToken() {
445 // no more references, this display must be terminated
446 Mutex::Autolock _l(flinger->mStateLock);
447 flinger->mCurrentState.displays.removeItem(this);
448 flinger->setTransactionFlags(eDisplayTransactionNeeded);
449 }
450 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700451 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700452 : flinger(flinger) {
453 }
454 };
455
456 sp<BBinder> token = new DisplayToken(this);
457
458 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700459 // Display ID is assigned when virtual display is allocated by HWC.
460 DisplayDeviceState state;
461 state.isSecure = secure;
462 state.displayName = displayName;
463 mCurrentState.displays.add(token, state);
464 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700465 return token;
466}
467
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700468void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700469 Mutex::Autolock _l(mStateLock);
470
Dominik Laskowski075d3172018-05-24 15:50:06 -0700471 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
472 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700473 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700474 return;
475 }
476
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
478 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700479 ALOGE("destroyDisplay called for non-virtual display");
480 return;
481 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700482 mInterceptor->saveDisplayDeletion(state.sequenceId);
483 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700484 setTransactionFlags(eDisplayTransactionNeeded);
485}
486
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800487std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
488 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700489
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800490 const auto internalDisplayId = getInternalDisplayIdLocked();
491 if (!internalDisplayId) {
492 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700493 }
494
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800495 std::vector<PhysicalDisplayId> displayIds;
496 displayIds.reserve(mPhysicalDisplayTokens.size());
497 displayIds.push_back(internalDisplayId->value);
498
499 for (const auto& [id, token] : mPhysicalDisplayTokens) {
500 if (id != *internalDisplayId) {
501 displayIds.push_back(id.value);
502 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700503 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700504
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800505 return displayIds;
506}
507
508sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
509 Mutex::Autolock lock(mStateLock);
510 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700511}
512
Ady Abraham37965d42018-11-01 13:43:32 -0700513status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
514 if (!outGetColorManagement) {
515 return BAD_VALUE;
516 }
517 *outGetColorManagement = useColorManagement;
518 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700519}
520
Lloyd Pique441d5042018-10-18 16:49:51 -0700521HWComposer& SurfaceFlinger::getHwComposer() const {
522 return mCompositionEngine->getHwComposer();
523}
524
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700525renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
526 return mCompositionEngine->getRenderEngine();
527}
528
Lloyd Pique70d91362018-10-18 16:02:55 -0700529compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
530 return *mCompositionEngine.get();
531}
532
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800533void SurfaceFlinger::bootFinished()
534{
Rob Carr2aa78cb2020-03-10 14:27:49 -0700535 if (mBootFinished == true) {
536 ALOGE("Extra call to bootFinished");
537 return;
538 }
539 mBootFinished = true;
Wei Wangf9b05ee2017-07-19 20:59:39 -0700540 if (mStartPropertySetThread->join() != NO_ERROR) {
541 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800542 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800543 const nsecs_t now = systemTime();
544 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000545 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546
Mikael Pessa90092f42019-08-26 17:22:04 -0700547 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000548 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700549
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700550 // wait patiently for the window manager death
551 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700552 mWindowManager = defaultServiceManager()->getService(name);
553 if (mWindowManager != 0) {
554 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700555 }
Robert Carr720e5062018-07-30 17:45:14 -0700556 sp<IBinder> input(defaultServiceManager()->getService(
557 String16("inputflinger")));
558 if (input == nullptr) {
559 ALOGE("Failed to link to input service");
560 } else {
561 mInputFlinger = interface_cast<IInputFlinger>(input);
562 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700563
Steven Thomas050b2c82017-03-06 11:45:16 -0800564 if (mVrFlinger) {
565 mVrFlinger->OnBootFinished();
566 }
567
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700568 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700569 // formerly we would just kill the process, but we now ask it to exit so it
570 // can choose where to stop the animation.
571 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700572
573 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
574 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
575 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700576
Ana Krulecbd6654b2019-02-15 15:18:15 -0800577 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800578 readPersistentProperties();
Dan Stoza29e7bdf2020-03-23 14:43:09 -0700579 mPowerAdvisor.onBootFinished();
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800580 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800581
Ady Abraham8a82ba62020-01-17 12:43:17 -0800582 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
583 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
584 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
585 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800586 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800587}
588
Dan Stoza436ccf32018-06-21 12:10:12 -0700589uint32_t SurfaceFlinger::getNewTexture() {
590 {
591 std::lock_guard lock(mTexturePoolMutex);
592 if (!mTexturePool.empty()) {
593 uint32_t name = mTexturePool.back();
594 mTexturePool.pop_back();
595 ATRACE_INT("TexturePoolSize", mTexturePool.size());
596 return name;
597 }
598
599 // The pool was too small, so increase it for the future
600 ++mTexturePoolSize;
601 }
602
603 // The pool was empty, so we need to get a new texture name directly using a
604 // blocking call to the main thread
605 uint32_t name = 0;
606 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
607 return name;
608}
609
Mathias Agopian3f844832013-08-07 21:24:32 -0700610void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700611 std::lock_guard lock(mTexturePoolMutex);
612 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
613 // to actually delete this or not based on mTexturePoolSize
614 mTexturePool.push_back(texture);
615 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700616}
617
Wei Wangf9b05ee2017-07-19 20:59:39 -0700618// Do not call property_set on main thread which will be blocked by init
619// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700620void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700621 ALOGI( "SurfaceFlinger's main thread ready to run. "
622 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700623 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800624
Steven Thomasb02664d2017-07-26 18:48:28 -0700625 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700626 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800627 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700628 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
629 renderengine::RenderEngineCreationArgs::Builder()
630 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
631 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
632 .setUseColorManagerment(useColorManagement)
633 .setEnableProtectedContext(enable_protected_contents(false))
634 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin00f16422020-03-11 11:33:04 -0700635 .setSupportsBackgroundBlur(mSupportsBlur)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700636 .setContextPriority(useContextPriority
637 ? renderengine::RenderEngine::ContextPriority::HIGH
638 : renderengine::RenderEngine::ContextPriority::MEDIUM)
639 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800640 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700641
642 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
643 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700644 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800645 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800646 // Process any initial hotplug and resulting display changes.
647 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700648 const auto display = getDefaultDisplayDeviceLocked();
649 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700650 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700651 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800652
Steven Thomas050b2c82017-03-06 11:45:16 -0800653 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700654 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700655 // This callback is called from the vr flinger dispatch thread. We
656 // need to call signalTransaction(), which requires holding
657 // mStateLock when we're not on the main thread. Acquiring
658 // mStateLock from the vr flinger dispatch thread might trigger a
659 // deadlock in surface flinger (see b/66916578), so post a message
660 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700661 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700662 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
663 mVrFlingerRequestsDisplay = requestDisplay;
664 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700665 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800666 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700667 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
668 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700669 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700670 .value_or(0),
671 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800672 if (!mVrFlinger) {
673 ALOGE("Failed to start vrflinger");
674 }
675 }
676
Mathias Agopian92a979a2012-08-02 18:32:23 -0700677 // initialize our drawing state
678 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700679
Andy McFadden13a082e2012-08-24 10:16:42 -0700680 // set initial conditions (e.g. unblank default device)
681 initializeDisplays();
682
Steven Thomas137d4bc2019-07-25 16:55:14 -0700683 char primeShaderCache[PROPERTY_VALUE_MAX];
684 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
685 if (atoi(primeShaderCache)) {
686 getRenderEngine().primeCache();
687 }
Dan Stoza4e637772016-07-28 13:31:51 -0700688
Wei Wangf9b05ee2017-07-19 20:59:39 -0700689 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700690
691 const bool presentFenceReliable =
692 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
693 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700694
695 if (mStartPropertySetThread->Start() != NO_ERROR) {
696 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800697 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800698
Dan Stoza9e56aa02015-11-02 13:00:03 -0800699 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700700}
701
Romain Guy11d63f42017-07-20 12:47:14 -0700702void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700703 Mutex::Autolock _l(mStateLock);
704
Romain Guy11d63f42017-07-20 12:47:14 -0700705 char value[PROPERTY_VALUE_MAX];
706
707 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800708 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700709 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800710 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100711
712 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700713 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800714
715 property_get("persist.sys.sf.color_mode", value, "0");
716 mForceColorMode = static_cast<ColorMode>(atoi(value));
Lucas Dupin00f16422020-03-11 11:33:04 -0700717
718 property_get("persist.sys.sf.disable_blurs", value, "0");
719 bool disableBlurs = atoi(value);
720 mDisableBlurs = disableBlurs;
721 ALOGI_IF(disableBlurs, "Disabling blur effects, user preference.");
Romain Guy11d63f42017-07-20 12:47:14 -0700722}
723
Mathias Agopiana67e4182012-06-19 17:26:12 -0700724void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800725 // Start boot animation service by setting a property mailbox
726 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700727 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800728 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700729 if (mStartPropertySetThread->join() != NO_ERROR) {
730 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800731 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700732}
733
Mathias Agopian875d8e12013-06-07 15:35:48 -0700734size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700735 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700736}
737
Mathias Agopian875d8e12013-06-07 15:35:48 -0700738size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700739 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700740}
741
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800742// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800743
Jamie Gennis582270d2011-08-17 18:19:00 -0700744bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800745 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800746 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800747 return authenticateSurfaceTextureLocked(bufferProducer);
748}
749
750bool SurfaceFlinger::authenticateSurfaceTextureLocked(
751 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800752 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800753 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800754}
755
Brian Anderson6b376712017-04-04 10:51:39 -0700756status_t SurfaceFlinger::getSupportedFrameTimestamps(
757 std::vector<FrameEvent>* outSupported) const {
758 *outSupported = {
759 FrameEvent::REQUESTED_PRESENT,
760 FrameEvent::ACQUIRE,
761 FrameEvent::LATCH,
762 FrameEvent::FIRST_REFRESH_START,
763 FrameEvent::LAST_REFRESH_START,
764 FrameEvent::GPU_COMPOSITION_DONE,
765 FrameEvent::DEQUEUE_READY,
766 FrameEvent::RELEASE,
767 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700768 ConditionalLock _l(mStateLock,
769 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700770 if (!getHwComposer().hasCapability(
771 HWC2::Capability::PresentFenceIsNotReliable)) {
772 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
773 }
774 return NO_ERROR;
775}
776
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800777status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
778 if (!displayToken || !state) {
779 return BAD_VALUE;
780 }
781
782 Mutex::Autolock lock(mStateLock);
783
784 const auto display = getDisplayDeviceLocked(displayToken);
785 if (!display) {
786 return NAME_NOT_FOUND;
787 }
788
789 state->layerStack = display->getLayerStack();
790 state->orientation = display->getOrientation();
791
792 const Rect viewport = display->getViewport();
793 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
794
795 return NO_ERROR;
796}
797
798status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
799 if (!displayToken || !info) {
800 return BAD_VALUE;
801 }
802
803 Mutex::Autolock lock(mStateLock);
804
805 const auto display = getDisplayDeviceLocked(displayToken);
806 if (!display) {
807 return NAME_NOT_FOUND;
808 }
809
Dominik Laskowski55c85402020-01-21 16:25:47 -0800810 if (const auto connectionType = display->getConnectionType())
811 info->connectionType = *connectionType;
812 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800813 return INVALID_OPERATION;
814 }
815
816 if (mEmulatedDisplayDensity) {
817 info->density = mEmulatedDisplayDensity;
818 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800819 info->density = info->connectionType == DisplayConnectionType::Internal
820 ? mInternalDisplayDensity
821 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800822 }
823
824 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200825 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800826
827 return NO_ERROR;
828}
829
Dominik Laskowski22488f62019-03-28 09:53:04 -0700830status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800831 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700832 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700833 return BAD_VALUE;
834 }
835
Dominik Laskowski22488f62019-03-28 09:53:04 -0700836 Mutex::Autolock lock(mStateLock);
837
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800838 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700839 if (!displayId) {
840 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700841 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700842
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800843 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700844
Dan Stoza7f7da322014-05-02 15:26:25 -0700845 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700846
Dominik Laskowski075d3172018-05-24 15:50:06 -0700847 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800848 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700849
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800850 auto width = hwConfig->getWidth();
851 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700852
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800853 auto xDpi = hwConfig->getDpiX();
854 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700855
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800856 if (isInternal &&
857 (internalDisplayOrientation == ui::ROTATION_90 ||
858 internalDisplayOrientation == ui::ROTATION_270)) {
859 std::swap(width, height);
860 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700861 }
862
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800863 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800864
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800865 if (mEmulatedDisplayDensity) {
866 config.xDpi = mEmulatedDisplayDensity;
867 config.yDpi = mEmulatedDisplayDensity;
868 } else {
869 config.xDpi = xDpi;
870 config.yDpi = yDpi;
871 }
872
873 const nsecs_t period = hwConfig->getVsyncPeriod();
874 config.refreshRate = 1e9f / period;
875
876 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
877 config.appVsyncOffset = offsets.late.app;
878 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800879 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800880
Andy McFadden91b2ca82014-06-13 14:04:23 -0700881 // This is how far in advance a buffer must be queued for
882 // presentation at a given time. If you want a buffer to appear
883 // on the screen at time N, you must submit the buffer before
884 // (N - presentationDeadline).
885 //
886 // Normally it's one full refresh period (to give SF a chance to
887 // latch the buffer), but this can be reduced by configuring a
888 // DispSync offset. Any additional delays introduced by the hardware
889 // composer or panel must be accounted for here.
890 //
891 // We add an additional 1ms to allow for processing time and
892 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800893 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700894
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800895 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700896 }
897
Dan Stoza7f7da322014-05-02 15:26:25 -0700898 return NO_ERROR;
899}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700900
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700901status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
902 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700903 return BAD_VALUE;
904 }
905
Ana Krulecc2870422019-01-29 19:00:58 -0800906 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700907 return NO_ERROR;
908}
909
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700910int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
911 const auto display = getDisplayDevice(displayToken);
912 if (!display) {
913 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800914 return BAD_VALUE;
915 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700916
Steven Thomasc9098452019-09-30 17:15:05 -0700917 if (display->isPrimary()) {
918 std::lock_guard<std::mutex> lock(mActiveConfigLock);
919 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800920 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700921 }
Steven Thomasc9098452019-09-30 17:15:05 -0700922 }
Ady Abraham2139f732019-11-13 18:56:40 -0800923
924 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700925}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700926
Ady Abraham03b02dd2019-03-21 15:40:11 -0700927void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800928 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800929 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abraham2139f732019-11-13 18:56:40 -0800930 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800931
Ady Abrahamb838aed2019-02-12 15:30:16 -0800932 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800933 if (mDesiredActiveConfigChanged) {
934 // If a config change is pending, just cache the latest request in
935 // mDesiredActiveConfig
936 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
937 mDesiredActiveConfig = info;
938 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
939 } else {
940 // Check is we are already at the desired config
941 const auto display = getDefaultDisplayDeviceLocked();
942 if (!display || display->getActiveConfig() == refreshRate.configId) {
943 return;
944 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800945
Ady Abraham59db0a32020-03-02 18:04:20 -0800946 // Initiate a config change.
947 mDesiredActiveConfigChanged = true;
948 mDesiredActiveConfig = info;
949
Ady Abrahamb838aed2019-02-12 15:30:16 -0800950 // This will trigger HWC refresh without resetting the idle timer.
951 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700952 // Start receiving vsync samples now, so that we can detect a period
953 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800954 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700955 // As we called to set period, we will call to onRefreshRateChangeCompleted once
956 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700957 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800958
Ady Abraham9e16a482019-12-03 17:19:41 -0800959 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
960 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800961 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700962
963 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800964 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700965 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800966}
967
968status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
969 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800970
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100971 if (!displayToken) {
972 return BAD_VALUE;
973 }
Ady Abraham838de062019-02-04 10:24:03 -0800974
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100975 status_t result = NO_ERROR;
976
977 postMessageSync(new LambdaMessage([&]() {
978 const auto display = getDisplayDeviceLocked(displayToken);
979 if (!display) {
980 ALOGE("Attempt to set allowed display configs for invalid display token %p",
981 displayToken.get());
982 result = BAD_VALUE;
983 } else if (display->isVirtual()) {
984 ALOGW("Attempt to set allowed display configs for virtual display");
985 result = BAD_VALUE;
986 } else {
987 HwcConfigIndexType config(mode);
988 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
Steven Thomasd4071902020-03-24 16:02:53 -0700989 result = setDesiredDisplayConfigSpecsInternal(display,
990 scheduler::RefreshRateConfigs::
991 Policy{config, refreshRate.fps,
992 refreshRate.fps},
993 /*overridePolicy=*/false);
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100994 }
995 }));
996
997 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800998}
999
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001000void SurfaceFlinger::setActiveConfigInternal() {
1001 ATRACE_CALL();
1002
Dominik Laskowski22488f62019-03-28 09:53:04 -07001003 const auto display = getDefaultDisplayDeviceLocked();
1004 if (!display) {
1005 return;
1006 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001007
Alec Mouri8de697e2020-03-19 10:52:01 -07001008 auto& oldRefreshRate =
1009 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1010
Dominik Laskowski22488f62019-03-28 09:53:04 -07001011 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001012 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001013 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001014 display->setActiveConfig(mUpcomingActiveConfig.configId);
1015
Ady Abraham2e1dd892020-03-05 13:48:36 -08001016 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001017 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Alec Mouri8de697e2020-03-19 10:52:01 -07001018 if (refreshRate.vsyncPeriod != oldRefreshRate.vsyncPeriod) {
1019 mTimeStats->incrementRefreshRateSwitches();
1020 }
Ady Abraham9e16a482019-12-03 17:19:41 -08001021 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1022 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -08001023 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -07001024
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001025 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001026 const nsecs_t vsyncPeriod =
1027 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
1028 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -08001029 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001030 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001031 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001032}
1033
Ady Abraham53852a52019-05-28 18:07:44 -07001034void SurfaceFlinger::desiredActiveConfigChangeDone() {
1035 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1036 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1037 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001038
Ady Abraham2e1dd892020-03-05 13:48:36 -08001039 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001040 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001041 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001042 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1043 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001044}
1045
Dominik Laskowski22488f62019-03-28 09:53:04 -07001046bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001047 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001048 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001049 if (mCheckPendingFence) {
Alec Mouri6d414b52020-03-17 11:18:05 -07001050 if (previousFramePending()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001051 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001052 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001053 return true;
1054 }
1055
1056 // We received the present fence from the HWC, so we assume it successfully updated
1057 // the config, hence we update SF.
1058 mCheckPendingFence = false;
1059 setActiveConfigInternal();
1060 }
1061
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001062 // Store the local variable to release the lock.
1063 ActiveConfigInfo desiredActiveConfig;
1064 {
1065 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001066 if (!mDesiredActiveConfigChanged) {
1067 return false;
1068 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001069 desiredActiveConfig = mDesiredActiveConfig;
1070 }
1071
Ady Abraham2e1dd892020-03-05 13:48:36 -08001072 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001073 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1074 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1075 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001076 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001077 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1078 // display is not valid or we are already in the requested mode
1079 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001080 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001081 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001082 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001083
Ady Abraham838de062019-02-04 10:24:03 -08001084 // Desired active config was set, it is different than the config currently in use, however
1085 // allowed configs might have change by the time we process the refresh.
1086 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001087 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001088 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001089 return false;
1090 }
Alec Mouri7f015182019-07-11 13:56:22 -07001091
Ady Abrahamb838aed2019-02-12 15:30:16 -08001092 mUpcomingActiveConfig = desiredActiveConfig;
1093 const auto displayId = display->getId();
1094 LOG_ALWAYS_FATAL_IF(!displayId);
1095
Ady Abraham2139f732019-11-13 18:56:40 -08001096 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001097
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001098 // TODO(b/142753666) use constrains
1099 HWC2::VsyncPeriodChangeConstraints constraints;
1100 constraints.desiredTimeNanos = systemTime();
1101 constraints.seamlessRequired = false;
1102
1103 HWC2::VsyncPeriodChangeTimeline outTimeline;
1104 auto status =
1105 getHwComposer().setActiveConfigWithConstraints(*displayId,
1106 mUpcomingActiveConfig.configId.value(),
1107 constraints, &outTimeline);
1108 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001109 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1110 // to be sent. We just log the error in this case.
1111 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001112 return false;
1113 }
1114
1115 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1116 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001117 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001118 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001119}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001120
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001121status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1122 Vector<ColorMode>* outColorModes) {
1123 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001124 return BAD_VALUE;
1125 }
1126
Peiyong Lina52f0292018-03-14 17:26:31 -07001127 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001128 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001129 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001130 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1131
1132 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1133 if (!displayId) {
1134 return NAME_NOT_FOUND;
1135 }
1136
Dominik Laskowski075d3172018-05-24 15:50:06 -07001137 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001138 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001139 }
Michael Wright28f24d02016-07-12 13:30:53 -07001140 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001141
1142 // If it's built-in display and the configuration claims it's not wide color capable,
1143 // filter out all wide color modes. The typical reason why this happens is that the
1144 // hardware is not good enough to support GPU composition of wide color, and thus the
1145 // OEMs choose to disable this capability.
1146 if (isInternalDisplay && !hasWideColorDisplay) {
1147 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1148 isWideColorMode);
1149 } else {
1150 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1151 }
Michael Wright28f24d02016-07-12 13:30:53 -07001152
1153 return NO_ERROR;
1154}
1155
Daniel Solomon42d04562019-01-20 21:03:19 -08001156status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1157 ui::DisplayPrimaries &primaries) {
1158 if (!displayToken) {
1159 return BAD_VALUE;
1160 }
1161
1162 // Currently we only support this API for a single internal display.
1163 if (getInternalDisplayToken() != displayToken) {
1164 return BAD_VALUE;
1165 }
1166
1167 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1168 return NO_ERROR;
1169}
1170
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001171ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1172 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001173 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001174 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001175 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001176}
1177
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001178status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001179 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001180 Vector<ColorMode> modes;
1181 getDisplayColorModes(displayToken, &modes);
1182 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1183 if (mode < ColorMode::NATIVE || !exists) {
1184 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1185 decodeColorMode(mode).c_str(), mode, displayToken.get());
1186 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001187 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001188 const auto display = getDisplayDevice(displayToken);
1189 if (!display) {
1190 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1191 decodeColorMode(mode).c_str(), mode, displayToken.get());
1192 } else if (display->isVirtual()) {
1193 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1194 decodeColorMode(mode).c_str(), mode);
1195 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001196 display->getCompositionDisplay()->setColorProfile(
1197 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1198 RenderIntent::COLORIMETRIC,
1199 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001200 }
1201 }));
1202
Michael Wright28f24d02016-07-12 13:30:53 -07001203 return NO_ERROR;
1204}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001205
Galia Peycheva5492cb52019-10-30 14:13:16 +01001206status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1207 bool* outSupport) const {
1208 Mutex::Autolock _l(mStateLock);
1209
1210 if (!displayToken) {
1211 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1212 return BAD_VALUE;
1213 }
1214 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1215 if (!displayId) {
1216 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1217 displayToken.get());
1218 return NAME_NOT_FOUND;
1219 }
1220 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1221 HWC2::DisplayCapability::AutoLowLatencyMode);
1222 return NO_ERROR;
1223}
1224
1225void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1226 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1227}
1228
1229void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1230 if (!displayToken) {
1231 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1232 return;
1233 }
1234 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1235 if (!displayId) {
1236 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1237 displayToken.get());
1238 return;
1239 }
1240
1241 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1242}
1243
1244status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1245 bool* outSupport) const {
1246 Mutex::Autolock _l(mStateLock);
1247
1248 if (!displayToken) {
1249 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1250 return BAD_VALUE;
1251 }
1252 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1253 if (!displayId) {
1254 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1255 displayToken.get());
1256 return NAME_NOT_FOUND;
1257 }
1258
1259 std::vector<HWC2::ContentType> outSupportedContentTypes;
1260 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1261 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1262 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1263 return NO_ERROR;
1264}
1265
1266void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1267 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1268}
1269
1270void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1271 if (!displayToken) {
1272 ALOGE("setGameContentType() failed. Missing display token.");
1273 return;
1274 }
1275 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1276 if (!displayId) {
1277 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1278 displayToken.get());
1279 return;
1280 }
1281
1282 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1283 getHwComposer().setContentType(*displayId, type);
1284}
1285
Svetoslavd85084b2014-03-20 10:28:31 -07001286status_t SurfaceFlinger::clearAnimationFrameStats() {
1287 Mutex::Autolock _l(mStateLock);
1288 mAnimFrameTracker.clearStats();
1289 return NO_ERROR;
1290}
1291
1292status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1293 Mutex::Autolock _l(mStateLock);
1294 mAnimFrameTracker.getStats(outStats);
1295 return NO_ERROR;
1296}
1297
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001298status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1299 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001300 Mutex::Autolock _l(mStateLock);
1301
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001302 const auto display = getDisplayDeviceLocked(displayToken);
1303 if (!display) {
1304 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001305 return BAD_VALUE;
1306 }
1307
Peiyong Linfb069302018-04-25 14:34:31 -07001308 // At this point the DisplayDeivce should already be set up,
1309 // meaning the luminance information is already queried from
1310 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001311 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001312 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1313 capabilities.getDesiredMaxLuminance(),
1314 capabilities.getDesiredMaxAverageLuminance(),
1315 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001316
1317 return NO_ERROR;
1318}
1319
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001320std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1321 const DisplayDevice& display) const {
1322 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1323 // avoid repetitive HAL IPC and EDID parsing.
1324 const auto displayId = display.getId();
1325 LOG_FATAL_IF(!displayId);
1326
1327 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1328 LOG_FATAL_IF(!hwcDisplayId);
1329
1330 uint8_t port;
1331 DisplayIdentificationData data;
1332 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1333 ALOGV("%s: No identification data.", __FUNCTION__);
1334 return {};
1335 }
1336
1337 const auto info = parseDisplayIdentificationData(port, data);
1338 if (!info) {
1339 return {};
1340 }
1341 return info->deviceProductInfo;
1342}
1343
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001344status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1345 ui::PixelFormat* outFormat,
1346 ui::Dataspace* outDataspace,
1347 uint8_t* outComponentMask) const {
1348 if (!outFormat || !outDataspace || !outComponentMask) {
1349 return BAD_VALUE;
1350 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001351 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001352 if (!display || !display->getId()) {
1353 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1354 return BAD_VALUE;
1355 }
1356 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1357 outDataspace, outComponentMask);
1358}
1359
Kevin DuBois74e53772018-11-19 10:52:38 -08001360status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1361 bool enable, uint8_t componentMask,
1362 uint64_t maxFrames) const {
1363 const auto display = getDisplayDevice(displayToken);
1364 if (!display || !display->getId()) {
1365 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1366 return BAD_VALUE;
1367 }
1368
1369 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1370 componentMask, maxFrames);
1371}
1372
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001373status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1374 uint64_t maxFrames, uint64_t timestamp,
1375 DisplayedFrameStats* outStats) const {
1376 const auto display = getDisplayDevice(displayToken);
1377 if (!display || !display->getId()) {
1378 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1379 return BAD_VALUE;
1380 }
1381
1382 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1383 outStats);
1384}
1385
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001386status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1387 if (!outSupported) {
1388 return BAD_VALUE;
1389 }
1390 *outSupported = getRenderEngine().supportsProtectedContent();
1391 return NO_ERROR;
1392}
1393
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001394status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1395 bool* outIsWideColorDisplay) const {
1396 if (!displayToken || !outIsWideColorDisplay) {
1397 return BAD_VALUE;
1398 }
1399 Mutex::Autolock _l(mStateLock);
1400 const auto display = getDisplayDeviceLocked(displayToken);
1401 if (!display) {
1402 return BAD_VALUE;
1403 }
Peiyong Linff84a152019-05-17 18:36:19 -07001404
1405 // Use hasWideColorDisplay to override built-in display.
1406 const auto displayId = display->getId();
1407 if (displayId && displayId == getInternalDisplayIdLocked()) {
1408 *outIsWideColorDisplay = hasWideColorDisplay;
1409 return NO_ERROR;
1410 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001411 *outIsWideColorDisplay = display->hasWideColorGamut();
1412 return NO_ERROR;
1413}
1414
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001415status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001416 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001417 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001418
Dominik Laskowski6505f792019-09-18 11:10:05 -07001419 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1420 mEventQueue->setEventConnection(
1421 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001422 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001423 }));
1424
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001425 return NO_ERROR;
1426}
1427
1428status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001429 Mutex::Autolock lock(mStateLock);
1430 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001431}
1432
Lloyd Pique755e3192018-01-31 16:46:15 -08001433status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1434 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001435 // Try to acquire a lock for 1s, fail gracefully
1436 const status_t err = mStateLock.timedLock(s2ns(1));
1437 const bool locked = (err == NO_ERROR);
1438 if (!locked) {
1439 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1440 return TIMED_OUT;
1441 }
1442
1443 outLayers->clear();
1444 mCurrentState.traverseInZOrder([&](Layer* layer) {
1445 outLayers->push_back(layer->getLayerDebugInfo());
1446 });
1447
1448 mStateLock.unlock();
1449 return NO_ERROR;
1450}
1451
Peiyong Linc6780972018-10-28 15:24:08 -07001452status_t SurfaceFlinger::getCompositionPreference(
1453 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1454 Dataspace* outWideColorGamutDataspace,
1455 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001456 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001457 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001458 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001459 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001460 return NO_ERROR;
1461}
1462
Dan Stozaec460082018-12-17 15:35:09 -08001463status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1464 const sp<IBinder>& stopLayerHandle,
1465 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001466 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001467 return BAD_VALUE;
1468 }
1469 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001470 return NO_ERROR;
1471}
1472
Dan Stozaec460082018-12-17 15:35:09 -08001473status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001474 if (!listener) {
1475 return BAD_VALUE;
1476 }
Dan Stozaec460082018-12-17 15:35:09 -08001477 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001478 return NO_ERROR;
1479}
Dan Gittik57e63c52019-01-18 16:37:54 +00001480
1481status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1482 bool* outSupport) const {
1483 if (!displayToken || !outSupport) {
1484 return BAD_VALUE;
1485 }
1486 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1487 if (!displayId) {
1488 return NAME_NOT_FOUND;
1489 }
1490 *outSupport =
1491 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1492 return NO_ERROR;
1493}
1494
1495status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1496 float brightness) const {
1497 if (!displayToken) {
1498 return BAD_VALUE;
1499 }
1500 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1501 if (!displayId) {
1502 return NAME_NOT_FOUND;
1503 }
1504 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1505}
1506
Ady Abraham8532d012019-05-08 14:50:56 -07001507status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1508 PowerHint powerHint = static_cast<PowerHint>(hintId);
1509
1510 if (powerHint == PowerHint::INTERACTION) {
1511 mScheduler->notifyTouchEvent();
1512 }
1513
1514 return NO_ERROR;
1515}
1516
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001517// ----------------------------------------------------------------------------
1518
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001519sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001520 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001521 const auto& handle =
1522 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001523
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001524 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001525}
1526
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001527// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001528
1529void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001530 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001531}
1532
1533void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001534 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001535 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001536 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001537}
1538
1539void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001540 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001541 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001542 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001543}
1544
1545void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001546 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001547 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001548}
1549
1550status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001551 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001552 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001553}
1554
1555status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001556 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001557 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001558 if (res == NO_ERROR) {
1559 msg->wait();
1560 }
1561 return res;
1562}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001563
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001564void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001565 do {
1566 waitForEvent();
1567 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001568}
1569
Dominik Laskowski83b88212018-12-11 13:34:06 -08001570nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001571 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001572 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1573 return 0;
1574 }
1575
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001576 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001577}
1578
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001579void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001580 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001581 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001582 ATRACE_NAME("SF onVsync");
1583
Steven Thomas3cfac282017-02-06 12:29:30 -08001584 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001585 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001586 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001587 return;
1588 }
1589
Dominik Laskowski075d3172018-05-24 15:50:06 -07001590 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001591 return;
1592 }
1593
Dominik Laskowski075d3172018-05-24 15:50:06 -07001594 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001595 // For now, we don't do anything with external display vsyncs.
1596 return;
1597 }
1598
Alec Mourif8e689c2019-05-20 18:32:22 -07001599 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001600 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001601 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001602 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001603 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001604}
1605
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001606void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001607 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1608 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001609}
1610
Ady Abraham2139f732019-11-13 18:56:40 -08001611bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001612 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001613}
1614
Ady Abraham2139f732019-11-13 18:56:40 -08001615void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1616 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001617 const auto display = getDefaultDisplayDeviceLocked();
1618 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001619 return;
1620 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001621 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001622
Ana Krulec7d1d6832018-12-27 11:10:09 -08001623 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001624 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1625 ALOGV("Skipping config %d as it is not part of allowed configs",
1626 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001627 return;
1628 }
1629
Ady Abraham2139f732019-11-13 18:56:40 -08001630 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001631}
1632
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001633void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001634 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001635 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001636 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001637
Lloyd Piqueba04e622017-12-14 17:11:26 -08001638 // Ignore events that do not have the right sequenceId.
1639 if (sequenceId != getBE().mComposerSequenceId) {
1640 return;
1641 }
1642
Steven Thomasb02664d2017-07-26 18:48:28 -07001643 // Only lock if we're not on the main thread. This function is normally
1644 // called on a hwbinder thread, but for the primary display it's called on
1645 // the main thread with the state lock already held, so don't attempt to
1646 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001647 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001648
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001649 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001650
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001651 if (std::this_thread::get_id() == mMainThreadId) {
1652 // Process all pending hot plug events immediately if we are on the main thread.
1653 processDisplayHotplugEventsLocked();
1654 }
1655
Lloyd Piqueba04e622017-12-14 17:11:26 -08001656 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001657}
1658
Ady Abraham7159f572019-10-11 11:10:18 -07001659void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001660 int32_t sequenceId, hwc2_display_t /*display*/,
1661 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1662 Mutex::Autolock lock(mStateLock);
1663 if (sequenceId != getBE().mComposerSequenceId) {
1664 return;
1665 }
1666 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001667}
1668
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001669void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1670 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1671 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1672}
1673
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001674void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001675 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001676 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001677 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001678 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001679 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001680}
1681
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001682void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001683 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001684
1685 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1686 // display power state.
1687 postMessageAsync(new LambdaMessage(
1688 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1689}
1690
1691void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1692 ATRACE_CALL();
1693
Ady Abraham27c70212019-06-11 10:52:26 -07001694 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1695
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001696 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001697 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1698 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001699 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001700 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001701 }
Mathias Agopian86303202012-07-24 22:46:10 -07001702}
1703
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001704// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001705void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001706 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001707 // Clear the drawing state so that the logic inside of
1708 // handleTransactionLocked will fire. It will determine the delta between
1709 // mCurrentState and mDrawingState and re-apply all changes when we make the
1710 // transition.
1711 mDrawingState.displays.clear();
1712 mDisplays.clear();
1713}
1714
Steven Thomas050b2c82017-03-06 11:45:16 -08001715void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001716 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001717 if (!mVrFlinger)
1718 return;
1719 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001720 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001721 return;
1722 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001723
Lloyd Pique441d5042018-10-18 16:49:51 -07001724 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001725 ALOGE("Vr flinger is only supported for remote hardware composer"
1726 " service connections. Ignoring request to transition to vr"
1727 " flinger.");
1728 mVrFlingerRequestsDisplay = false;
1729 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001730 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001731
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001732 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001733
Steven Thomas0123ac62018-07-12 11:32:34 -07001734 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001735 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001736
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001737 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001738
1739 // Clear out all the output layers from the composition engine for all
1740 // displays before destroying the hardware composer interface. This ensures
1741 // any HWC layers are destroyed through that interface before it becomes
1742 // invalid.
1743 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001744 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001745 }
1746
Steven Thomas0123ac62018-07-12 11:32:34 -07001747 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1748 // called below. Clear the reference now so we don't accidentally use it
1749 // later.
1750 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001751
Steven Thomasb02664d2017-07-26 18:48:28 -07001752 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001753 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001754 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001755
Steven Thomasb02664d2017-07-26 18:48:28 -07001756 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001757 // Delete the current instance before creating the new one
1758 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1759 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1760 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001761 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001762
Lloyd Pique441d5042018-10-18 16:49:51 -07001763 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001764 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001765
1766 if (vrFlingerRequestsDisplay) {
1767 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001768 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001769
1770 mVisibleRegionsDirty = true;
1771 invalidateHwcGeometry();
1772
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001773 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001774 display = getDefaultDisplayDeviceLocked();
1775 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001776 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001777
Steven Thomasb02664d2017-07-26 18:48:28 -07001778 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001779 const nsecs_t vsyncPeriod = getVsyncPeriod();
1780 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001781
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001782 // The present fences returned from vr_hwc are not an accurate
1783 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001784 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001785
Steven Thomasb02664d2017-07-26 18:48:28 -07001786 // Use phase of 0 since phase is not known.
1787 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001788 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001789 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001790
Ana Krulecc2870422019-01-29 19:00:58 -08001791 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001792
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001793 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001794 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001795}
1796
Alec Mouri6d414b52020-03-17 11:18:05 -07001797sp<Fence> SurfaceFlinger::previousFrameFence() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001798 // We are storing the last 2 present fences. If sf's phase offset is to be
1799 // woken up before the actual vsync but targeting the next vsync, we need to check
1800 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001801 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1802 : mPreviousPresentFences[1];
1803}
1804
1805bool SurfaceFlinger::previousFramePending(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1806 ATRACE_CALL();
1807 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001808
Ady Abraham11579302019-09-19 12:35:58 -07001809 if (fence == Fence::NO_FENCE) {
1810 return false;
1811 }
1812
1813 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1814 fence->wait(graceTimeMs);
1815 }
1816
1817 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001818}
1819
Alec Mouri6d414b52020-03-17 11:18:05 -07001820nsecs_t SurfaceFlinger::previousFramePresentTime() NO_THREAD_SAFETY_ANALYSIS {
1821 const sp<Fence>& fence = previousFrameFence();
1822
1823 if (fence == Fence::NO_FENCE) {
1824 return Fence::SIGNAL_TIME_INVALID;
1825 }
1826
1827 return fence->getSignalTime();
1828}
1829
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001830void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001831 DisplayStatInfo stats;
1832 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001833 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001834 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001835 mExpectedPresentTime.store(
1836 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001837}
1838
Dominik Laskowski22488f62019-03-28 09:53:04 -07001839void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001840 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001841 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001842 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001843 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001844 // calculate the expected present time once and use the cached
1845 // value throughout this frame to make sure all layers are
1846 // seeing this same value.
Alec Mouri6d414b52020-03-17 11:18:05 -07001847 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001848 populateExpectedPresentTime();
1849
Ady Abraham11579302019-09-19 12:35:58 -07001850 // When Backpressure propagation is enabled we want to give a small grace period
1851 // for the present fence to fire instead of just giving up on this frame to handle cases
1852 // where present fence is just about to get signaled.
1853 const int graceTimeForPresentFenceMs =
1854 (mPropagateBackpressure &&
1855 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1856 ? 1
1857 : 0;
Alec Mouri6d414b52020-03-17 11:18:05 -07001858
1859 // Pending frames may trigger backpressure propagation.
1860 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1861 previousFramePending(
1862 graceTimeForPresentFenceMs)};
1863
1864 // Frame missed counts for metrics tracking.
1865 // A frame is missed if the prior frame is still pending. If no longer pending,
1866 // then we still count the frame as missed if the predicted present time
1867 // was further in the past than when the fence actually fired.
1868
1869 // Add some slop to correct for drift. This should generally be
1870 // smaller than a typical frame duration, but should not be so small
1871 // that it reports reasonable drift as a missed frame.
1872 DisplayStatInfo stats;
1873 mScheduler->getDisplayStatInfo(&stats);
1874 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1875 const nsecs_t previousPresentTime = previousFramePresentTime();
1876 const TracedOrdinal<bool> frameMissed =
1877 {"PrevFrameMissed",
1878 framePending ||
1879 (previousPresentTime >= 0 &&
1880 (lastExpectedPresentTime < previousPresentTime - frameMissedSlop))};
1881 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001882 mHadDeviceComposition && frameMissed};
Alec Mouri6d414b52020-03-17 11:18:05 -07001883 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001884 mHadClientComposition && frameMissed};
1885
Alec Mouricc0fc602019-02-26 21:45:19 -08001886 if (frameMissed) {
1887 mFrameMissedCount++;
1888 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001889 if (mMissedFrameJankCount == 0) {
1890 mMissedFrameJankStart = systemTime();
1891 }
1892 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001893 }
1894
Alec Mouri40189b02019-03-05 15:07:54 -08001895 if (hwcFrameMissed) {
1896 mHwcFrameMissedCount++;
1897 }
1898
1899 if (gpuFrameMissed) {
1900 mGpuFrameMissedCount++;
1901 }
1902
Alec Mouri6d414b52020-03-17 11:18:05 -07001903 if (framePending && mPropagateBackpressure) {
Ady Abrahamadb9a992019-09-19 21:21:55 +00001904 if ((hwcFrameMissed && !gpuFrameMissed) ||
1905 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001906 signalLayerUpdate();
1907 break;
1908 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001909 }
Dan Stoza50182882016-07-08 12:02:20 -07001910
Alec Mouri989ddbe2020-02-06 09:26:19 -08001911 // Our jank window is always at least 100ms since we missed a
1912 // frame...
1913 static constexpr nsecs_t kMinJankyDuration =
1914 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1915 // ...but if it's larger than 1s then we missed the trace cutoff.
1916 static constexpr nsecs_t kMaxJankyDuration =
1917 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1918 // If we're in a user build then don't push any atoms
1919 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1920 const auto displayDevice = getDefaultDisplayDeviceLocked();
1921 // Only report jank when the display is on, as displays in DOZE
1922 // power mode may operate at a different frame rate than is
1923 // reported in their config, which causes noticeable (but less
1924 // severe) jank.
1925 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1926 const nsecs_t currentTime = systemTime();
1927 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1928 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1929 ATRACE_NAME("Jank detected");
1930 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1931 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1932 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1933 jankyDurationMillis, mMissedFrameJankCount);
1934 }
1935
1936 // We either reported a jank event or we missed the trace
1937 // window, so clear counters here.
1938 if (jankDuration > kMinJankyDuration) {
1939 mMissedFrameJankCount = 0;
1940 mMissedFrameJankStart = 0;
1941 }
1942 }
1943 }
1944
Steven Thomas050b2c82017-03-06 11:45:16 -08001945 // Now that we're going to make it to the handleMessageTransaction()
1946 // call below it's safe to call updateVrFlinger(), which will
1947 // potentially trigger a display handoff.
1948 updateVrFlinger();
1949
Dan Stoza6b9454d2014-11-07 16:00:59 -08001950 bool refreshNeeded = handleMessageTransaction();
1951 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001952
Ana Krulecc84d09b2019-11-02 23:10:29 +01001953 // Layers need to get updated (in the previous line) before we can use them for
1954 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001955 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1956 // and may eventually call to ~Layer() if it holds the last reference
1957 {
1958 Mutex::Autolock _l(mStateLock);
1959 mScheduler->chooseRefreshRateForContent();
1960 }
1961
Ana Krulecc84d09b2019-11-02 23:10:29 +01001962 if (performSetActiveConfig()) {
1963 break;
1964 }
1965
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001966 updateCursorAsync();
1967 updateInputFlinger();
1968
Dan Stoza58784442014-12-02 16:58:17 -08001969 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001970 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001971 // Signal a refresh if a transaction modified the window state,
1972 // a new buffer was latched, or if HWC has requested a full
1973 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001974 if (mFrameStartTime <= 0) {
1975 // We should only use the time of the first invalidate
1976 // message that signals a refresh as the beginning of the
1977 // frame. Otherwise the real frame time will be
1978 // underestimated.
1979 mFrameStartTime = frameStart;
1980 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001981 signalRefresh();
1982 }
1983 break;
1984 }
1985 case MessageQueue::REFRESH: {
1986 handleMessageRefresh();
1987 break;
1988 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001989 }
1990}
1991
Dan Stoza6b9454d2014-11-07 16:00:59 -08001992bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001993 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001994 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001995
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001996 bool flushedATransaction = flushTransactionQueues();
1997
1998 bool runHandleTransaction = transactionFlags &&
1999 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
2000
2001 if (runHandleTransaction) {
2002 handleTransaction(eTransactionMask);
2003 } else {
2004 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002005 }
2006
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002007 if (transactionFlushNeeded()) {
2008 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002009 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002010
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002011 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002012}
2013
Mathias Agopian4fec8732012-06-29 14:12:52 -07002014void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002015 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002016
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002017 mRefreshPending = false;
2018
Lloyd Piqueab039b52019-02-13 14:22:42 -08002019 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002020 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002021 for (const auto& [_, display] : mDisplays) {
2022 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2023 }
2024 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002025 if (auto layerFE = layer->getCompositionEngineLayerFE())
2026 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002027 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002028 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2029 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002030 if (auto layerFE = layer->getCompositionEngineLayerFE())
2031 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002032 }
2033
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002034 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002035 refreshArgs.outputColorSetting = useColorManagement
2036 ? mDisplayColorSetting
2037 : compositionengine::OutputColorSetting::kUnmanaged;
2038 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2039 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002040
2041 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2042 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002043 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002044
2045 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2046 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2047 mDrawingState.colorMatrixChanged = false;
2048 }
2049
2050 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2051
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002052 if (mDebugRegion != 0) {
2053 refreshArgs.devOptFlashDirtyRegionsDelay =
2054 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2055 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002056
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002057 mGeometryInvalid = false;
2058
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002059 // Store the present time just before calling to the composition engine so we could notify
2060 // the scheduler.
2061 const auto presentTime = systemTime();
2062
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002063 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002064 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2065 // Reset the frame start time now that we've recorded this frame.
2066 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002067
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002068 mScheduler->onDisplayRefreshed(presentTime);
2069
David Sodmanfa9b2af2017-12-24 13:28:59 -08002070 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002071 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002072
Lloyd Pique66d68602019-02-13 14:23:31 -08002073 mHadClientComposition =
2074 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2075 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002076 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2077 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002078 });
2079 mHadDeviceComposition =
2080 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2081 auto& displayDevice = tokenDisplayPair.second;
2082 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2083 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002084 mReusedClientComposition =
2085 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2086 auto& displayDevice = tokenDisplayPair.second;
2087 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2088 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002089
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002090 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002091
David Sodman7e4ae112018-02-09 15:02:28 -08002092 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002093 if (mVisibleRegionsDirty) {
2094 mVisibleRegionsDirty = false;
2095 if (mTracingEnabled) {
2096 mTracing.notify("visibleRegionsDirty");
2097 }
2098 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002099
2100 if (mCompositionEngine->needsAnotherUpdate()) {
2101 signalLayerUpdate();
2102 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002103}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002104
David Sodmanfa9b2af2017-12-24 13:28:59 -08002105
2106bool SurfaceFlinger::handleMessageInvalidate() {
2107 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002108 bool refreshNeeded = handlePageFlip();
2109
Vishnu Nair4351ad52019-02-11 14:13:02 -08002110 if (mVisibleRegionsDirty) {
2111 computeLayerBounds();
2112 }
2113
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002114 for (auto& layer : mLayersPendingRefresh) {
2115 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002116 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002117 invalidateLayerStack(layer, visibleReg);
2118 }
2119 mLayersPendingRefresh.clear();
2120 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002121}
2122
Ana Krulece588e312018-09-18 12:32:24 -07002123void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2124 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002125 // Update queue of past composite+present times and determine the
2126 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002127 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002128 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002129 while (!getBE().mCompositePresentTimes.empty()) {
2130 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002131 // Cached values should have been updated before calling this method,
2132 // which helps avoid duplicate syscalls.
2133 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2134 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2135 break;
2136 }
2137 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002138 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002139 }
2140
2141 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002142 while (getBE().mCompositePresentTimes.size() > 16) {
2143 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002144 }
2145
Ana Krulece588e312018-09-18 12:32:24 -07002146 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002147}
2148
Ana Krulece588e312018-09-18 12:32:24 -07002149void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2150 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002151 // Integer division and modulo round toward 0 not -inf, so we need to
2152 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002153 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2154 ? (stats.vsyncPeriod -
2155 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2156 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002157
Ady Abraham9e16a482019-12-03 17:19:41 -08002158 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002159 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002160 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002161 }
2162
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002163 // Snap the latency to a value that removes scheduling jitter from the
2164 // composition and present times, which often have >1ms of jitter.
2165 // Reducing jitter is important if an app attempts to extrapolate
2166 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002167 // Snapping also allows an app to precisely calculate
2168 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002169 nsecs_t bias = stats.vsyncPeriod / 2;
2170 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2171 nsecs_t snappedCompositeToPresentLatency =
2172 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002173
David Sodman99974d22017-11-28 12:04:33 -08002174 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002175 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2176 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002177 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002178}
2179
David Sodman2b406362017-12-15 13:33:47 -08002180void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002181{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002182 ATRACE_CALL();
2183 ALOGV("postComposition");
2184
Brian Andersonf6386862016-10-31 16:34:13 -07002185 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002186 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002187 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002188 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002189 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002190 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002191
David Sodman73beded2017-11-15 11:56:06 -08002192 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002193 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002194 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002195 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002196 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2197 ->getRenderSurface()
2198 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002199 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002200 } else {
2201 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2202 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002203
David Sodman73beded2017-11-15 11:56:06 -08002204 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002205 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2206 mPreviousPresentFences[0] = displayDevice
2207 ? getHwComposer().getPresentFence(*displayDevice->getId())
2208 : Fence::NO_FENCE;
2209 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002210 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002211
Ana Krulece588e312018-09-18 12:32:24 -07002212 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002213 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002214
Lloyd Piqueab039b52019-02-13 14:22:42 -08002215 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2216 // be sampled a little later than when we started doing work for this frame,
2217 // but that should be okay since updateCompositorTiming has snapping logic.
2218 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2219 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002220 CompositorTiming compositorTiming;
2221 {
David Sodman99974d22017-11-28 12:04:33 -08002222 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2223 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002224 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002225
Edgar Arriaga844fa672020-01-16 14:21:42 -08002226 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002227 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2228 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002229 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002230 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002231 }
Robert Carr2047fae2016-11-28 14:09:09 -08002232 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002233
Ady Abraham92fa2f42020-02-11 15:33:56 -08002234 if (displayDevice && displayDevice->isPrimary() &&
2235 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002236 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002237 }
2238
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002239 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002240 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2241 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002242 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002243 }
2244 }
2245
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002246 if (mAnimCompositionPending) {
2247 mAnimCompositionPending = false;
2248
Brian Anderson4e606e32017-03-16 15:34:57 -07002249 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002250 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002251 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002252 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002253 // The HWC doesn't support present fences, so use the refresh
2254 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002255 const nsecs_t presentTime =
2256 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002257 mAnimFrameTracker.setActualPresentTime(presentTime);
2258 }
2259 mAnimFrameTracker.advanceFrame();
2260 }
Dan Stozab90cf072015-03-05 11:05:59 -08002261
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002262 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002263 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002264 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002265 }
2266
Vishnu Nair9b079a22020-01-21 14:36:08 -08002267 if (mReusedClientComposition) {
2268 mTimeStats->incrementClientCompositionReusedFrames();
2269 }
2270
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002271 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002272
Alec Mouri717bcb62020-02-10 17:07:19 -08002273 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2274 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2275 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2276
Lloyd Pique32cbe282018-10-19 13:09:22 -07002277 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2278 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002279 return;
2280 }
2281
2282 nsecs_t currentTime = systemTime();
2283 if (mHasPoweredOff) {
2284 mHasPoweredOff = false;
2285 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002286 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002287 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002288 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2289 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002290 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002291 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002292 }
David Sodman4a36e932017-11-07 14:29:47 -08002293 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002294 }
David Sodman4a36e932017-11-07 14:29:47 -08002295 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002296
2297 {
2298 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002299 if (mTexturePool.size() < mTexturePoolSize) {
2300 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002301 const size_t offset = mTexturePool.size();
2302 mTexturePool.resize(mTexturePoolSize);
2303 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2304 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002305 } else if (mTexturePool.size() > mTexturePoolSize) {
2306 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2307 const size_t offset = mTexturePoolSize;
2308 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2309 mTexturePool.resize(mTexturePoolSize);
2310 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002311 }
2312 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002313
Ady Abrahambe0f9482019-04-24 15:41:53 -07002314 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002315 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002316
Kevin DuBois413287f2019-02-25 08:46:47 -08002317 if (mLumaSampling && mRegionSamplingThread) {
2318 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002319 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002320
2321 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2322 // side-effect of getTotalSize(), so we check that again here
2323 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002324 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002325 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2326 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002327}
2328
Vishnu Nair4351ad52019-02-11 14:13:02 -08002329void SurfaceFlinger::computeLayerBounds() {
2330 for (const auto& pair : mDisplays) {
2331 const auto& displayDevice = pair.second;
2332 const auto display = displayDevice->getCompositionDisplay();
2333 for (const auto& layer : mDrawingState.layersSortedByZ) {
2334 // only consider the layers on the given layer stack
2335 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002336 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002337 }
2338
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002339 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2340 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002341 }
2342 }
2343}
2344
David Sodmanfa9b2af2017-12-24 13:28:59 -08002345void SurfaceFlinger::postFrame()
2346{
2347 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002348 const auto display = getDefaultDisplayDeviceLocked();
2349 if (display && getHwComposer().isConnected(*display->getId())) {
2350 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002351 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2352 logFrameStats();
2353 }
2354 }
2355}
2356
Mathias Agopian87baae12012-07-31 12:38:26 -07002357void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002358{
Mathias Agopian841cde52012-03-01 15:44:37 -08002359 ATRACE_CALL();
2360
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002361 // here we keep a copy of the drawing state (that is the state that's
2362 // going to be overwritten by handleTransactionLocked()) outside of
2363 // mStateLock so that the side-effects of the State assignment
2364 // don't happen with mStateLock held (which can cause deadlocks).
2365 State drawingState(mDrawingState);
2366
Mathias Agopianca4d3602011-05-19 15:38:14 -07002367 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002368 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369
Mathias Agopianca4d3602011-05-19 15:38:14 -07002370 // Here we're guaranteed that some transaction flags are set
2371 // so we can call handleTransactionLocked() unconditionally.
2372 // We call getTransactionFlags(), which will also clear the flags,
2373 // with mStateLock held to guarantee that mCurrentState won't change
2374 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002375
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002376 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002377 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002378 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002379
Mathias Agopianca4d3602011-05-19 15:38:14 -07002380 mDebugInTransaction = 0;
2381 invalidateHwcGeometry();
2382 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002383}
2384
Lloyd Piqueba04e622017-12-14 17:11:26 -08002385void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2386 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002387 const std::optional<DisplayIdentificationInfo> info =
2388 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002389
Dominik Laskowski075d3172018-05-24 15:50:06 -07002390 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002391 continue;
2392 }
2393
Dominik Laskowski55c85402020-01-21 16:25:47 -08002394 const DisplayId displayId = info->id;
2395 const auto it = mPhysicalDisplayTokens.find(displayId);
2396
Lloyd Piqueba04e622017-12-14 17:11:26 -08002397 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002398 if (it == mPhysicalDisplayTokens.end()) {
2399 ALOGV("Creating display %s", to_string(displayId).c_str());
2400
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002401 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002402 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002403 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002404
Dominik Laskowski075d3172018-05-24 15:50:06 -07002405 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002406 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2407 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002408 state.isSecure = true; // All physical displays are currently considered secure.
2409 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002410
2411 sp<IBinder> token = new BBinder();
2412 mCurrentState.displays.add(token, state);
2413 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2414
Dominik Laskowski075d3172018-05-24 15:50:06 -07002415 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002416 } else {
2417 ALOGV("Recreating display %s", to_string(displayId).c_str());
2418
2419 const auto token = it->second;
2420 auto& state = mCurrentState.displays.editValueFor(token);
2421 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002422 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002423 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002424 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002425
Dominik Laskowski55c85402020-01-21 16:25:47 -08002426 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002427 if (index >= 0) {
2428 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2429 mInterceptor->saveDisplayDeletion(state.sequenceId);
2430 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002431 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002432 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002433 }
2434
2435 processDisplayChangesLocked();
2436 }
2437
2438 mPendingHotplugEvents.clear();
2439}
2440
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002441void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002442 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2443 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002444}
2445
Lloyd Pique99d3da52018-01-22 17:48:03 -08002446sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002447 const wp<IBinder>& displayToken,
2448 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002449 const DisplayDeviceState& state,
2450 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002451 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002452 auto displayId = compositionDisplay->getDisplayId();
2453 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002454 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002455 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002456 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002457 creationArgs.hasWideColorGamut = false;
2458 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002459
Dominik Laskowski55c85402020-01-21 16:25:47 -08002460 if (const auto& physical = state.physical) {
2461 creationArgs.connectionType = physical->type;
2462 }
2463
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002464 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002465 creationArgs.isPrimary = isInternalDisplay;
2466
2467 if (useColorManagement && displayId) {
2468 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002469 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002470 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002471 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002472 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002473
Dominik Laskowski7e045462018-05-30 13:02:02 -07002474 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002475 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002476 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002477 }
tangrobin6753a022018-08-10 10:58:54 +08002478 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002479
Dominik Laskowski075d3172018-05-24 15:50:06 -07002480 if (displayId) {
2481 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002482 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002483 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002484 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002485
Lloyd Pique90c115d2018-09-18 21:39:42 -07002486 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002487 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002488 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002489
Lloyd Pique99d3da52018-01-22 17:48:03 -08002490 // Make sure that composition can never be stalled by a virtual display
2491 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002492 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002493 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002494 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2495 }
2496
Dominik Laskowski718f9602019-11-09 20:01:35 -08002497 creationArgs.physicalOrientation =
2498 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002499
Lloyd Pique99d3da52018-01-22 17:48:03 -08002500 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002501 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002502
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002503 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002504
2505 if (maxFrameBufferAcquiredBuffers >= 3) {
2506 nativeWindowSurface->preallocateBuffers();
2507 }
2508
2509 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002510 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002511 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002512 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002513 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002514 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002515 display->getCompositionDisplay()->setColorProfile(
2516 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2517 RenderIntent::COLORIMETRIC,
2518 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002519 if (!state.isVirtual()) {
2520 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002521 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2522 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002523 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002524
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002525 display->setLayerStack(state.layerStack);
2526 display->setProjection(state.orientation, state.viewport, state.frame);
2527 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002528
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002529 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002530}
2531
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002532void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2533 const DisplayDeviceState& state) {
2534 int width = 0;
2535 int height = 0;
2536 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2537 if (state.physical) {
2538 const auto& activeConfig =
2539 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2540 width = activeConfig->getWidth();
2541 height = activeConfig->getHeight();
2542 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2543 } else if (state.surface != nullptr) {
2544 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2545 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2546 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2547 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2548 int intPixelFormat;
2549 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2550 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2551 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2552 } else {
2553 // Virtual displays without a surface are dormant:
2554 // they have external state (layer stack, projection,
2555 // etc.) but no internal state (i.e. a DisplayDevice).
2556 return;
2557 }
2558
2559 compositionengine::DisplayCreationArgsBuilder builder;
2560 if (const auto& physical = state.physical) {
2561 builder.setPhysical({physical->id, physical->type});
2562 }
2563 builder.setPixels(ui::Size(width, height));
2564 builder.setPixelFormat(pixelFormat);
2565 builder.setIsSecure(state.isSecure);
2566 builder.setLayerStackId(state.layerStack);
2567 builder.setPowerAdvisor(&mPowerAdvisor);
2568 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2569 builder.setName(state.displayName);
2570 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2571
2572 sp<compositionengine::DisplaySurface> displaySurface;
2573 sp<IGraphicBufferProducer> producer;
2574 sp<IGraphicBufferProducer> bqProducer;
2575 sp<IGraphicBufferConsumer> bqConsumer;
2576 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2577
2578 std::optional<DisplayId> displayId = compositionDisplay->getId();
2579
2580 if (state.isVirtual()) {
2581 sp<VirtualDisplaySurface> vds =
2582 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2583 bqConsumer, state.displayName);
2584
2585 displaySurface = vds;
2586 producer = vds;
2587 } else {
2588 ALOGE_IF(state.surface != nullptr,
2589 "adding a supported display, but rendering "
2590 "surface is provided (%p), ignoring it",
2591 state.surface.get());
2592
2593 LOG_ALWAYS_FATAL_IF(!displayId);
2594 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2595 maxGraphicsWidth, maxGraphicsHeight);
2596 producer = bqProducer;
2597 }
2598
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002599 LOG_FATAL_IF(!displaySurface);
2600 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2601 displaySurface, producer);
2602 mDisplays.emplace(displayToken, display);
2603 if (!state.isVirtual()) {
2604 LOG_FATAL_IF(!displayId);
2605 dispatchDisplayHotplugEvent(displayId->value, true);
2606 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002607
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002608 if (display->isPrimary()) {
2609 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002610 }
2611}
2612
2613void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2614 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2615 // Save display ID before disconnecting.
2616 const auto displayId = display->getId();
2617 display->disconnect();
2618
2619 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002620 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002621 dispatchDisplayHotplugEvent(displayId->value, false);
2622 }
2623 }
2624
2625 mDisplays.erase(displayToken);
2626}
2627
2628void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2629 const DisplayDeviceState& currentState,
2630 const DisplayDeviceState& drawingState) {
2631 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2632 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002633 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002634 // changing the surface is like destroying and recreating the DisplayDevice
2635 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2636 display->disconnect();
2637 }
2638 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002639 if (const auto& physical = currentState.physical) {
2640 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2641 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002642 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002643 if (currentState.physical) {
2644 initializeDisplays();
2645 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002646 return;
2647 }
2648
2649 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2650 if (currentState.layerStack != drawingState.layerStack) {
2651 display->setLayerStack(currentState.layerStack);
2652 }
2653 if ((currentState.orientation != drawingState.orientation) ||
2654 (currentState.viewport != drawingState.viewport) ||
2655 (currentState.frame != drawingState.frame)) {
2656 display->setProjection(currentState.orientation, currentState.viewport,
2657 currentState.frame);
2658 }
2659 if (currentState.width != drawingState.width ||
2660 currentState.height != drawingState.height) {
2661 display->setDisplaySize(currentState.width, currentState.height);
2662 if (display->isPrimary()) {
2663 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2664 }
2665 }
2666 }
2667}
2668
Lloyd Pique347200f2017-12-14 17:00:15 -08002669void SurfaceFlinger::processDisplayChangesLocked() {
2670 // here we take advantage of Vector's copy-on-write semantics to
2671 // improve performance by skipping the transaction entirely when
2672 // know that the lists are identical
2673 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2674 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2675 if (!curr.isIdenticalTo(draw)) {
2676 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002677
2678 // find the displays that were removed
2679 // (ie: in drawing state but not in current state)
2680 // also handle displays that changed
2681 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002682 for (size_t i = 0; i < draw.size(); i++) {
2683 const wp<IBinder>& displayToken = draw.keyAt(i);
2684 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002685 if (j < 0) {
2686 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002687 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002688 } else {
2689 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002690 const DisplayDeviceState& currentState = curr[j];
2691 const DisplayDeviceState& drawingState = draw[i];
2692 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002693 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002694 }
2695
2696 // find displays that were added
2697 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002698 for (size_t i = 0; i < curr.size(); i++) {
2699 const wp<IBinder>& displayToken = curr.keyAt(i);
2700 if (draw.indexOfKey(displayToken) < 0) {
2701 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002702 }
2703 }
2704 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002705
2706 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002707}
2708
Mathias Agopian87baae12012-07-31 12:38:26 -07002709void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002710{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002711 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2712
Dan Stoza7dde5992015-05-22 09:51:44 -07002713 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002714 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002715 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002716 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002717
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002718 /*
2719 * Traversal of the children
2720 * (perform the transaction for each of them if needed)
2721 */
2722
Marissa Wall06255332019-03-27 13:48:27 -07002723 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002724 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002725 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002726 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002727
2728 const uint32_t flags = layer->doTransaction(0);
2729 if (flags & Layer::eVisibleRegion)
2730 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002731
2732 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002733 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002734 }
Robert Carr2047fae2016-11-28 14:09:09 -08002735 });
Marissa Wall06255332019-03-27 13:48:27 -07002736 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737 }
2738
2739 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002740 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741 */
2742
Mathias Agopiane57f2922012-08-09 16:29:12 -07002743 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002744 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002745 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002746 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002747
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002748 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002749 // The transform hint might have changed for some layers
2750 // (either because a display has changed, or because a layer
2751 // as changed).
2752 //
2753 // Walk through all the layers in currentLayers,
2754 // and update their transform hint.
2755 //
2756 // If a layer is visible only on a single display, then that
2757 // display is used to calculate the hint, otherwise we use the
2758 // default display.
2759 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002760 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002761 // the hint is set before we acquire a buffer from the surface texture.
2762 //
2763 // NOTE: layer transactions have taken place already, so we use their
2764 // drawing state. However, SurfaceFlinger's own transaction has not
2765 // happened yet, so we must use the current state layer list
2766 // (soon to become the drawing state list).
2767 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002768 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002769 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002770 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002771 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002772 // NOTE: we rely on the fact that layers are sorted by
2773 // layerStack first (so we don't have to traverse the list
2774 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002775 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002776 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002777 currentlayerStack = layerStack;
2778 // figure out if this layerstack is mirrored
2779 // (more than one display) if so, pick the default display,
2780 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002781 hintDisplay = nullptr;
2782 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002783 if (display->getCompositionDisplay()
2784 ->belongsInOutput(layer->getLayerStack(),
2785 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002786 if (hintDisplay) {
2787 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002788 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002789 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002790 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002791 }
2792 }
2793 }
2794 }
Chet Haase91d25932013-04-11 15:24:55 -07002795
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002796 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002797 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2798 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002799
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002800 // could be null when this layer is using a layerStack
2801 // that is not visible on any display. Also can occur at
2802 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002803 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002804 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002805
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002806 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002807 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002808 if (hintDisplay) {
2809 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002810 }
Robert Carr2047fae2016-11-28 14:09:09 -08002811
2812 first = false;
2813 });
Mathias Agopian84300952012-11-21 16:02:13 -08002814 }
2815
2816
Mathias Agopian3559b072012-08-15 13:46:03 -07002817 /*
2818 * Perform our own transaction if needed
2819 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002820
2821 if (mLayersAdded) {
2822 mLayersAdded = false;
2823 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002824 mVisibleRegionsDirty = true;
2825 }
2826
2827 // some layers might have been removed, so
2828 // we need to update the regions they're exposing.
2829 if (mLayersRemoved) {
2830 mLayersRemoved = false;
2831 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002832 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002833 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002834 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002835 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002836 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002837 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002838 }
Robert Carr2047fae2016-11-28 14:09:09 -08002839 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002840 }
2841
Vishnu Nairec0ab382019-02-13 15:32:56 -08002842 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002843 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002844}
2845
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002846void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002847 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002848 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002849 return;
2850 }
2851
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002852 if (mVisibleRegionsDirty || mInputInfoChanged) {
2853 mInputInfoChanged = false;
2854 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002855 } else if (mInputWindowCommands.syncInputWindows) {
2856 // If the caller requested to sync input windows, but there are no
2857 // changes to input windows, notify immediately.
2858 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002859 }
2860
Arthur Hung6cbb9752019-09-05 16:38:18 +08002861 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002862}
2863
2864void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002865 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002866
Robert Carra1257842020-01-31 13:48:28 -08002867 // We use a simple caching algorithm here. mInputDirty begins as true,
2868 // after we call setInputWindows we set it to false, so
2869 // in the future we wont call it again.. We set input dirty to true again
2870 // when any layer that hasInput() has a transaction performed on it
2871 // or when any parent or relative parent of such a layer has a transaction
2872 // performed on it. Not all of these transactions will really result in
2873 // input changes but all input changes will spring from these transactions
2874 // so the cache is safe but not optimal. It seems like it might be annoyingly
2875 // costly to cache and comapre the actual InputWindowHandle vector though.
Robert Carr0854b992020-03-11 12:09:42 -07002876 if (!mInputDirty && !mInputWindowCommands.syncInputWindows) {
Robert Carra1257842020-01-31 13:48:28 -08002877 return;
2878 }
2879
Robert Carr720e5062018-07-30 17:45:14 -07002880 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2881 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002882 // When calculating the screen bounds we ignore the transparent region since it may
2883 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002884 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002885 }
2886 });
chaviw291d88a2019-02-14 10:33:58 -08002887
2888 mInputFlinger->setInputWindows(inputHandles,
2889 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2890 : nullptr);
Robert Carra1257842020-01-31 13:48:28 -08002891
2892 mInputDirty = false;
Robert Carr720e5062018-07-30 17:45:14 -07002893}
2894
Vishnu Nairec0ab382019-02-13 15:32:56 -08002895void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002896 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002897 mPendingInputWindowCommands.clear();
2898}
2899
Riley Andrews03414a12014-07-01 14:22:59 -07002900void SurfaceFlinger::updateCursorAsync()
2901{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002902 compositionengine::CompositionRefreshArgs refreshArgs;
2903 for (const auto& [_, display] : mDisplays) {
2904 if (display->getId()) {
2905 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002906 }
2907 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002908
2909 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002910}
2911
Ady Abraham2139f732019-11-13 18:56:40 -08002912void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002913 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2914 // If this is called from the main thread mStateLock must be locked before
2915 // Currently the only way to call this function from the main thread is from
2916 // Sheduler::chooseRefreshRateForContent
2917
2918 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002919 changeRefreshRateLocked(refreshRate, event);
2920}
2921
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002922void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2923 if (mScheduler) {
2924 // In practice it's not allowed to hotplug in/out the primary display once it's been
2925 // connected during startup, but some tests do it, so just warn and return.
2926 ALOGW("Can't re-init scheduler");
2927 return;
2928 }
2929
Ady Abraham2139f732019-11-13 18:56:40 -08002930 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002931 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002932 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002933 primaryDisplayId),
2934 currentConfig);
2935 mRefreshRateStats =
2936 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2937 currentConfig, HWC_POWER_MODE_OFF);
2938 mRefreshRateStats->setConfigMode(currentConfig);
2939
Ady Abraham9e16a482019-12-03 17:19:41 -08002940 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2941
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002942 // start the EventThread
2943 mScheduler =
2944 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002945 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002946 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002947 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002948 impl::EventThread::InterceptVSyncsCallback());
2949 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002950 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002951 [this](nsecs_t timestamp) {
2952 mInterceptor->saveVSyncEvent(timestamp);
2953 });
2954
2955 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2956 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002957 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002958
2959 mRegionSamplingThread =
2960 new RegionSamplingThread(*this, *mScheduler,
2961 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002962 // Dispatch a config change request for the primary display on scheduler
2963 // initialization, so that the EventThreads always contain a reference to a
2964 // prior configuration.
2965 //
2966 // This is a bit hacky, but this avoids a back-pointer into the main SF
2967 // classes from EventThread, and there should be no run-time binder cost
2968 // anyway since there are no connected apps at this point.
2969 const nsecs_t vsyncPeriod =
2970 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2971 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2972 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002973}
2974
Mathias Agopian4fec8732012-06-29 14:12:52 -07002975void SurfaceFlinger::commitTransaction()
2976{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002977 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002978
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002979 mTransactionPending = false;
2980 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002981 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002982}
2983
Lloyd Pique58e24a32019-08-01 15:50:14 -07002984void SurfaceFlinger::commitTransactionLocked() {
2985 if (!mLayersPendingRemoval.isEmpty()) {
2986 // Notify removed layers now that they can't be drawn from
2987 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002988 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002989
2990 // Ensure any buffers set to display on any children are released.
2991 if (l->isRemovedFromCurrentState()) {
2992 l->latchAndReleaseBuffer();
2993 }
2994
2995 // If the layer has been removed and has no parent, then it will not be reachable
2996 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2997 // ensure we can copy its current to drawing state.
2998 if (!l->getParent()) {
2999 mOffscreenLayers.emplace(l.get());
3000 }
3001 }
3002 mLayersPendingRemoval.clear();
3003 }
3004
3005 // If this transaction is part of a window animation then the next frame
3006 // we composite should be considered an animation as well.
3007 mAnimCompositionPending = mAnimTransactionPending;
3008
3009 mDrawingState = mCurrentState;
3010 // clear the "changed" flags in current state
3011 mCurrentState.colorMatrixChanged = false;
3012
Edgar Arriaga844fa672020-01-16 14:21:42 -08003013 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003014 layer->commitChildList();
3015
3016 // If the layer can be reached when traversing mDrawingState, then the layer is no
3017 // longer offscreen. Remove the layer from the offscreenLayer set.
3018 if (mOffscreenLayers.count(layer)) {
3019 mOffscreenLayers.erase(layer);
3020 }
3021 });
3022
3023 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003024 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003025}
3026
Nataniel Borges2b796da2019-02-15 13:32:18 -08003027void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3028 if (mTracingEnabledChanged) {
3029 mTracingEnabled = mTracing.isEnabled();
3030 mTracingEnabledChanged = false;
3031 }
3032
3033 // Synchronize with Tracing thread
3034 std::unique_lock<std::mutex> lock;
3035 if (mTracingEnabled) {
3036 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3037 }
3038
3039 lockedOperation();
3040
3041 // Synchronize with Tracing thread
3042 if (mTracingEnabled) {
3043 lock.unlock();
3044 }
3045}
3046
chaviw74d90ad2019-04-26 14:45:26 -07003047void SurfaceFlinger::commitOffscreenLayers() {
3048 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003049 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003050 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3051 if (!trFlags) return;
3052
3053 layer->doTransaction(0);
3054 layer->commitChildList();
3055 });
3056 }
3057}
3058
Chia-I Wuab0c3192017-08-01 11:29:00 -07003059void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003060 for (const auto& [token, displayDevice] : mDisplays) {
3061 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003062 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003063 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003064 }
3065 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003066}
3067
Dan Stoza6b9454d2014-11-07 16:00:59 -08003068bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003069{
Ady Abraham09bd3922019-04-08 10:44:56 -07003070 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003071 ALOGV("handlePageFlip");
3072
Brian Andersond6927fb2016-07-23 23:37:30 -07003073 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003074
Mathias Agopian4fec8732012-06-29 14:12:52 -07003075 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003076 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003077 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003078
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003079 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3080
Eric Penner51c59cd2014-07-28 19:51:58 -07003081 // Store the set of layers that need updates. This set must not change as
3082 // buffers are being latched, as this could result in a deadlock.
3083 // Example: Two producers share the same command stream and:
3084 // 1.) Layer 0 is latched
3085 // 2.) Layer 0 gets a new frame
3086 // 2.) Layer 1 gets a new frame
3087 // 3.) Layer 1 is latched.
3088 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3089 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003090 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003091 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003092 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003093 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003094 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003095 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003096 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003097 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003098 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003099 } else {
3100 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003101 }
Robert Carr2047fae2016-11-28 14:09:09 -08003102 });
3103
chaviw49a108c2019-08-12 11:23:06 -07003104 // The client can continue submitting buffers for offscreen layers, but they will not
3105 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3106 // layers to ensure dequeueBuffer doesn't block indefinitely.
3107 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003108 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003109 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3110 }
3111
Lloyd Piquef2c79392018-12-20 16:23:33 -08003112 if (!mLayersWithQueuedFrames.empty()) {
3113 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3114 // writes to Layer current state. See also b/119481871
3115 Mutex::Autolock lock(mStateLock);
3116
3117 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003118 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003119 mLayersPendingRefresh.push_back(layer);
3120 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003121 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003122 if (layer->isBufferLatched()) {
3123 newDataLatched = true;
3124 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003125 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003126 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003127
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003128 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003129
3130 // If we will need to wake up at some time in the future to deal with a
3131 // queued frame that shouldn't be displayed during this vsync period, wake
3132 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003133 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003134 signalLayerUpdate();
3135 }
3136
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003137 // enter boot animation on first buffer latch
3138 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3139 ALOGI("Enter boot animation");
3140 mBootStage = BootStage::BOOTANIMATION;
3141 }
3142
Edgar Arriaga844fa672020-01-16 14:21:42 -08003143 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003144
Dan Stoza6b9454d2014-11-07 16:00:59 -08003145 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003146 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003147}
3148
Mathias Agopianad456f92011-01-13 17:53:01 -08003149void SurfaceFlinger::invalidateHwcGeometry()
3150{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003151 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003152}
3153
Robert Carrc0df3122019-04-11 13:18:21 -07003154status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3155 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3156 const sp<IBinder>& parentHandle,
3157 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003158 // add this layer to the current state list
3159 {
3160 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003161 sp<Layer> parent;
3162 if (parentHandle != nullptr) {
3163 parent = fromHandle(parentHandle);
3164 if (parent == nullptr) {
3165 return NAME_NOT_FOUND;
3166 }
3167 } else {
3168 parent = parentLayer;
3169 }
3170
Ady Abraham0a525092020-03-03 12:51:24 -08003171 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003172 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003173 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003174 return NO_MEMORY;
3175 }
Robert Carrc0df3122019-04-11 13:18:21 -07003176
3177 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3178
Robert Carrb89ea9d2018-12-10 13:01:14 -08003179 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003180 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003181 } else if (parent == nullptr) {
3182 lbc->onRemovedFromCurrentState();
3183 } else if (parent->isRemovedFromCurrentState()) {
3184 parent->addChild(lbc);
3185 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003186 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003187 parent->addChild(lbc);
3188 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003189
Yiwei Zhang243b3782018-05-15 17:40:04 -07003190 if (gbc != nullptr) {
3191 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3192 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3193 mMaxGraphicBufferProducerListSize,
3194 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3195 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003196 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003197 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003198 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003199 }
3200
Mathias Agopian96f08192010-06-02 23:28:45 -07003201 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003202 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003203
Dan Stoza7d89d062015-04-30 13:29:25 -07003204 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003205}
3206
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003207uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003208 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003209}
3210
Mathias Agopian3f844832013-08-07 21:24:32 -07003211uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003212 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003213}
3214
Mathias Agopian3f844832013-08-07 21:24:32 -07003215uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003216 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003217}
3218
3219uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003220 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003221 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003222 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003223 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003224 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003225 }
3226 return old;
3227}
3228
Marissa Wall713b63f2018-10-17 15:42:43 -07003229bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003230 // to prevent onHandleDestroyed from being called while the lock is held,
3231 // we must keep a copy of the transactions (specifically the composer
3232 // states) around outside the scope of the lock
3233 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003234 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003235 {
3236 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003237
Valerie Haufce31b82019-04-30 16:41:14 -07003238 auto it = mTransactionQueues.begin();
3239 while (it != mTransactionQueues.end()) {
3240 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003241
Valerie Haufce31b82019-04-30 16:41:14 -07003242 while (!transactionQueue.empty()) {
3243 const auto& transaction = transactionQueue.front();
3244 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003245 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003246 transaction.states)) {
3247 setTransactionFlags(eTransactionFlushNeeded);
3248 break;
3249 }
3250 transactions.push_back(transaction);
3251 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3252 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003253 transaction.buffer, transaction.postTime,
3254 transaction.privileged, transaction.hasListenerCallbacks,
3255 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003256 transactionQueue.pop();
3257 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003258 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003259
Valerie Haufce31b82019-04-30 16:41:14 -07003260 if (transactionQueue.empty()) {
3261 it = mTransactionQueues.erase(it);
3262 mTransactionCV.broadcast();
3263 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003264 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003265 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003266 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003267 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003268 return flushedATransaction;
3269}
3270
3271bool SurfaceFlinger::transactionFlushNeeded() {
3272 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003273}
3274
chaviwca27f252018-02-06 16:46:39 -08003275
Marissa Wall17b4e452018-12-26 16:32:34 -08003276bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003277 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003278 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003279 if (!useCachedExpectedPresentTime)
3280 populateExpectedPresentTime();
3281
3282 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003283 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3284 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3285 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3286 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3287 return false;
3288 }
3289
Marissa Wall713b63f2018-10-17 15:42:43 -07003290 for (const ComposerState& state : states) {
3291 const layer_state_t& s = state.state;
3292 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3293 continue;
3294 }
3295 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003296 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003297 }
3298 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003299 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003300}
3301
Valerie Hau9dab9732019-08-20 09:29:25 -07003302void SurfaceFlinger::setTransactionState(
3303 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3304 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3305 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3306 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003307 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003308
Valerie Haubc6ddb12019-03-08 11:10:15 -08003309 const int64_t postTime = systemTime();
3310
Robert Carr14167e02019-02-13 13:50:55 -08003311 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3312
Mathias Agopian698c0872011-06-28 19:09:31 -07003313 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003314
Marissa Wall713b63f2018-10-17 15:42:43 -07003315 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003316 auto itr = mTransactionQueues.find(applyToken);
3317 // if this is an animation frame, wait until prior animation frame has
3318 // been applied by SF
3319 if (flags & eAnimation) {
3320 while (itr != mTransactionQueues.end()) {
3321 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3322 if (CC_UNLIKELY(err != NO_ERROR)) {
3323 ALOGW_IF(err == TIMED_OUT,
3324 "setTransactionState timed out "
3325 "waiting for animation frame to apply");
3326 break;
3327 }
3328 itr = mTransactionQueues.find(applyToken);
3329 }
3330 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003331
3332 // Expected present time is computed and cached on invalidate, so it may be stale.
3333 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3334 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003335 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003336 uncacheBuffer, postTime, privileged,
3337 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003338 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003339 return;
3340 }
3341
Valerie Haubc6ddb12019-03-08 11:10:15 -08003342 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003343 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3344 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003345}
3346
Valerie Hau9dab9732019-08-20 09:29:25 -07003347void SurfaceFlinger::applyTransactionState(
3348 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3349 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3350 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3351 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3352 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003353 uint32_t transactionFlags = 0;
3354
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003355 if (flags & eAnimation) {
3356 // For window updates that are part of an animation we must wait for
3357 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003358 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003359 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003360 if (CC_UNLIKELY(err != NO_ERROR)) {
3361 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003362 // caller after a few seconds.
3363 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3364 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003365 mAnimTransactionPending = false;
3366 break;
3367 }
3368 }
3369 }
3370
chaviwca27f252018-02-06 16:46:39 -08003371 for (const DisplayState& display : displays) {
3372 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003373 }
3374
Valerie Hau9dab9732019-08-20 09:29:25 -07003375 // start and end registration for listeners w/ no surface so they can get their callback. Note
3376 // that listeners with SurfaceControls will start registration during setClientStateLocked
3377 // below.
3378 for (const auto& listener : listenerCallbacks) {
3379 mTransactionCompletedThread.startRegistration(listener);
3380 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003381 }
3382
Valerie Hau9dab9732019-08-20 09:29:25 -07003383 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003384 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003385 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003386 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3387 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003388 }
3389
Valerie Hau9dab9732019-08-20 09:29:25 -07003390 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003391 mTransactionCompletedThread.endRegistration(listenerCallback);
3392 }
3393
Marissa Walle2ffb422018-10-12 11:33:52 -07003394 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003395 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003396 mTransactionCompletedThread.sendCallbacks();
3397 }
3398 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003399
chaviw273171b2018-12-26 11:46:30 -08003400 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3401
Marissa Wall947d34e2019-03-29 14:03:53 -07003402 if (uncacheBuffer.isValid()) {
3403 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003404 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003405 }
3406
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003407 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3408 // anyway. This can be used as a flush mechanism for previous async transactions.
3409 // Empty animation transaction can be used to simulate back-pressure, so also force a
3410 // transaction for empty animation transactions.
3411 if (transactionFlags == 0 &&
3412 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003413 transactionFlags = eTransactionNeeded;
3414 }
3415
Marissa Wall06255332019-03-27 13:48:27 -07003416 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3417 // so we don't have to wake up again next frame to preform an uneeded traversal.
3418 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3419 transactionFlags = transactionFlags & (~eTraversalNeeded);
3420 mTraversalNeededMainThread = true;
3421 }
3422
Mathias Agopian386aa982011-11-07 21:58:03 -08003423 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003424 if (mInterceptor->isEnabled()) {
3425 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003426 }
Irvel468051e2016-06-13 16:44:44 -07003427
Mathias Agopian386aa982011-11-07 21:58:03 -08003428 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003429 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3430 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003431 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003432
3433 // if this is a synchronous transaction, wait for it to take effect
3434 // before returning.
3435 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003436 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003437 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003438 if (flags & eAnimation) {
3439 mAnimTransactionPending = true;
3440 }
chaviw4fe36852019-04-15 16:25:49 -07003441 if (mPendingInputWindowCommands.syncInputWindows) {
3442 mPendingSyncInputWindows = true;
3443 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003444
3445 // applyTransactionState can be called by either the main SF thread or by
3446 // another process through setTransactionState. While a given process may wish
3447 // to wait on synchronous transactions, the main SF thread should never
3448 // be blocked. Therefore, we only wait if isMainThread is false.
3449 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003450 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3451 if (CC_UNLIKELY(err != NO_ERROR)) {
3452 // just in case something goes wrong in SF, return to the
3453 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003454 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3455 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003456 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003457 break;
3458 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003459 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003460 }
3461}
3462
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003463uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3464 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3465 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003466
Mathias Agopiane57f2922012-08-09 16:29:12 -07003467 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003468 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3469
3470 const uint32_t what = s.what;
3471 if (what & DisplayState::eSurfaceChanged) {
3472 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3473 state.surface = s.surface;
3474 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003475 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003476 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003477 if (what & DisplayState::eLayerStackChanged) {
3478 if (state.layerStack != s.layerStack) {
3479 state.layerStack = s.layerStack;
3480 flags |= eDisplayTransactionNeeded;
3481 }
3482 }
3483 if (what & DisplayState::eDisplayProjectionChanged) {
3484 if (state.orientation != s.orientation) {
3485 state.orientation = s.orientation;
3486 flags |= eDisplayTransactionNeeded;
3487 }
3488 if (state.frame != s.frame) {
3489 state.frame = s.frame;
3490 flags |= eDisplayTransactionNeeded;
3491 }
3492 if (state.viewport != s.viewport) {
3493 state.viewport = s.viewport;
3494 flags |= eDisplayTransactionNeeded;
3495 }
3496 }
3497 if (what & DisplayState::eDisplaySizeChanged) {
3498 if (state.width != s.width) {
3499 state.width = s.width;
3500 flags |= eDisplayTransactionNeeded;
3501 }
3502 if (state.height != s.height) {
3503 state.height = s.height;
3504 flags |= eDisplayTransactionNeeded;
3505 }
3506 }
3507
Mathias Agopiane57f2922012-08-09 16:29:12 -07003508 return flags;
3509}
3510
Steven Thomasd4071902020-03-24 16:02:53 -07003511bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003512 IPCThreadState* ipc = IPCThreadState::self();
3513 const int pid = ipc->getCallingPid();
3514 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003515 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003516 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3517 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003518 return false;
3519 }
3520 return true;
3521}
3522
Marissa Wall3dad52d2019-03-22 14:03:19 -07003523uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003524 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3525 bool privileged,
3526 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003527 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003528
Valerie Hau9dab9732019-08-20 09:29:25 -07003529 for (auto& listener : s.listeners) {
3530 // note that startRegistration will not re-register if the listener has
3531 // already be registered for a prior surface control
3532 mTransactionCompletedThread.startRegistration(listener);
3533 listenerCallbacks.insert(listener);
3534 }
3535
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003536 sp<Layer> layer = nullptr;
3537 if (s.surface) {
3538 layer = fromHandle(s.surface);
3539 } else {
3540 // The client may provide us a null handle. Treat it as if the layer was removed.
3541 ALOGW("Attempt to set client state with a null layer handle");
3542 }
chaviw8b3871a2017-11-01 17:41:01 -07003543 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003544 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003545 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003546 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003547 }
chaviw8b3871a2017-11-01 17:41:01 -07003548 return 0;
3549 }
3550
chaviw8b3871a2017-11-01 17:41:01 -07003551 uint32_t flags = 0;
3552
Garfield Tan8a3083e2018-12-03 13:21:07 -08003553 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003554
3555 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3556 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003557 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003558 layer->pushPendingState();
3559 }
3560
Valerie Hau871d6352020-01-29 08:44:02 -08003561 // Only set by BLAST adapter layers
3562 if (what & layer_state_t::eProducerDisconnect) {
3563 layer->onDisconnect();
3564 }
3565
chaviw8b3871a2017-11-01 17:41:01 -07003566 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003567 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003568 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003569 }
chaviw8b3871a2017-11-01 17:41:01 -07003570 }
3571 if (what & layer_state_t::eLayerChanged) {
3572 // NOTE: index needs to be calculated before we update the state
3573 const auto& p = layer->getParent();
3574 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003575 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003576 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003577 mCurrentState.layersSortedByZ.removeAt(idx);
3578 mCurrentState.layersSortedByZ.add(layer);
3579 // we need traversal (state changed)
3580 // AND transaction (list changed)
3581 flags |= eTransactionNeeded|eTraversalNeeded;
3582 }
chaviw8b3871a2017-11-01 17:41:01 -07003583 } else {
3584 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003585 flags |= eTransactionNeeded|eTraversalNeeded;
3586 }
3587 }
chaviw8b3871a2017-11-01 17:41:01 -07003588 }
3589 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003590 // NOTE: index needs to be calculated before we update the state
3591 const auto& p = layer->getParent();
3592 if (p == nullptr) {
3593 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3594 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3595 mCurrentState.layersSortedByZ.removeAt(idx);
3596 mCurrentState.layersSortedByZ.add(layer);
3597 // we need traversal (state changed)
3598 // AND transaction (list changed)
3599 flags |= eTransactionNeeded|eTraversalNeeded;
3600 }
3601 } else {
3602 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3603 flags |= eTransactionNeeded|eTraversalNeeded;
3604 }
chaviw8b3871a2017-11-01 17:41:01 -07003605 }
3606 }
3607 if (what & layer_state_t::eSizeChanged) {
3608 if (layer->setSize(s.w, s.h)) {
3609 flags |= eTraversalNeeded;
3610 }
3611 }
3612 if (what & layer_state_t::eAlphaChanged) {
3613 if (layer->setAlpha(s.alpha))
3614 flags |= eTraversalNeeded;
3615 }
3616 if (what & layer_state_t::eColorChanged) {
3617 if (layer->setColor(s.color))
3618 flags |= eTraversalNeeded;
3619 }
Peiyong Lind3788632018-09-18 16:01:31 -07003620 if (what & layer_state_t::eColorTransformChanged) {
3621 if (layer->setColorTransform(s.colorTransform)) {
3622 flags |= eTraversalNeeded;
3623 }
3624 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003625 if (what & layer_state_t::eBackgroundColorChanged) {
3626 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3627 flags |= eTraversalNeeded;
3628 }
3629 }
chaviw8b3871a2017-11-01 17:41:01 -07003630 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003631 // TODO: b/109894387
3632 //
3633 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3634 // rotation. To see the problem observe that if we have a square parent, and a child
3635 // of the same size, then we rotate the child 45 degrees around it's center, the child
3636 // must now be cropped to a non rectangular 8 sided region.
3637 //
3638 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3639 // private API, and the WindowManager only uses rotation in one case, which is on a top
3640 // level layer in which cropping is not an issue.
3641 //
3642 // However given that abuse of rotation matrices could lead to surfaces extending outside
3643 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3644 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3645 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003646 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003647 flags |= eTraversalNeeded;
3648 }
3649 if (what & layer_state_t::eTransparentRegionChanged) {
3650 if (layer->setTransparentRegionHint(s.transparentRegion))
3651 flags |= eTraversalNeeded;
3652 }
3653 if (what & layer_state_t::eFlagsChanged) {
3654 if (layer->setFlags(s.flags, s.mask))
3655 flags |= eTraversalNeeded;
3656 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003657 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003658 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003659 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003660 if (what & layer_state_t::eCornerRadiusChanged) {
3661 if (layer->setCornerRadius(s.cornerRadius))
3662 flags |= eTraversalNeeded;
3663 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003664 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003665 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3666 }
chaviw8b3871a2017-11-01 17:41:01 -07003667 if (what & layer_state_t::eLayerStackChanged) {
3668 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3669 // We only allow setting layer stacks for top level layers,
3670 // everything else inherits layer stack from its parent.
3671 if (layer->hasParent()) {
3672 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003673 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003674 } else if (idx < 0) {
3675 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003676 "that also does not appear in the top level layer list. Something"
3677 " has gone wrong.",
3678 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003679 } else if (layer->setLayerStack(s.layerStack)) {
3680 mCurrentState.layersSortedByZ.removeAt(idx);
3681 mCurrentState.layersSortedByZ.add(layer);
3682 // we need traversal (state changed)
3683 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003684 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003685 }
3686 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003687 if (what & layer_state_t::eDeferTransaction_legacy) {
3688 if (s.barrierHandle_legacy != nullptr) {
3689 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3690 } else if (s.barrierGbp_legacy != nullptr) {
3691 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003692 if (authenticateSurfaceTextureLocked(gbp)) {
3693 const auto& otherLayer =
3694 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003695 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003696 } else {
3697 ALOGE("Attempt to defer transaction to to an"
3698 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003699 }
3700 }
chaviw8b3871a2017-11-01 17:41:01 -07003701 // We don't trigger a traversal here because if no other state is
3702 // changed, we don't want this to cause any more work
3703 }
chaviw8b3871a2017-11-01 17:41:01 -07003704 if (what & layer_state_t::eReparentChildren) {
3705 if (layer->reparentChildren(s.reparentHandle)) {
3706 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003707 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003708 }
chaviw8b3871a2017-11-01 17:41:01 -07003709 if (what & layer_state_t::eDetachChildren) {
3710 layer->detachChildren();
3711 }
3712 if (what & layer_state_t::eOverrideScalingModeChanged) {
3713 layer->setOverrideScalingMode(s.overrideScalingMode);
3714 // We don't trigger a traversal here because if no other state is
3715 // changed, we don't want this to cause any more work
3716 }
Marissa Wall61c58622018-07-18 10:12:20 -07003717 if (what & layer_state_t::eTransformChanged) {
3718 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3719 }
3720 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3721 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3722 flags |= eTraversalNeeded;
3723 }
3724 if (what & layer_state_t::eCropChanged) {
3725 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3726 }
Marissa Wall861616d2018-10-22 12:52:23 -07003727 if (what & layer_state_t::eFrameChanged) {
3728 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3729 }
Marissa Wall61c58622018-07-18 10:12:20 -07003730 if (what & layer_state_t::eAcquireFenceChanged) {
3731 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3732 }
3733 if (what & layer_state_t::eDataspaceChanged) {
3734 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3735 }
3736 if (what & layer_state_t::eHdrMetadataChanged) {
3737 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3738 }
3739 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3740 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3741 }
3742 if (what & layer_state_t::eApiChanged) {
3743 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3744 }
3745 if (what & layer_state_t::eSidebandStreamChanged) {
3746 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3747 }
Robert Carr720e5062018-07-30 17:45:14 -07003748 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003749 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003750 layer->setInputInfo(s.inputInfo);
3751 flags |= eTraversalNeeded;
3752 } else {
3753 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3754 }
Robert Carr720e5062018-07-30 17:45:14 -07003755 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003756 if (what & layer_state_t::eMetadataChanged) {
3757 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3758 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003759 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3760 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3761 flags |= eTraversalNeeded;
3762 }
3763 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003764 if (what & layer_state_t::eShadowRadiusChanged) {
3765 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3766 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003767 if (what & layer_state_t::eFrameRateSelectionPriority) {
3768 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3769 flags |= eTraversalNeeded;
3770 }
3771 }
Steven Thomas3172e202020-01-06 19:25:30 -08003772 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003773 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3774 "SurfaceFlinger::setClientStateLocked") &&
3775 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3776 Layer::FrameRate::convertCompatibility(
3777 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003778 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003779 }
Steven Thomas3172e202020-01-06 19:25:30 -08003780 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003781 // This has to happen after we reparent children because when we reparent to null we remove
3782 // child layers from current state and remove its relative z. If the children are reparented in
3783 // the same transaction, then we have to make sure we reparent the children first so we do not
3784 // lose its relative z order.
3785 if (what & layer_state_t::eReparent) {
3786 bool hadParent = layer->hasParent();
3787 if (layer->reparent(s.parentHandleForChild)) {
3788 if (!hadParent) {
3789 mCurrentState.layersSortedByZ.remove(layer);
3790 }
3791 flags |= eTransactionNeeded | eTraversalNeeded;
3792 }
3793 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003794 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003795 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3796 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003797 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3798 }
3799 }
Marissa Wall78b72202019-03-15 14:58:34 -07003800 bool bufferChanged = what & layer_state_t::eBufferChanged;
3801 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3802 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003803 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003804 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003805 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3806 if (success) {
3807 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3808 success = ClientCache::getInstance()
3809 .registerErasedRecipient(s.cachedBuffer,
3810 wp<ClientCache::ErasedRecipient>(this));
3811 if (!success) {
3812 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3813 }
3814 }
Marissa Wall78b72202019-03-15 14:58:34 -07003815 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003816 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003817 } else if (bufferChanged) {
3818 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003819 }
Marissa Wall78b72202019-03-15 14:58:34 -07003820 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003821 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3822 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003823 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003824 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003825 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003826 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3827 // Do not put anything that updates layer state or modifies flags after
3828 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003829 return flags;
3830}
3831
chaviw273171b2018-12-26 11:46:30 -08003832uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3833 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003834 if (inputWindowCommands.syncInputWindows) {
3835 flags |= eTraversalNeeded;
3836 }
3837
Vishnu Nairec0ab382019-02-13 15:32:56 -08003838 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003839 return flags;
3840}
3841
chaviwfe94a222019-08-21 13:52:59 -07003842status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3843 sp<IBinder>* outHandle) {
3844 if (!mirrorFromHandle) {
3845 return NAME_NOT_FOUND;
3846 }
3847
3848 sp<Layer> mirrorLayer;
3849 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003850 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003851
3852 {
3853 Mutex::Autolock _l(mStateLock);
3854 mirrorFrom = fromHandle(mirrorFromHandle);
3855 if (!mirrorFrom) {
3856 return NAME_NOT_FOUND;
3857 }
3858
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003859 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3860 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003861 if (result != NO_ERROR) {
3862 return result;
3863 }
3864
3865 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3866 }
3867
3868 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3869}
3870
Marissa Wall2d814fb2019-04-09 18:52:57 +00003871status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3872 uint32_t h, PixelFormat format, uint32_t flags,
3873 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003874 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003875 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3876 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003877 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003878 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003879 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003880 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003881 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003882
Robert Carrc0df3122019-04-11 13:18:21 -07003883 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3884 "Expected only one of parentLayer or parentHandle to be non-null. "
3885 "Programmer error?");
3886
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003887 status_t result = NO_ERROR;
3888
3889 sp<Layer> layer;
3890
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003891 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003892
Evan Roskya1f1e152019-01-24 16:17:46 -08003893 bool primaryDisplayOnly = false;
3894
3895 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3896 // TODO b/64227542
3897 if (metadata.has(METADATA_WINDOW_TYPE)) {
3898 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3899 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003900 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003901 primaryDisplayOnly = true;
3902 }
3903 }
3904
Mathias Agopian3165cc22012-08-08 19:42:09 -07003905 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003906 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003907 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3908 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003909
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003910 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003911 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003912 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003913 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003914 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003915 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003916 // check if buffer size is set for color layer.
3917 if (w > 0 || h > 0) {
3918 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3919 int(w), int(h));
3920 return BAD_VALUE;
3921 }
3922
Vishnu Nairfa247b12020-02-11 08:58:26 -08003923 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3924 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003925 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003926 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003927 // check if buffer size is set for container layer.
3928 if (w > 0 || h > 0) {
3929 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3930 int(w), int(h));
3931 return BAD_VALUE;
3932 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003933 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3934 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003935 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003936 default:
3937 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003938 break;
3939 }
3940
Dan Stoza7d89d062015-04-30 13:29:25 -07003941 if (result != NO_ERROR) {
3942 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003943 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003944
Evan Roskya1f1e152019-01-24 16:17:46 -08003945 if (primaryDisplayOnly) {
3946 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003947 }
3948
Robert Carrb89ea9d2018-12-10 13:01:14 -08003949 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003950 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3951 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003952 if (result != NO_ERROR) {
3953 return result;
3954 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003955 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003956
3957 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003958 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003959}
3960
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003961std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3962 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003963
3964 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003965 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003966
Dan Stoza436ccf32018-06-21 12:10:12 -07003967 // Grab the state lock since we're accessing mCurrentState
3968 Mutex::Autolock lock(mStateLock);
3969
Cody Northropbc755282017-03-31 12:00:08 -06003970 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003971 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003972 while (matchFound) {
3973 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003974 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003975 if (layer->getName() == uniqueName) {
3976 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003977 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003978 }
3979 });
3980 }
3981
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003982 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003983 return uniqueName;
3984}
3985
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003986status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003987 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003988 LayerMetadata metadata, PixelFormat& format,
3989 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003990 sp<IGraphicBufferProducer>* gbp,
3991 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003992 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003993 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003994 case PIXEL_FORMAT_TRANSPARENT:
3995 case PIXEL_FORMAT_TRANSLUCENT:
3996 format = PIXEL_FORMAT_RGBA_8888;
3997 break;
3998 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003999 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004000 break;
4001 }
4002
chaviwb4c6e582019-08-16 14:35:07 -07004003 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004004 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004005 args.textureName = getNewTexture();
4006 {
4007 // Grab the SF state lock during this since it's the only safe way to access
4008 // RenderEngine when creating a BufferLayerConsumer
4009 // TODO: Check if this lock is still needed here
4010 Mutex::Autolock lock(mStateLock);
4011 layer = getFactory().createBufferQueueLayer(args);
4012 }
4013
Marissa Wallfd668622018-05-10 10:21:13 -07004014 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004015 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004016 *handle = layer->getHandle();
4017 *gbp = layer->getProducer();
4018 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004019 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004020
Marissa Wallfd668622018-05-10 10:21:13 -07004021 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004022 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004023}
4024
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004025status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004026 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004027 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07004028 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004029 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004030 args.displayDevice = getDefaultDisplayDevice();
4031 args.textureName = getNewTexture();
4032 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07004033 if (outTransformHint) {
4034 *outTransformHint = layer->getTransformHint();
4035 }
Marissa Wall61c58622018-07-18 10:12:20 -07004036 *handle = layer->getHandle();
4037 *outLayer = layer;
4038
4039 return NO_ERROR;
4040}
4041
Vishnu Nairfa247b12020-02-11 08:58:26 -08004042status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4043 uint32_t h, uint32_t flags, LayerMetadata metadata,
4044 sp<IBinder>* handle, sp<Layer>* outLayer) {
4045 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004046 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004047 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004048 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004049}
4050
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004051status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004052 uint32_t w, uint32_t h, uint32_t flags,
4053 LayerMetadata metadata, sp<IBinder>* handle,
4054 sp<Layer>* outLayer) {
4055 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004056 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004057 *handle = (*outLayer)->getHandle();
4058 return NO_ERROR;
4059}
4060
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004061void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004062 mLayersPendingRemoval.add(layer);
4063 mLayersRemoved = true;
4064 setTransactionFlags(eTransactionNeeded);
4065}
4066
Robert Carr695d5282018-12-18 15:27:58 -08004067void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004068{
Robert Carr2e102c92018-10-23 12:11:15 -07004069 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004070 // If a layer has a parent, we allow it to out-live it's handle
4071 // with the idea that the parent holds a reference and will eventually
4072 // be cleaned up. However no one cleans up the top-level so we do so
4073 // here.
4074 if (layer->getParent() == nullptr) {
4075 mCurrentState.layersSortedByZ.remove(layer);
4076 }
4077 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004078
4079 auto it = mLayersByLocalBinderToken.begin();
4080 while (it != mLayersByLocalBinderToken.end()) {
4081 if (it->second == layer) {
4082 it = mLayersByLocalBinderToken.erase(it);
4083 } else {
4084 it++;
4085 }
4086 }
4087
Robert Carr695d5282018-12-18 15:27:58 -08004088 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004089}
4090
Mathias Agopianb60314a2012-04-10 22:09:54 -07004091// ---------------------------------------------------------------------------
4092
Andy McFadden13a082e2012-08-24 10:16:42 -07004093void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004094 const auto display = getDefaultDisplayDeviceLocked();
4095 if (!display) return;
4096
4097 const sp<IBinder> token = display->getDisplayToken().promote();
4098 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004099
Jesse Hall01e29052013-02-19 16:13:35 -08004100 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004101 Vector<ComposerState> state;
4102 Vector<DisplayState> displays;
4103 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004104 d.what = DisplayState::eDisplayProjectionChanged |
4105 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004106 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004107 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004108 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004109 d.frame.makeInvalid();
4110 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004111 d.width = 0;
4112 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004113 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004114 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4115 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004116
Dominik Laskowskie9774092018-12-11 10:04:24 -08004117 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004118
Dominik Laskowski83b88212018-12-11 13:34:06 -08004119 const nsecs_t vsyncPeriod = getVsyncPeriod();
4120 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004121
Brian Andersond0010582017-03-07 13:20:31 -08004122 // Use phase of 0 since phase is not known.
4123 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004124 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004125 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004126}
4127
4128void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004129 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004130 postMessageAsync(
4131 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004132}
4133
Ady Abraham27c70212019-06-11 10:52:26 -07004134void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4135 if (mHWCVsyncState != enabled) {
4136 getHwComposer().setVsyncEnabled(displayId, enabled);
4137 mHWCVsyncState = enabled;
4138 }
4139}
4140
Dominik Laskowskie9774092018-12-11 10:04:24 -08004141void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004142 if (display->isVirtual()) {
4143 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004144 return;
4145 }
4146
Dominik Laskowski075d3172018-05-24 15:50:06 -07004147 const auto displayId = display->getId();
4148 LOG_ALWAYS_FATAL_IF(!displayId);
4149
Dominik Laskowski34157762018-10-31 13:07:19 -07004150 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004151
4152 int currentMode = display->getPowerMode();
4153 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004154 return;
4155 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004156
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004157 display->setPowerMode(mode);
4158
Lloyd Pique4dccc412018-01-22 17:21:36 -08004159 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004160 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004161 }
4162
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004163 if (currentMode == HWC_POWER_MODE_OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004164 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4165 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4166 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004167 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004168 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004169 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004170 mScheduler->onScreenAcquired(mAppConnectionHandle);
4171 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004172 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004173
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004174 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004175 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004176 repaintEverything();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004177 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004178 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004179 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4180 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004181 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004182 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004183 mScheduler->disableHardwareVsync(true);
4184 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004185 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004186
Ady Abraham27c70212019-06-11 10:52:26 -07004187 // Make sure HWVsync is disabled before turning off the display
4188 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4189
Dominik Laskowski075d3172018-05-24 15:50:06 -07004190 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004191 mVisibleRegionsDirty = true;
4192 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004193 } else if (mode == HWC_POWER_MODE_DOZE ||
4194 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004195 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004196 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004197 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004198 mScheduler->onScreenAcquired(mAppConnectionHandle);
4199 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004200 }
4201 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4202 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004203 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004204 mScheduler->disableHardwareVsync(true);
4205 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004206 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004207 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004208 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004209 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004210 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004211 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004212
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004213 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004214 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004215 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004216 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004217 }
4218
Dominik Laskowski34157762018-10-31 13:07:19 -07004219 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004220}
4221
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004222void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004223 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004224 const auto display = getDisplayDevice(displayToken);
4225 if (!display) {
4226 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4227 displayToken.get());
4228 } else if (display->isVirtual()) {
4229 ALOGW("Attempt to set power mode %d for virtual display", mode);
4230 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004231 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004232 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004233 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004234}
4235
4236// ---------------------------------------------------------------------------
4237
Dominik Laskowskic2867142019-01-21 11:33:38 -08004238status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4239 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004240 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004241
Mathias Agopianbd115332013-04-18 16:41:04 -07004242 IPCThreadState* ipc = IPCThreadState::self();
4243 const int pid = ipc->getCallingPid();
4244 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004245
Mathias Agopianbd115332013-04-18 16:41:04 -07004246 if ((uid != AID_SHELL) &&
4247 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004248 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4249 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004250 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004251 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004252 // (this would indicate SF is stuck, but we want to be able to
4253 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004254 status_t err = mStateLock.timedLock(s2ns(1));
4255 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004256 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004257 StringAppendF(&result,
4258 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4259 "(no locks held)\n",
4260 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004261 }
4262
Dominik Laskowskic2867142019-01-21 11:33:38 -08004263 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004264 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004265 {"--dispsync"s,
4266 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004267 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004268 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4269 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4270 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4271 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4272 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4273 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004274 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004275 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4276 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004277
Dominik Laskowskic2867142019-01-21 11:33:38 -08004278 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004279
Dominik Laskowski46470112019-08-02 13:13:11 -07004280 const auto it = dumpers.find(flag);
4281 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004282 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004283 } else if (!asProto) {
4284 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004285 }
4286
Mathias Agopian9795c422009-08-26 16:36:26 -07004287 if (locked) {
4288 mStateLock.unlock();
4289 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004290
Dominik Laskowski46470112019-08-02 13:13:11 -07004291 if (it == dumpers.end()) {
4292 const LayersProto layersProto = dumpProtoFromMainThread();
4293 if (asProto) {
4294 result.append(layersProto.SerializeAsString());
4295 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004296 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004297 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4298 result.append(LayerProtoParser::layerTreeToString(layerTree));
4299 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004300 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004301 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004302 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004303 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004304 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004305 return NO_ERROR;
4306}
4307
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004308status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4309 if (asProto && mTracing.isEnabled()) {
4310 mTracing.writeToFileAsync();
4311 }
4312
4313 return doDump(fd, DumpArgs(), asProto);
4314}
4315
Dominik Laskowskic2867142019-01-21 11:33:38 -08004316void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004317 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004318 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004319}
4320
Dominik Laskowskic2867142019-01-21 11:33:38 -08004321void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004322 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004323
Dominik Laskowskic2867142019-01-21 11:33:38 -08004324 if (args.size() > 1) {
4325 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004326 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004327 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004328 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004329 }
Robert Carr2047fae2016-11-28 14:09:09 -08004330 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004331 } else {
4332 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333 }
4334}
4335
Dominik Laskowskic2867142019-01-21 11:33:38 -08004336void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004337 const bool clearAll = args.size() < 2;
4338 const auto name = clearAll ? String8() : String8(args[1]);
4339
Edgar Arriaga844fa672020-01-16 14:21:42 -08004340 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004341 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004342 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004343 }
Robert Carr2047fae2016-11-28 14:09:09 -08004344 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004345
Svetoslavd85084b2014-03-20 10:28:31 -07004346 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004347}
4348
Dominik Laskowskic2867142019-01-21 11:33:38 -08004349void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4350 mTimeStats->parseArgs(asProto, args, result);
4351}
4352
Jamie Gennis6547ff42013-07-16 20:12:42 -07004353// This should only be called from the main thread. Otherwise it would need
4354// the lock and should use mCurrentState rather than mDrawingState.
4355void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004356 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004357 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004358 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004359
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004360 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004361}
4362
Yiwei Zhang5434a782018-12-05 18:06:32 -08004363void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004364 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004365
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004366 if (isLayerTripleBufferingDisabled())
4367 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004368
Yiwei Zhang5434a782018-12-05 18:06:32 -08004369 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4370 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4371 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4372 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4373 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4374 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004375 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004376}
4377
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004378void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004379 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004380
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004381 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004382 result.append("\n");
4383
Ady Abraham9e16a482019-12-03 17:19:41 -08004384 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004385 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004386 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004387 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004388
Steven Thomasd4071902020-03-24 16:02:53 -07004389 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004390 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004391 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004392 ", min: %.2f Hz, max: %.2f Hz",
Steven Thomasd4071902020-03-24 16:02:53 -07004393 policy.defaultConfig.value(), policy.minRefreshRate, policy.maxRefreshRate);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004394 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4395 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004396
Ana Krulecc2870422019-01-29 19:00:58 -08004397 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004398}
4399
Yiwei Zhang5434a782018-12-05 18:06:32 -08004400void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4401 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004402 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4403 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004404 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004405 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004406 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004407 }
David Sodman4a36e932017-11-07 14:29:47 -08004408 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004409 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004410 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004411 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4412 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004413}
4414
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004415void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4416 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004417 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4418 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004419 for (const auto& segment : history) {
4420 if (!segment.usedThirdBuffer) {
4421 stats.twoBufferTime += segment.totalTime;
4422 }
4423 if (segment.occupancyAverage < 1.0f) {
4424 stats.doubleBufferedTime += segment.totalTime;
4425 } else if (segment.occupancyAverage < 2.0f) {
4426 stats.tripleBufferedTime += segment.totalTime;
4427 }
4428 ++stats.numSegments;
4429 stats.totalTime += segment.totalTime;
4430 }
4431}
4432
Yiwei Zhang5434a782018-12-05 18:06:32 -08004433void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4434 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004435
4436 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4437 const size_t count = currentLayers.size();
4438 for (size_t i=0 ; i<count ; i++) {
4439 currentLayers[i]->dumpFrameEvents(result);
4440 }
4441}
4442
Yiwei Zhang5434a782018-12-05 18:06:32 -08004443void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004444 result.append("Buffering stats:\n");
4445 result.append(" [Layer name] <Active time> <Two buffer> "
4446 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004447 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004448 typedef std::tuple<std::string, float, float, float> BufferTuple;
4449 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004450 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004451 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004452 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004453 if (stats.numSegments == 0) {
4454 continue;
4455 }
4456 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4457 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4458 stats.totalTime;
4459 float doubleBufferRatio = static_cast<float>(
4460 stats.doubleBufferedTime) / stats.totalTime;
4461 float tripleBufferRatio = static_cast<float>(
4462 stats.tripleBufferedTime) / stats.totalTime;
4463 sorted.insert({activeTime, {name, twoBufferRatio,
4464 doubleBufferRatio, tripleBufferRatio}});
4465 }
4466 for (const auto& sortedPair : sorted) {
4467 float activeTime = sortedPair.first;
4468 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004469 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4470 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004471 }
4472 result.append("\n");
4473}
4474
Yiwei Zhang5434a782018-12-05 18:06:32 -08004475void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004476 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004477 const auto displayId = display->getId();
4478 if (!displayId) {
4479 continue;
4480 }
4481 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004482 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004483 continue;
4484 }
4485
Yiwei Zhang5434a782018-12-05 18:06:32 -08004486 StringAppendF(&result,
4487 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4488 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004489 uint8_t port;
4490 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004491 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004492 result.append("no identification data\n");
4493 continue;
4494 }
4495
4496 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004497 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004498 continue;
4499 }
4500
4501 const auto edid = parseEdid(data);
4502 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004503 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004504 continue;
4505 }
4506
Yiwei Zhang5434a782018-12-05 18:06:32 -08004507 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004508 result.append(edid->displayName.data(), edid->displayName.length());
4509 result.append("\"\n");
4510 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004511}
4512
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004513void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4514 std::string& result) const {
4515 hwc2_display_t hwcDisplayId;
4516 uint8_t port;
4517 DisplayIdentificationData data;
4518
4519 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4520 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4521 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4522 }
4523}
4524
Yiwei Zhang5434a782018-12-05 18:06:32 -08004525void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004526 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004527 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4528 StringAppendF(&result, "DisplayColorSetting: %s\n",
4529 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004530
4531 // TODO: print out if wide-color mode is active or not
4532
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004533 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004534 const auto displayId = display->getId();
4535 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004536 continue;
4537 }
4538
Yiwei Zhang5434a782018-12-05 18:06:32 -08004539 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004540 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004541 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004542 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004543 }
4544
Lloyd Pique32cbe282018-10-19 13:09:22 -07004545 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004546 StringAppendF(&result, " Current color mode: %s (%d)\n",
4547 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004548 }
4549 result.append("\n");
4550}
4551
Alec Mouri5793c7d2020-03-10 19:55:50 -07004552LayersProto SurfaceFlinger::dumpDrawingStateProto(
4553 uint32_t traceFlags, const sp<const DisplayDevice>& displayDevice) const {
chaviw1d044282017-09-27 12:19:28 -07004554 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004555 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Alec Mouri5793c7d2020-03-10 19:55:50 -07004556 layer->writeToProto(layersProto, traceFlags, displayDevice);
chaviw08f3cb22020-01-13 13:17:21 -08004557 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004558
chaviw1d044282017-09-27 12:19:28 -07004559 return layersProto;
4560}
4561
Alec Mouri6b9e9912020-01-21 10:50:24 -08004562void SurfaceFlinger::dumpHwc(std::string& result) const {
4563 getHwComposer().dump(result);
4564}
4565
Vishnu Nair0f085c62019-08-30 08:49:12 -07004566void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4567 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4568 // it.
4569 LayerProto* rootProto = layersProto.add_layers();
4570 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4571 rootProto->set_id(offscreenRootLayerId);
4572 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004573 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004574
4575 for (Layer* offscreenLayer : mOffscreenLayers) {
4576 // Add layer as child of the fake root
4577 rootProto->add_children(offscreenLayer->sequence);
4578
4579 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004580 LayerProto* layerProto =
4581 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004582 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004583 }
4584}
4585
Vishnu Nair8406fd72019-07-30 11:29:31 -07004586LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4587 LayersProto layersProto;
Alec Mouri5793c7d2020-03-10 19:55:50 -07004588 postMessageSync(new LambdaMessage([&]() {
4589 const auto& displayDevice = getDefaultDisplayDeviceLocked();
4590 layersProto = dumpDrawingStateProto(traceFlags, displayDevice);
4591 }));
Vishnu Nair8406fd72019-07-30 11:29:31 -07004592 return layersProto;
4593}
4594
Vishnu Nair0f085c62019-08-30 08:49:12 -07004595void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4596 result.append("Offscreen Layers:\n");
4597 postMessageSync(new LambdaMessage([&]() {
4598 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004599 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004600 layer->dumpCallingUidPid(result);
4601 });
4602 }
4603 }));
4604}
4605
Dominik Laskowskic2867142019-01-21 11:33:38 -08004606void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4607 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004608 Colorizer colorizer(colorize);
4609
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004610 // figure out if we're stuck somewhere
4611 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004612 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004613 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4614
4615 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004616 * Dump library configuration.
4617 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004618
4619 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004620 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004621 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004622 appendSfConfigString(result);
4623 appendUiConfigString(result);
4624 appendGuiConfigString(result);
4625 result.append("\n");
4626
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004627 result.append("\nDisplay identification data:\n");
4628 dumpDisplayIdentificationData(result);
4629
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004630 result.append("\nWide-Color information:\n");
4631 dumpWideColorInfo(result);
4632
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004633 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004634 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004635 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004636 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004637 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004638
Andy McFadden41d67d72014-04-25 16:58:34 -07004639 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004640 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004641 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004642 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004643 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004644
Dan Stozab90cf072015-03-05 11:05:59 -08004645 dumpStaticScreenStats(result);
4646 result.append("\n");
4647
Alec Mouri40189b02019-03-05 15:07:54 -08004648 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4649 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4650 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004651
Dan Stozae77c7662016-05-13 11:37:28 -07004652 dumpBufferingStats(result);
4653
Andy McFadden4803b742012-09-24 19:07:20 -07004654 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004655 * Dump the visible layer list
4656 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004657 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004658 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004659 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4660 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004661 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004662
Chia-I Wu2f884132018-09-13 15:17:58 -07004663 {
Lloyd Pique207def92019-02-28 16:09:52 -08004664 StringAppendF(&result, "Composition layers\n");
4665 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004666 auto* compositionState = layer->getCompositionState();
4667 if (!compositionState) return;
4668
4669 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4670 layer->getDebugName() ? layer->getDebugName()
4671 : "<unknown>");
4672 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004673 });
4674 }
4675
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004676 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004677 * Dump Display state
4678 */
4679
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004680 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004681 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004682 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004683 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004684 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004685 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004686 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004687
4688 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004689 * Dump CompositionEngine state
4690 */
4691
4692 mCompositionEngine->dump(result);
4693
4694 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004695 * Dump SurfaceFlinger global state
4696 */
4697
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004698 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004699 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004700 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004701
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004702 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004703
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004704 DebugEGLImageTracker::getInstance()->dump(result);
4705
Dominik Laskowski075d3172018-05-24 15:50:06 -07004706 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004707 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4708 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004709 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4710 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004711 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004712 StringAppendF(&result,
4713 " transaction-flags : %08x\n"
4714 " gpu_to_cpu_unsupported : %d\n",
4715 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004716
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004717 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004718 displayId && getHwComposer().isConnected(*displayId)) {
4719 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004720 StringAppendF(&result,
4721 " refresh-rate : %f fps\n"
4722 " x-dpi : %f\n"
4723 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004724 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4725 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004726 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004727
Yiwei Zhang5434a782018-12-05 18:06:32 -08004728 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004729
Dan Stozae22aec72016-08-01 13:20:59 -07004730 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004731 * Tracing state
4732 */
4733 mTracing.dump(result);
4734 result.append("\n");
4735
4736 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004737 * HWC layer minidump
4738 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004739 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004740 const auto displayId = display->getId();
4741 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004742 continue;
4743 }
4744
Yiwei Zhang5434a782018-12-05 18:06:32 -08004745 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004746 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004747 const sp<DisplayDevice> displayDevice = display;
4748 mCurrentState.traverseInZOrder(
4749 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004750 result.append("\n");
4751 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004752
4753 /*
4754 * Dump HWComposer state
4755 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004756 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004757 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004758 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004759 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004760 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004761 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004762
4763 /*
4764 * Dump gralloc state
4765 */
4766 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4767 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004768
4769 /*
4770 * Dump VrFlinger state if in use.
4771 */
4772 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4773 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004774 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004775 result.append("\n");
4776 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004777
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004778 result.append(mTimeStats->miniDump());
4779 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004780}
4781
Chia-I Wu28f320b2018-05-03 11:02:56 -07004782void SurfaceFlinger::updateColorMatrixLocked() {
4783 mat4 colorMatrix;
4784 if (mGlobalSaturationFactor != 1.0f) {
4785 // Rec.709 luma coefficients
4786 float3 luminance{0.213f, 0.715f, 0.072f};
4787 luminance *= 1.0f - mGlobalSaturationFactor;
4788 mat4 saturationMatrix = mat4(
4789 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4790 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4791 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4792 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4793 );
4794 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4795 } else {
4796 colorMatrix = mClientColorMatrix * mDaltonizer();
4797 }
4798
4799 if (mCurrentState.colorMatrix != colorMatrix) {
4800 mCurrentState.colorMatrix = colorMatrix;
4801 mCurrentState.colorMatrixChanged = true;
4802 setTransactionFlags(eTransactionNeeded);
4803 }
4804}
4805
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004806status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004807#pragma clang diagnostic push
4808#pragma clang diagnostic error "-Wswitch-enum"
4809 switch (static_cast<ISurfaceComposerTag>(code)) {
4810 // These methods should at minimum make sure that the client requested
4811 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004812 case BOOT_FINISHED:
4813 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004814 case CREATE_DISPLAY:
4815 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004816 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004817 case GET_ANIMATION_FRAME_STATS:
4818 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004819 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004820 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004821 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004822 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4823 case SET_AUTO_LOW_LATENCY_MODE:
4824 case GET_GAME_CONTENT_TYPE_SUPPORT:
4825 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004826 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004827 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004828 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004829 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004830 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004831 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004832 case SET_GLOBAL_SHADOW_SETTINGS:
4833 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4834 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4835 // necessary permission dynamically. Don't use the permission cache for this check.
4836 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4837 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004838 IPCThreadState* ipc = IPCThreadState::self();
4839 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4840 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004841 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004842 }
Robert Carr1db73f62016-12-21 12:58:51 -08004843 return OK;
4844 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004845 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004846 IPCThreadState* ipc = IPCThreadState::self();
4847 const int pid = ipc->getCallingPid();
4848 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004849 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4850 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004851 return PERMISSION_DENIED;
4852 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004853 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004854 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004855 // Used by apps to hook Choreographer to SurfaceFlinger.
4856 case CREATE_DISPLAY_EVENT_CONNECTION:
4857 // The following calls are currently used by clients that do not
4858 // request necessary permissions. However, they do not expose any secret
4859 // information, so it is OK to pass them.
4860 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004861 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004862 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004863 case GET_PHYSICAL_DISPLAY_IDS:
4864 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004865 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004866 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004867 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004868 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004869 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004870 case GET_DISPLAY_STATS:
4871 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4872 // Calling setTransactionState is safe, because you need to have been
4873 // granted a reference to Client* and Handle* to do anything with it.
4874 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004875 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004876 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004877 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004878 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004879 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004880 // setFrameRate() is deliberately available for apps to call without any
4881 // special permissions.
4882 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004883 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4884 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004885 return OK;
4886 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004887 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004888 case CAPTURE_SCREEN:
4889 case ADD_REGION_SAMPLING_LISTENER:
4890 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004891 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004892 IPCThreadState* ipc = IPCThreadState::self();
4893 const int pid = ipc->getCallingPid();
4894 const int uid = ipc->getCallingUid();
4895 if ((uid != AID_GRAPHICS) &&
4896 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4897 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4898 return PERMISSION_DENIED;
4899 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004900 return OK;
4901 }
chaviw93df2ea2019-04-30 16:45:12 -07004902 case CAPTURE_SCREEN_BY_ID: {
4903 IPCThreadState* ipc = IPCThreadState::self();
4904 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004905 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004906 return OK;
4907 }
4908 return PERMISSION_DENIED;
4909 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004910 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004911
4912 // These codes are used for the IBinder protocol to either interrogate the recipient
4913 // side of the transaction for its canonical interface descriptor or to dump its state.
4914 // We let them pass by default.
4915 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4916 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4917 code == IBinder::SYSPROPS_TRANSACTION) {
4918 return OK;
4919 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004920 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004921 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004922 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004923 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4924 return OK;
4925 }
4926 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4927 return PERMISSION_DENIED;
4928#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004929}
4930
Ana Krulec13be8ad2018-08-21 02:43:56 +00004931status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4932 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004933 status_t credentialCheck = CheckTransactCodeCredentials(code);
4934 if (credentialCheck != OK) {
4935 return credentialCheck;
4936 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004937
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004938 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4939 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004940 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004941 IPCThreadState* ipc = IPCThreadState::self();
4942 const int uid = ipc->getCallingUid();
4943 if (CC_UNLIKELY(uid != AID_SYSTEM
4944 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004945 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004946 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004947 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004948 return PERMISSION_DENIED;
4949 }
4950 int n;
4951 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004952 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004953 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004954 return NO_ERROR;
4955 case 1002: // SHOW_UPDATES
4956 n = data.readInt32();
4957 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004958 invalidateHwcGeometry();
4959 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004960 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004961 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004962 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004963 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004964 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004965 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004966 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004967 setTransactionFlags(
4968 eTransactionNeeded|
4969 eDisplayTransactionNeeded|
4970 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004971 return NO_ERROR;
4972 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004973 case 1006:{ // send empty update
4974 signalRefresh();
4975 return NO_ERROR;
4976 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004977 case 1008: // toggle use of hw composer
4978 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004979 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004980 invalidateHwcGeometry();
4981 repaintEverything();
4982 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004983 case 1009: // toggle use of transform hint
4984 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004985 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004986 invalidateHwcGeometry();
4987 repaintEverything();
4988 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004989 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004990 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004991 reply->writeInt32(0);
4992 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004993 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004994 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004995 return NO_ERROR;
4996 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004997 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004998 if (!display) {
4999 return NAME_NOT_FOUND;
5000 }
5001
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005002 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005003 return NO_ERROR;
5004 }
5005 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005006 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005007 // daltonize
5008 n = data.readInt32();
5009 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005010 case 1:
5011 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5012 break;
5013 case 2:
5014 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5015 break;
5016 case 3:
5017 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5018 break;
5019 default:
5020 mDaltonizer.setType(ColorBlindnessType::None);
5021 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005022 }
5023 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005024 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005025 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005026 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005027 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005028
5029 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005030 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005031 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005032 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005033 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005034 // apply a color matrix
5035 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005036 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005037 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005038 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005039 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005040 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005041 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005042 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005043 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005044 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005045 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005046
5047 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5048 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005049 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005050 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5051 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5052 }
5053
Chia-I Wu28f320b2018-05-03 11:02:56 -07005054 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005055 return NO_ERROR;
5056 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005057 case 1016: { // Unused.
5058 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005059 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005060 case 1017: {
5061 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005062 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005063 return NO_ERROR;
5064 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005065 case 1018: { // Modify Choreographer's phase offset
5066 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005067 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005068 return NO_ERROR;
5069 }
5070 case 1019: { // Modify SurfaceFlinger's phase offset
5071 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005072 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005073 return NO_ERROR;
5074 }
Irvel468051e2016-06-13 16:44:44 -07005075 case 1020: { // Layer updates interceptor
5076 n = data.readInt32();
5077 if (n) {
5078 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005079 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005080 }
5081 else{
5082 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005083 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005084 }
5085 return NO_ERROR;
5086 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005087 case 1021: { // Disable HWC virtual displays
5088 n = data.readInt32();
5089 mUseHwcVirtualDisplays = !n;
5090 return NO_ERROR;
5091 }
Romain Guy0147a172017-06-01 13:53:56 -07005092 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005093 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005094 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005095
Chia-I Wu28f320b2018-05-03 11:02:56 -07005096 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005097 return NO_ERROR;
5098 }
Romain Guy54f154a2017-10-24 21:40:32 +01005099 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005100 int32_t colorMode;
5101
Chia-I Wu0d711262018-05-21 15:19:35 -07005102 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005103 if (data.readInt32(&colorMode) == NO_ERROR) {
5104 mForceColorMode = static_cast<ColorMode>(colorMode);
5105 }
Romain Guy54f154a2017-10-24 21:40:32 +01005106 invalidateHwcGeometry();
5107 repaintEverything();
5108 return NO_ERROR;
5109 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005110 // Deprecate, use 1030 to check whether the device is color managed.
5111 case 1024: {
5112 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005113 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005114 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005115 n = data.readInt32();
5116 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005117 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005118 Mutex::Autolock lock(mStateLock);
5119 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005120 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005121 reply->writeInt32(NO_ERROR);
5122 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005123 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005124 bool writeFile = false;
5125 {
5126 Mutex::Autolock lock(mStateLock);
5127 mTracingEnabledChanged = true;
5128 writeFile = mTracing.disable();
5129 }
5130
5131 if (writeFile) {
5132 reply->writeInt32(mTracing.writeToFile());
5133 } else {
5134 reply->writeInt32(NO_ERROR);
5135 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005136 }
5137 return NO_ERROR;
5138 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005139 case 1026: { // Get layer tracing status
5140 reply->writeBool(mTracing.isEnabled());
5141 return NO_ERROR;
5142 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005143 // Is a DisplayColorSetting supported?
5144 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005145 const auto display = getDefaultDisplayDevice();
5146 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005147 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005148 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005149
5150 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5151 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005152 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005153 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005154 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005155 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005156 reply->writeBool(true);
5157 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005158 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005159 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005160 break;
5161 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005162 reply->writeBool(
5163 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005164 break;
5165 }
5166 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005167 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005168 // Is VrFlinger active?
5169 case 1028: {
5170 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005171 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005172 return NO_ERROR;
5173 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005174 // Set buffer size for SF tracing (value in KB)
5175 case 1029: {
5176 n = data.readInt32();
5177 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5178 ALOGW("Invalid buffer size: %d KB", n);
5179 reply->writeInt32(BAD_VALUE);
5180 return BAD_VALUE;
5181 }
5182
5183 ALOGD("Updating trace buffer to %d KB", n);
5184 mTracing.setBufferSize(n * 1024);
5185 reply->writeInt32(NO_ERROR);
5186 return NO_ERROR;
5187 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005188 // Is device color managed?
5189 case 1030: {
5190 reply->writeBool(useColorManagement);
5191 return NO_ERROR;
5192 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005193 // Override default composition data space
5194 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5195 // && adb shell stop zygote && adb shell start zygote
5196 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5197 // adb shell stop zygote && adb shell start zygote
5198 case 1031: {
5199 Mutex::Autolock _l(mStateLock);
5200 n = data.readInt32();
5201 if (n) {
5202 n = data.readInt32();
5203 if (n) {
5204 Dataspace dataspace = static_cast<Dataspace>(n);
5205 if (!validateCompositionDataspace(dataspace)) {
5206 return BAD_VALUE;
5207 }
5208 mDefaultCompositionDataspace = dataspace;
5209 }
5210 n = data.readInt32();
5211 if (n) {
5212 Dataspace dataspace = static_cast<Dataspace>(n);
5213 if (!validateCompositionDataspace(dataspace)) {
5214 return BAD_VALUE;
5215 }
5216 mWideColorGamutCompositionDataspace = dataspace;
5217 }
5218 } else {
5219 // restore composition data space.
5220 mDefaultCompositionDataspace = defaultCompositionDataspace;
5221 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5222 }
5223 return NO_ERROR;
5224 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005225 // Set trace flags
5226 case 1033: {
5227 n = data.readUint32();
5228 ALOGD("Updating trace flags to 0x%x", n);
5229 mTracing.setTraceFlags(n);
5230 reply->writeInt32(NO_ERROR);
5231 return NO_ERROR;
5232 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005233 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005234 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005235 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005236 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005237 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005238 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005239 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005240 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005241 } else {
5242 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005243 }
5244 return NO_ERROR;
5245 }
Ady Abraham34392f72019-04-10 11:29:27 -07005246 case 1035: {
5247 n = data.readInt32();
5248 mDebugDisplayConfigSetByBackdoor = false;
5249 if (n >= 0) {
5250 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005251 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005252 if (result != NO_ERROR) {
5253 return result;
5254 }
5255 mDebugDisplayConfigSetByBackdoor = true;
5256 }
5257 return NO_ERROR;
5258 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005259 }
5260 }
5261 return err;
5262}
5263
Steven Thomas6d8110b2017-08-31 18:24:21 -07005264void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005265 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005266 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005267}
5268
Ana Krulec7d1d6832018-12-27 11:10:09 -08005269void SurfaceFlinger::repaintEverythingForHWC() {
5270 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005271 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005272 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005273}
5274
Ady Abrahama09852a2020-02-20 14:23:42 -08005275void SurfaceFlinger::kernelTimerChanged(bool expired) {
5276 static bool updateOverlay =
5277 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5278 if (!updateOverlay || !mRefreshRateOverlay) return;
5279
5280 // Update the overlay on the main thread to avoid race conditions with
5281 // mRefreshRateConfigs->getCurrentRefreshRate()
5282 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5283 if (mRefreshRateOverlay) {
5284 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5285 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005286 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005287 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5288 if (mDesiredActiveConfigChanged) {
5289 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5290 mDesiredActiveConfig.configId);
5291 }
5292
5293 return mRefreshRateConfigs->getCurrentRefreshRate();
5294 }();
5295 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5296
5297 if (current != min) {
5298 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5299 mEventQueue->invalidate();
5300 }
5301 }
5302 }));
5303}
5304
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005305// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5306class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005307public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005308 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5309 ~WindowDisconnector() {
5310 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005311 }
5312
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005313private:
5314 ANativeWindow* mWindow;
5315 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005316};
5317
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005318status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005319 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005320 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5321 const Rect& sourceCrop, uint32_t reqWidth,
5322 uint32_t reqHeight, bool useIdentityTransform,
5323 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005324 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005325
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005326 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005327
Dominik Laskowski718f9602019-11-09 20:01:35 -08005328 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5329 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5330 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5331 renderAreaRotation = ui::Transform::ROT_0;
5332 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005333
Chia-I Wu20261cb2018-08-23 12:55:44 -07005334 sp<DisplayDevice> display;
5335 {
5336 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005337
Chia-I Wu20261cb2018-08-23 12:55:44 -07005338 display = getDisplayDeviceLocked(displayToken);
5339 if (!display) return BAD_VALUE;
5340
Chia-I Wucb023152018-08-28 12:57:23 -07005341 // set the requested width/height to the logical display viewport size
5342 // by default
5343 if (reqWidth == 0 || reqHeight == 0) {
5344 reqWidth = uint32_t(display->getViewport().width());
5345 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005346 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005347 }
5348
Peiyong Lin0e003c92018-09-17 11:09:51 -07005349 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005350 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005351
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005352 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5353 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005354 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005355 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005356}
5357
chaviw93df2ea2019-04-30 16:45:12 -07005358static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5359 switch (colorMode) {
5360 case ColorMode::DISPLAY_P3:
5361 case ColorMode::BT2100_PQ:
5362 case ColorMode::BT2100_HLG:
5363 case ColorMode::DISPLAY_BT2020:
5364 return Dataspace::DISPLAY_P3;
5365 default:
5366 return Dataspace::V0_SRGB;
5367 }
5368}
5369
Martin Liu4a322352020-03-24 21:30:38 +08005370status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5371 static constexpr int kFifoPriority = 2;
5372 static constexpr int kOtherPriority = 0;
5373
5374 struct sched_param param = {0};
5375 int sched_policy;
5376 if (enabled) {
5377 sched_policy = SCHED_FIFO;
5378 param.sched_priority = kFifoPriority;
5379 } else {
5380 sched_policy = SCHED_OTHER;
5381 param.sched_priority = kOtherPriority;
5382 }
5383
5384 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5385 return -errno;
5386 }
5387 return NO_ERROR;
5388}
5389
chaviw93df2ea2019-04-30 16:45:12 -07005390const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5391 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5392 if (displayToken) {
5393 return getDisplayDeviceLocked(displayToken);
5394 }
5395 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5396 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005397 return getDisplayByLayerStack(displayOrLayerStack);
5398}
5399
5400const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005401 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005402 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005403 return display;
5404 }
5405 }
5406 return nullptr;
5407}
5408
5409status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5410 sp<GraphicBuffer>* outBuffer) {
5411 sp<DisplayDevice> display;
5412 uint32_t width;
5413 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005414 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005415 {
5416 Mutex::Autolock _l(mStateLock);
5417 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5418 if (!display) {
5419 return BAD_VALUE;
5420 }
5421
5422 width = uint32_t(display->getViewport().width());
5423 height = uint32_t(display->getViewport().height());
5424
Dominik Laskowski718f9602019-11-09 20:01:35 -08005425 const auto orientation = display->getOrientation();
5426 captureOrientation = ui::Transform::toRotationFlags(orientation);
5427
5428 switch (captureOrientation) {
5429 case ui::Transform::ROT_90:
5430 captureOrientation = ui::Transform::ROT_270;
5431 break;
5432
5433 case ui::Transform::ROT_270:
5434 captureOrientation = ui::Transform::ROT_90;
5435 break;
5436
5437 case ui::Transform::ROT_INVALID:
5438 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5439 captureOrientation = ui::Transform::ROT_0;
5440 break;
5441
5442 default:
5443 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005444 }
chaviw93df2ea2019-04-30 16:45:12 -07005445 *outDataspace =
5446 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5447 }
5448
5449 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5450 false /* captureSecureLayers */);
5451
5452 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5453 std::placeholders::_1);
5454 bool ignored = false;
5455 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5456 false /* useIdentityTransform */,
5457 ignored /* outCapturedSecureLayers */);
5458}
5459
Robert Carr866455f2019-04-02 16:28:26 -07005460status_t SurfaceFlinger::captureLayers(
5461 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5462 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5463 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5464 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005465 ATRACE_CALL();
5466
5467 class LayerRenderArea : public RenderArea {
5468 public:
Robert Carr578038f2018-03-09 12:25:24 -08005469 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005470 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005471 bool childrenOnly, const Rect& displayViewport)
5472 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005473 mLayer(layer),
5474 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005475 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005476 mFlinger(flinger),
5477 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005478 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005479 Rect getBounds() const override {
5480 const Layer::State& layerState(mLayer->getDrawingState());
5481 return mLayer->getBufferSize(layerState);
5482 }
Marissa Wall61c58622018-07-18 10:12:20 -07005483 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005484 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005485 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005486 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005487 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005488 }
chaviwa76b2712017-09-20 12:02:26 -07005489 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005490 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005491 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005492 Rect getSourceCrop() const override {
5493 if (mCrop.isEmpty()) {
5494 return getBounds();
5495 } else {
5496 return mCrop;
5497 }
5498 }
Robert Carr578038f2018-03-09 12:25:24 -08005499 class ReparentForDrawing {
5500 public:
5501 const sp<Layer>& oldParent;
5502 const sp<Layer>& newParent;
5503
Vishnu Nair4351ad52019-02-11 14:13:02 -08005504 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5505 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005506 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005507 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005508 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5509 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005510 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005511 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005512 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005513 };
5514
5515 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005516 const Rect sourceCrop = getSourceCrop();
5517 // no need to check rotation because there is none
5518 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5519 sourceCrop.height() != getReqHeight();
5520
Robert Carr578038f2018-03-09 12:25:24 -08005521 if (!mChildrenOnly) {
5522 mTransform = mLayer->getTransform().inverse();
5523 drawLayers();
5524 } else {
5525 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005526 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5527 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005528 // In the "childrenOnly" case we reparent the children to a screenshot
5529 // layer which has no properties set and which does not draw.
5530 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005531 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5532 "Screenshot Parent"s, w, h, 0,
5533 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005534
Vishnu Nair4351ad52019-02-11 14:13:02 -08005535 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005536 drawLayers();
5537 }
5538 }
chaviwa76b2712017-09-20 12:02:26 -07005539
chaviwa76b2712017-09-20 12:02:26 -07005540 private:
chaviw7206d492017-11-10 16:16:12 -08005541 const sp<Layer> mLayer;
5542 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005543
Peiyong Linefefaac2018-08-17 12:27:51 -07005544 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005545 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005546
5547 SurfaceFlinger* mFlinger;
5548 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005549 };
5550
Robert Carrc0df3122019-04-11 13:18:21 -07005551 int reqWidth = 0;
5552 int reqHeight = 0;
5553 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005554 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005555 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005556 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005557 {
5558 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005559
Robert Carrc0df3122019-04-11 13:18:21 -07005560 parent = fromHandle(layerHandleBinder);
5561 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5562 ALOGE("captureLayers called with an invalid or removed parent");
5563 return NAME_NOT_FOUND;
5564 }
5565
5566 const int uid = IPCThreadState::self()->getCallingUid();
5567 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5568 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5569 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5570 return PERMISSION_DENIED;
5571 }
5572
Vishnu Nairefc42e22019-12-03 17:36:12 -08005573 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005574 if (sourceCrop.width() <= 0) {
5575 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005576 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005577 }
5578
5579 if (sourceCrop.height() <= 0) {
5580 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005581 crop.bottom = parentSourceBounds.getHeight();
5582 }
5583
5584 if (crop.isEmpty() || frameScale <= 0.0f) {
5585 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5586 // crop was not specified, or an invalid frame scale was provided.
5587 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005588 }
5589 reqWidth = crop.width() * frameScale;
5590 reqHeight = crop.height() * frameScale;
5591
5592 for (const auto& handle : excludeHandles) {
5593 sp<Layer> excludeLayer = fromHandle(handle);
5594 if (excludeLayer != nullptr) {
5595 excludeLayers.emplace(excludeLayer);
5596 } else {
5597 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5598 return NAME_NOT_FOUND;
5599 }
5600 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005601
5602 auto display = getDisplayByLayerStack(parent->getLayerStack());
5603 if (!display) {
5604 return BAD_VALUE;
5605 }
5606
5607 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005608 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005609
Chia-I Wu20261cb2018-08-23 12:55:44 -07005610 // really small crop or frameScale
5611 if (reqWidth <= 0) {
5612 reqWidth = 1;
5613 }
5614 if (reqHeight <= 0) {
5615 reqHeight = 1;
5616 }
5617
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005618 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5619 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005620 auto traverseLayers = [parent, childrenOnly,
5621 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005622 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5623 if (!layer->isVisible()) {
5624 return;
Robert Carr578038f2018-03-09 12:25:24 -08005625 } else if (childrenOnly && layer == parent.get()) {
5626 return;
chaviwa76b2712017-09-20 12:02:26 -07005627 }
Robert Carr866455f2019-04-02 16:28:26 -07005628
5629 sp<Layer> p = layer;
5630 while (p != nullptr) {
5631 if (excludeLayers.count(p) != 0) {
5632 return;
5633 }
5634 p = p->getParent();
5635 }
5636
chaviwa76b2712017-09-20 12:02:26 -07005637 visitor(layer);
5638 });
5639 };
Robert Carr108b2c72019-04-02 16:32:58 -07005640
5641 bool outCapturedSecureLayers = false;
5642 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5643 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005644}
5645
5646status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5647 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005648 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005649 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005650 bool useIdentityTransform,
5651 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005652 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005653
Peiyong Lin0e003c92018-09-17 11:09:51 -07005654 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005655 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5656 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005657 *outBuffer =
5658 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5659 static_cast<android_pixel_format>(reqPixelFormat), 1,
5660 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005661
Robert Carr108b2c72019-04-02 16:32:58 -07005662 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5663 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005664}
5665
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005666status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5667 TraverseLayersFunction traverseLayers,
5668 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005669 bool useIdentityTransform,
5670 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005671 // This mutex protects syncFd and captureResult for communication of the return values from the
5672 // main thread back to this Binder thread
5673 std::mutex captureMutex;
5674 std::condition_variable captureCondition;
5675 std::unique_lock<std::mutex> captureLock(captureMutex);
5676 int syncFd = -1;
5677 std::optional<status_t> captureResult;
5678
Robert Carr03480e22018-01-04 16:02:06 -08005679 const int uid = IPCThreadState::self()->getCallingUid();
5680 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5681
Dominik Laskowski8c001672018-05-30 16:52:06 -07005682 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005683 // If there is a refresh pending, bug out early and tell the binder thread to try again
5684 // after the refresh.
5685 if (mRefreshPending) {
5686 ATRACE_NAME("Skipping screenshot for now");
5687 std::unique_lock<std::mutex> captureLock(captureMutex);
5688 captureResult = std::make_optional<status_t>(EAGAIN);
5689 captureCondition.notify_one();
5690 return;
5691 }
5692
5693 status_t result = NO_ERROR;
5694 int fd = -1;
5695 {
5696 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005697 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005698 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005699 useIdentityTransform, forSystem, &fd,
5700 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005701 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005702 }
5703
5704 {
5705 std::unique_lock<std::mutex> captureLock(captureMutex);
5706 syncFd = fd;
5707 captureResult = std::make_optional<status_t>(result);
5708 captureCondition.notify_one();
5709 }
5710 });
5711
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005712 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005713 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005714 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005715 while (*captureResult == EAGAIN) {
5716 captureResult.reset();
5717 result = postMessageAsync(message);
5718 if (result != NO_ERROR) {
5719 return result;
5720 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005721 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005722 }
5723 result = *captureResult;
5724 }
5725
5726 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005727 sync_wait(syncFd, -1);
5728 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005729 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005730
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005731 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005732}
5733
chaviwa76b2712017-09-20 12:02:26 -07005734void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005735 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005736 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5737 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005738 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005739
chaviwa76b2712017-09-20 12:02:26 -07005740 const auto reqWidth = renderArea.getReqWidth();
5741 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005742 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005743 const auto transform = renderArea.getTransform();
5744 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005745 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005746
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005747 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005748 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005749
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005750 // assume that bounds are never offset, and that they are the same as the
5751 // buffer bounds.
5752 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005753 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005754 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005755
5756 // Now take into account the rotation flag. We append a transform that
5757 // rotates the layer stack about the origin, then translate by buffer
5758 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005759 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005760 int displacementX = 0;
5761 int displacementY = 0;
5762 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5763 switch (rotation) {
5764 case ui::Transform::ROT_90:
5765 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005766 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005767 break;
5768 case ui::Transform::ROT_180:
5769 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005770 displacementY = renderArea.getBounds().getWidth();
5771 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005772 break;
5773 case ui::Transform::ROT_270:
5774 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005775 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005776 break;
5777 default:
5778 break;
5779 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005780
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005781 // We need to transform the clipping window into the right spot.
5782 // First, rotate the clipping rectangle by the rotation hint to get the
5783 // right orientation
5784 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5785 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5786 const vec4 rotClipTL = rotMatrix * clipTL;
5787 const vec4 rotClipBR = rotMatrix * clipBR;
5788 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5789 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5790 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5791 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5792
5793 // Now reposition the clipping rectangle with the displacement vector
5794 // computed above.
5795 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005796 clientCompositionDisplay.clip =
5797 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5798 newClipRight + displacementX, newClipBottom + displacementY);
5799
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005800 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005801 clientCompositionDisplay.globalTransform =
5802 clipTransform * clientCompositionDisplay.globalTransform;
5803
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005804 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5805 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005806
chaviw50da5042018-04-09 13:49:37 -07005807 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005808
Vishnu Nair9b079a22020-01-21 14:36:08 -08005809 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005810 fillLayer.source.buffer.buffer = nullptr;
5811 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5812 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5813 fillLayer.alpha = half(alpha);
5814 clientCompositionLayers.push_back(fillLayer);
5815
5816 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005817 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005818 const bool supportProtectedContent = false;
5819 Region clip(renderArea.getBounds());
5820 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5821 clip,
5822 useIdentityTransform,
5823 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5824 renderArea.isSecure(),
5825 supportProtectedContent,
5826 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005827 displayViewport,
5828 clientCompositionDisplay.outputDataspace,
5829 true, /* realContentIsVisible */
5830 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005831 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005832 std::vector<compositionengine::LayerFE::LayerSettings> results =
5833 layer->prepareClientCompositionList(targetSettings);
5834 clientCompositionLayers.insert(clientCompositionLayers.end(),
5835 std::make_move_iterator(results.begin()),
5836 std::make_move_iterator(results.end()));
5837 results.clear();
5838
chaviwa76b2712017-09-20 12:02:26 -07005839 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005840
Vishnu Nair9b079a22020-01-21 14:36:08 -08005841 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5842 clientCompositionLayers.reserve(clientCompositionLayers.size());
5843 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5844 std::back_inserter(clientCompositionLayerPointers),
5845 [](compositionengine::LayerFE::LayerSettings& settings)
5846 -> renderengine::LayerSettings* { return &settings; });
5847
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005848 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005849 // Use an empty fence for the buffer fence, since we just created the buffer so
5850 // there is no need for synchronization with the GPU.
5851 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005852 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005853 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005854 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005855 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005856
5857 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005858}
5859
chaviwa76b2712017-09-20 12:02:26 -07005860status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5861 TraverseLayersFunction traverseLayers,
5862 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005863 bool useIdentityTransform, bool forSystem,
5864 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005865 ATRACE_CALL();
5866
chaviwa76b2712017-09-20 12:02:26 -07005867 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005868 outCapturedSecureLayers =
5869 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005870 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005871
Robert Carr03480e22018-01-04 16:02:06 -08005872 // We allow the system server to take screenshots of secure layers for
5873 // use in situations like the Screen-rotation animation and place
5874 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005875 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005876 ALOGW("FB is protected: PERMISSION_DENIED");
5877 return PERMISSION_DENIED;
5878 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005879 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005880 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005881}
5882
chaviw95ef3c42019-02-14 10:55:09 -08005883void SurfaceFlinger::setInputWindowsFinished() {
5884 Mutex::Autolock _l(mStateLock);
5885
5886 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005887
chaviw95ef3c42019-02-14 10:55:09 -08005888 mTransactionCV.broadcast();
5889}
chaviw5f21a5e2019-02-14 10:00:34 -08005890
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005891// ---------------------------------------------------------------------------
5892
Edgar Arriaga844fa672020-01-16 14:21:42 -08005893void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5894 layersSortedByZ.traverse(visitor);
5895}
5896
Dan Stoza412903f2017-04-27 13:42:17 -07005897void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5898 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005899}
5900
Dan Stoza412903f2017-04-27 13:42:17 -07005901void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5902 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005903}
5904
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005905void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005906 const LayerVector::Visitor& visitor) {
5907 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005908 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005909 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005910 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005911 continue;
5912 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005913 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005914 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005915 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005916 return;
5917 }
chaviwa76b2712017-09-20 12:02:26 -07005918 if (!layer->isVisible()) {
5919 return;
5920 }
5921 visitor(layer);
5922 });
5923 }
5924}
5925
Steven Thomasd4071902020-03-24 16:02:53 -07005926status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5927 const sp<DisplayDevice>& display,
5928 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005929 Mutex::Autolock lock(mStateLock);
5930
Steven Thomasd4071902020-03-24 16:02:53 -07005931 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5932 "Can only set override policy on the primary display");
5933 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5934
Dominik Laskowski22488f62019-03-28 09:53:04 -07005935 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005936 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5937 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5938 // it should go thru setDesiredActiveConfig, similar to primary display.
5939 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5940 const auto displayId = display->getId();
5941 LOG_ALWAYS_FATAL_IF(!displayId);
5942
5943 HWC2::VsyncPeriodChangeConstraints constraints;
5944 constraints.desiredTimeNanos = systemTime();
5945 constraints.seamlessRequired = false;
5946
5947 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005948 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5949 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005950 constraints, &timeline) < 0) {
5951 return BAD_VALUE;
5952 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005953 if (timeline.refreshRequired) {
5954 repaintEverythingForHWC();
5955 }
5956
Steven Thomasd4071902020-03-24 16:02:53 -07005957 display->setActiveConfig(policy->defaultConfig);
5958 const nsecs_t vsyncPeriod = getHwComposer()
5959 .getConfigs(*displayId)[policy->defaultConfig.value()]
5960 ->getVsyncPeriod();
5961 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5962 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005963 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005964 }
5965
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005966 if (mDebugDisplayConfigSetByBackdoor) {
5967 // ignore this request as config is overridden by backdoor
5968 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005969 }
5970
Steven Thomasd4071902020-03-24 16:02:53 -07005971 status_t setPolicyResult = overridePolicy
5972 ? mRefreshRateConfigs->setOverridePolicy(policy)
5973 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5974 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005975 return BAD_VALUE;
5976 }
Steven Thomasd4071902020-03-24 16:02:53 -07005977 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005978 return NO_ERROR;
5979 }
Steven Thomasd4071902020-03-24 16:02:53 -07005980 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005981
5982 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
Steven Thomasd4071902020-03-24 16:02:53 -07005983 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
5984 currentPolicy.maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005985
5986 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5987 // that listeners that care about a change in allowed configs can get the notification.
5988 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005989 const nsecs_t vsyncPeriod =
5990 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005991 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005992 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005993
Ana Krulec3f6a2062020-01-23 15:48:01 -08005994 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005995 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005996 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5997 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005998 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005999 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
6000 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
6001
6002 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
6003 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
6004 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08006005 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08006006 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07006007 }
6008
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08006009 return NO_ERROR;
6010}
6011
Ana Krulec0782b882019-10-15 17:34:54 -07006012status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006013 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07006014 float maxRefreshRate) {
6015 ATRACE_CALL();
6016
6017 if (!displayToken) {
6018 return BAD_VALUE;
6019 }
6020
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006021 status_t result = NO_ERROR;
6022
Ana Krulec234bb162019-11-10 22:55:55 +01006023 postMessageSync(new LambdaMessage([&]() {
6024 const auto display = getDisplayDeviceLocked(displayToken);
6025 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006026 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01006027 ALOGE("Attempt to set desired display configs for invalid display token %p",
6028 displayToken.get());
6029 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006030 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01006031 ALOGW("Attempt to set desired display configs for virtual display");
6032 } else {
Steven Thomasd4071902020-03-24 16:02:53 -07006033 result = setDesiredDisplayConfigSpecsInternal(display,
6034 scheduler::RefreshRateConfigs::
6035 Policy{HwcConfigIndexType(
6036 defaultConfig),
6037 minRefreshRate,
6038 maxRefreshRate},
6039 /*overridePolicy=*/false);
Ana Krulec234bb162019-11-10 22:55:55 +01006040 }
6041 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006042
6043 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01006044}
6045
6046status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006047 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01006048 float* outMinRefreshRate,
6049 float* outMaxRefreshRate) {
6050 ATRACE_CALL();
6051
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006052 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01006053 return BAD_VALUE;
6054 }
6055
6056 Mutex::Autolock lock(mStateLock);
6057 const auto display = getDisplayDeviceLocked(displayToken);
6058 if (!display) {
6059 return NAME_NOT_FOUND;
6060 }
6061
6062 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006063 scheduler::RefreshRateConfigs::Policy policy =
6064 mRefreshRateConfigs->getDisplayManagerPolicy();
6065 *outDefaultConfig = policy.defaultConfig.value();
6066 *outMinRefreshRate = policy.minRefreshRate;
6067 *outMaxRefreshRate = policy.maxRefreshRate;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006068 return NO_ERROR;
6069 } else if (display->isVirtual()) {
6070 return BAD_VALUE;
6071 } else {
6072 const auto displayId = display->getId();
6073 if (!displayId) {
6074 return BAD_VALUE;
6075 }
6076 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6077 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6078 *outMinRefreshRate = 1e9f / vsyncPeriod;
6079 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6080 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006081 }
Ana Krulec0782b882019-10-15 17:34:54 -07006082}
6083
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006084void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006085 mFlinger->setInputWindowsFinished();
6086}
6087
Robert Carrc0df3122019-04-11 13:18:21 -07006088sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006089 BBinder* b = nullptr;
6090 if (handle) {
6091 b = handle->localBinder();
6092 }
Robert Carrc0df3122019-04-11 13:18:21 -07006093 if (b == nullptr) {
6094 return nullptr;
6095 }
6096 auto it = mLayersByLocalBinderToken.find(b);
6097 if (it != mLayersByLocalBinderToken.end()) {
6098 return it->second.promote();
6099 }
6100 return nullptr;
6101}
6102
Dominik Laskowski75848362019-11-11 17:57:20 -08006103void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006104 mNumLayers++;
6105 mScheduler->registerLayer(layer);
6106}
6107
6108void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6109 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006110 removeFromOffscreenLayers(layer);
6111}
6112
6113// WARNING: ONLY CALL THIS FROM LAYER DTOR
6114// Here we add children in the current state to offscreen layers and remove the
6115// layer itself from the offscreen layer list. Since
6116// this is the dtor, it is safe to access the current state. This keeps us
6117// from dangling children layers such that they are not reachable from the
6118// Drawing state nor the offscreen layer list
6119// See b/141111965
6120void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6121 for (auto& child : layer->getCurrentChildren()) {
6122 mOffscreenLayers.emplace(child.get());
6123 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006124 mOffscreenLayers.erase(layer);
6125}
6126
Alec Mouri4545a8a2019-08-08 20:05:32 -07006127void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6128 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6129}
6130
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006131status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6132 float lightPosY, float lightPosZ,
6133 float lightRadius) {
6134 Mutex::Autolock _l(mStateLock);
6135 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6136 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6137 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6138 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6139 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6140
6141 // these values are overridden when calculating the shadow settings for a layer.
6142 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6143 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006144 return NO_ERROR;
6145}
6146
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006147const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6148 const {
6149 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6150 // on the work to remove the table in that bug rather than adding more to
6151 // it.
6152 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6153 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6154 // supported, and exposed via the
6155 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6156 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6157 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6158 };
6159 return genericLayerMetadataKeyMap;
6160}
6161
Steven Thomas62a4cf82020-01-31 12:04:03 -08006162status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6163 int8_t compatibility) {
6164 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6165 return BAD_VALUE;
6166 }
6167
Ady Abraham60e42ea2020-03-09 19:17:31 -07006168 postMessageAsync(new LambdaMessage([=]() NO_THREAD_SAFETY_ANALYSIS {
6169 Mutex::Autolock lock(mStateLock);
6170 if (authenticateSurfaceTextureLocked(surface)) {
6171 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6172 if (layer->setFrameRate(
6173 Layer::FrameRate(frameRate,
6174 Layer::FrameRate::convertCompatibility(compatibility)))) {
6175 setTransactionFlags(eTraversalNeeded);
6176 }
6177 } else {
6178 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6179 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006180 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006181 return NO_ERROR;
6182 }));
6183
Steven Thomas62a4cf82020-01-31 12:04:03 -08006184 return NO_ERROR;
6185}
6186
Steven Thomasd4071902020-03-24 16:02:53 -07006187status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6188 if (!outToken) {
6189 return BAD_VALUE;
6190 }
6191 status_t result = NO_ERROR;
6192 postMessageSync(new LambdaMessage([&]() {
6193 if (mFrameRateFlexibilityTokenCount == 0) {
6194 // |mStateLock| not needed as we are on the main thread
6195 const auto display = getDefaultDisplayDeviceLocked();
6196
6197 // This is a little racy, but not in a way that hurts anything. As we grab the
6198 // defaultConfig from the display manager policy, we could be setting a new display
6199 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6200 // matter for the override policy though, since we set allowGroupSwitching to true, so
6201 // it's not a problem.
6202 scheduler::RefreshRateConfigs::Policy overridePolicy;
6203 overridePolicy.defaultConfig =
6204 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6205 overridePolicy.allowGroupSwitching = true;
6206 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy,
6207 /*overridePolicy=*/true);
6208 }
6209
6210 if (result == NO_ERROR) {
6211 mFrameRateFlexibilityTokenCount++;
6212 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6213 // below, is something to consider carefully. The lifetime of the
6214 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6215 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6216 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6217 // in this case, for two reasons:
6218 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6219 // the program exits is via a crash. So we won't have a situation where the
6220 // SurfaceFlinger object is dead but the process is still up.
6221 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6222 // if condition 1 were changed, the problem would only show up when running CTS tests,
6223 // not on end user devices, so we could spot it and fix it without serious impact.
6224 *outToken = new FrameRateFlexibilityToken(
6225 [this]() { onFrameRateFlexibilityTokenReleased(); });
6226 ALOGD("Frame rate flexibility token acquired. count=%d",
6227 mFrameRateFlexibilityTokenCount);
6228 }
6229 }));
6230 return result;
6231}
6232
6233void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
6234 postMessageAsync(new LambdaMessage([&]() {
6235 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6236 "Failed tracking frame rate flexibility tokens");
6237 mFrameRateFlexibilityTokenCount--;
6238 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6239 if (mFrameRateFlexibilityTokenCount == 0) {
6240 // |mStateLock| not needed as we are on the main thread
6241 const auto display = getDefaultDisplayDeviceLocked();
6242 status_t result =
6243 setDesiredDisplayConfigSpecsInternal(display, {}, /*overridePolicy=*/true);
6244 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6245 }
6246 }));
6247}
6248
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006249} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006250
Mathias Agopian3f844832013-08-07 21:24:32 -07006251#if defined(__gl_h_)
6252#error "don't include gl/gl.h in this file"
6253#endif
6254
6255#if defined(__gl2_h_)
6256#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006257#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006258
6259// TODO(b/129481165): remove the #pragma below and fix conversion issues
6260#pragma clang diagnostic pop // ignored "-Wconversion"