blob: 54b7ef39c2c768f507f8470977f80b06799b36e7 [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) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700469 Mutex::Autolock lock(mStateLock);
Jesse Hall6c913be2013-08-08 12:15:49 -0700470
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700471 const ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700472 if (index < 0) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700473 ALOGE("%s: Invalid display token %p", __FUNCTION__, 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);
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700478 if (state.physical) {
479 ALOGE("%s: Invalid operation on physical display", __FUNCTION__);
Jesse Hall6c913be2013-08-08 12:15:49 -0700480 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) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700911 int activeConfig;
912 bool isPrimary;
913
914 {
915 Mutex::Autolock lock(mStateLock);
916
917 if (const auto display = getDisplayDeviceLocked(displayToken)) {
918 activeConfig = display->getActiveConfig().value();
919 isPrimary = display->isPrimary();
920 } else {
921 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
922 return NAME_NOT_FOUND;
923 }
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800924 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700925
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700926 if (isPrimary) {
Steven Thomasc9098452019-09-30 17:15:05 -0700927 std::lock_guard<std::mutex> lock(mActiveConfigLock);
928 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800929 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700930 }
Steven Thomasc9098452019-09-30 17:15:05 -0700931 }
Ady Abraham2139f732019-11-13 18:56:40 -0800932
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700933 return activeConfig;
Dan Stoza7f7da322014-05-02 15:26:25 -0700934}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700935
Ady Abraham03b02dd2019-03-21 15:40:11 -0700936void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800937 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800938 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -0700939 ALOGV("setDesiredActiveConfig(%s)", refreshRate.getName().c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800940
Ady Abrahamb838aed2019-02-12 15:30:16 -0800941 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800942 if (mDesiredActiveConfigChanged) {
943 // If a config change is pending, just cache the latest request in
944 // mDesiredActiveConfig
945 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
946 mDesiredActiveConfig = info;
947 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
948 } else {
949 // Check is we are already at the desired config
950 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamabc27602020-04-08 17:20:29 -0700951 if (!display || display->getActiveConfig() == refreshRate.getConfigId()) {
Ady Abraham59db0a32020-03-02 18:04:20 -0800952 return;
953 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800954
Ady Abraham59db0a32020-03-02 18:04:20 -0800955 // Initiate a config change.
956 mDesiredActiveConfigChanged = true;
957 mDesiredActiveConfig = info;
958
Ady Abrahamb838aed2019-02-12 15:30:16 -0800959 // This will trigger HWC refresh without resetting the idle timer.
960 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700961 // Start receiving vsync samples now, so that we can detect a period
962 // switch.
Ady Abrahamabc27602020-04-08 17:20:29 -0700963 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700964 // As we called to set period, we will call to onRefreshRateChangeCompleted once
965 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700966 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800967
Ady Abrahamabc27602020-04-08 17:20:29 -0700968 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -0800969 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800970 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700971
972 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800973 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700974 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800975}
976
977status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
978 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800979
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100980 if (!displayToken) {
981 return BAD_VALUE;
982 }
Ady Abraham838de062019-02-04 10:24:03 -0800983
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700984 status_t result = NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100985
986 postMessageSync(new LambdaMessage([&]() {
987 const auto display = getDisplayDeviceLocked(displayToken);
988 if (!display) {
989 ALOGE("Attempt to set allowed display configs for invalid display token %p",
990 displayToken.get());
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100991 } else if (display->isVirtual()) {
992 ALOGW("Attempt to set allowed display configs for virtual display");
Dominik Laskowski470df5f2020-04-02 22:27:42 -0700993 result = INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100994 } else {
995 HwcConfigIndexType config(mode);
996 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
Steven Thomasd4071902020-03-24 16:02:53 -0700997 result = setDesiredDisplayConfigSpecsInternal(display,
998 scheduler::RefreshRateConfigs::
Ady Abrahamabc27602020-04-08 17:20:29 -0700999 Policy{config,
1000 refreshRate.getFps(),
1001 refreshRate.getFps()},
Steven Thomasd4071902020-03-24 16:02:53 -07001002 /*overridePolicy=*/false);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001003 }
1004 }));
1005
1006 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001007}
1008
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001009void SurfaceFlinger::setActiveConfigInternal() {
1010 ATRACE_CALL();
1011
Dominik Laskowski22488f62019-03-28 09:53:04 -07001012 const auto display = getDefaultDisplayDeviceLocked();
1013 if (!display) {
1014 return;
1015 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001016
Alec Mouri8de697e2020-03-19 10:52:01 -07001017 auto& oldRefreshRate =
1018 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig());
1019
Dominik Laskowski22488f62019-03-28 09:53:04 -07001020 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -08001021 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001022 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001023 display->setActiveConfig(mUpcomingActiveConfig.configId);
1024
Ady Abraham2e1dd892020-03-05 13:48:36 -08001025 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001026 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001027 if (refreshRate.getVsyncPeriod() != oldRefreshRate.getVsyncPeriod()) {
Alec Mouri8de697e2020-03-19 10:52:01 -07001028 mTimeStats->incrementRefreshRateSwitches();
1029 }
Ady Abrahamabc27602020-04-08 17:20:29 -07001030 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001031 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abrahamabc27602020-04-08 17:20:29 -07001032 ATRACE_INT("ActiveConfigFPS", refreshRate.getFps());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001033
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001034 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -07001035 const nsecs_t vsyncPeriod =
1036 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
Ady Abrahamabc27602020-04-08 17:20:29 -07001037 .getVsyncPeriod();
Ady Abraham447052e2019-02-13 16:07:27 -08001038 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07001039 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -08001040 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001041}
1042
Ady Abraham53852a52019-05-28 18:07:44 -07001043void SurfaceFlinger::desiredActiveConfigChangeDone() {
1044 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1045 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1046 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001047
Ady Abraham2e1dd892020-03-05 13:48:36 -08001048 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001049 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001050 mScheduler->resyncToHardwareVsync(true, refreshRate.getVsyncPeriod());
1051 mPhaseConfiguration->setRefreshRateFps(refreshRate.getFps());
Ady Abraham9e16a482019-12-03 17:19:41 -08001052 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001053}
1054
Ady Abraham27cbed72020-04-10 12:56:59 -07001055void SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001056 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001057 ALOGV("performSetActiveConfig");
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001058 // Store the local variable to release the lock.
Ady Abraham27cbed72020-04-10 12:56:59 -07001059 const auto desiredActiveConfig = [&]() -> std::optional<ActiveConfigInfo> {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001060 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham27cbed72020-04-10 12:56:59 -07001061 if (mDesiredActiveConfigChanged) {
1062 return mDesiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001063 }
Ady Abraham27cbed72020-04-10 12:56:59 -07001064 return std::nullopt;
1065 }();
1066
1067 if (!desiredActiveConfig) {
1068 // No desired active config pending to be applied
1069 return;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001070 }
1071
Ady Abraham2e1dd892020-03-05 13:48:36 -08001072 auto& refreshRate =
Ady Abraham27cbed72020-04-10 12:56:59 -07001073 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig->configId);
Ady Abrahamabc27602020-04-08 17:20:29 -07001074 ALOGV("performSetActiveConfig changing active config to %d(%s)",
1075 refreshRate.getConfigId().value(), refreshRate.getName().c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001076 const auto display = getDefaultDisplayDeviceLocked();
Ady Abraham27cbed72020-04-10 12:56:59 -07001077 if (!display || display->getActiveConfig() == desiredActiveConfig->configId) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001078 // 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 Abraham27cbed72020-04-10 12:56:59 -07001081 return;
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
Ady Abraham27cbed72020-04-10 12:56:59 -07001087 if (!isDisplayConfigAllowed(desiredActiveConfig->configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001088 desiredActiveConfigChangeDone();
Ady Abraham27cbed72020-04-10 12:56:59 -07001089 return;
Ady Abraham838de062019-02-04 10:24:03 -08001090 }
Alec Mouri7f015182019-07-11 13:56:22 -07001091
Ady Abraham27cbed72020-04-10 12:56:59 -07001092 mUpcomingActiveConfig = *desiredActiveConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001093 const auto displayId = display->getId();
1094 LOG_ALWAYS_FATAL_IF(!displayId);
1095
Ady Abrahamabc27602020-04-08 17:20:29 -07001096 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.getFps());
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 Abraham27cbed72020-04-10 12:56:59 -07001112 return;
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001113 }
1114
1115 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1116 // Scheduler will submit an empty frame to HWC if needed.
Ady Abraham27cbed72020-04-10 12:56:59 -07001117 mSetActiveConfigPending = true;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001118}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001119
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001120status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1121 Vector<ColorMode>* outColorModes) {
1122 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001123 return BAD_VALUE;
1124 }
1125
Peiyong Lina52f0292018-03-14 17:26:31 -07001126 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001127 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001128 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001129 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1130
1131 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1132 if (!displayId) {
1133 return NAME_NOT_FOUND;
1134 }
1135
Dominik Laskowski075d3172018-05-24 15:50:06 -07001136 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001137 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001138 }
Michael Wright28f24d02016-07-12 13:30:53 -07001139 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001140
1141 // If it's built-in display and the configuration claims it's not wide color capable,
1142 // filter out all wide color modes. The typical reason why this happens is that the
1143 // hardware is not good enough to support GPU composition of wide color, and thus the
1144 // OEMs choose to disable this capability.
1145 if (isInternalDisplay && !hasWideColorDisplay) {
1146 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1147 isWideColorMode);
1148 } else {
1149 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1150 }
Michael Wright28f24d02016-07-12 13:30:53 -07001151
1152 return NO_ERROR;
1153}
1154
Daniel Solomon42d04562019-01-20 21:03:19 -08001155status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1156 ui::DisplayPrimaries &primaries) {
1157 if (!displayToken) {
1158 return BAD_VALUE;
1159 }
1160
1161 // Currently we only support this API for a single internal display.
1162 if (getInternalDisplayToken() != displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001163 return NAME_NOT_FOUND;
Daniel Solomon42d04562019-01-20 21:03:19 -08001164 }
1165
1166 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1167 return NO_ERROR;
1168}
1169
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001170ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001171 Mutex::Autolock lock(mStateLock);
1172
1173 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001174 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001175 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001176 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001177}
1178
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001179status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001180 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001181 Vector<ColorMode> modes;
1182 getDisplayColorModes(displayToken, &modes);
1183 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1184 if (mode < ColorMode::NATIVE || !exists) {
1185 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1186 decodeColorMode(mode).c_str(), mode, displayToken.get());
1187 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001188 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001189 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001190 if (!display) {
1191 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1192 decodeColorMode(mode).c_str(), mode, displayToken.get());
1193 } else if (display->isVirtual()) {
1194 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1195 decodeColorMode(mode).c_str(), mode);
1196 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001197 display->getCompositionDisplay()->setColorProfile(
1198 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1199 RenderIntent::COLORIMETRIC,
1200 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001201 }
1202 }));
1203
Michael Wright28f24d02016-07-12 13:30:53 -07001204 return NO_ERROR;
1205}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001206
Galia Peycheva5492cb52019-10-30 14:13:16 +01001207status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1208 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001209 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001210 return BAD_VALUE;
1211 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001212
1213 Mutex::Autolock lock(mStateLock);
1214
Galia Peycheva5492cb52019-10-30 14:13:16 +01001215 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1216 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001217 return NAME_NOT_FOUND;
1218 }
Dominik Laskowski1162e472020-04-02 19:02:47 -07001219 *outSupport = getHwComposer().hasDisplayCapability(*displayId,
Galia Peycheva5492cb52019-10-30 14:13:16 +01001220 HWC2::DisplayCapability::AutoLowLatencyMode);
1221 return NO_ERROR;
1222}
1223
1224void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001225 postMessageAsync(new LambdaMessage([=] {
1226 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1227 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1228 } else {
1229 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1230 }
1231 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001232}
1233
1234status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1235 bool* outSupport) const {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001236 if (!displayToken) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001237 return BAD_VALUE;
1238 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001239
1240 Mutex::Autolock lock(mStateLock);
1241
Galia Peycheva5492cb52019-10-30 14:13:16 +01001242 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1243 if (!displayId) {
Galia Peycheva5492cb52019-10-30 14:13:16 +01001244 return NAME_NOT_FOUND;
1245 }
1246
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001247 std::vector<HWC2::ContentType> types;
1248 getHwComposer().getSupportedContentTypes(*displayId, &types);
1249
1250 *outSupport = std::any_of(types.begin(), types.end(),
1251 [](auto type) { return type == HWC2::ContentType::Game; });
Galia Peycheva5492cb52019-10-30 14:13:16 +01001252 return NO_ERROR;
1253}
1254
1255void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001256 postMessageAsync(new LambdaMessage([=] {
1257 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1258 const auto type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1259 getHwComposer().setContentType(*displayId, type);
1260 } else {
1261 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1262 }
1263 }));
Galia Peycheva5492cb52019-10-30 14:13:16 +01001264}
1265
Svetoslavd85084b2014-03-20 10:28:31 -07001266status_t SurfaceFlinger::clearAnimationFrameStats() {
1267 Mutex::Autolock _l(mStateLock);
1268 mAnimFrameTracker.clearStats();
1269 return NO_ERROR;
1270}
1271
1272status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1273 Mutex::Autolock _l(mStateLock);
1274 mAnimFrameTracker.getStats(outStats);
1275 return NO_ERROR;
1276}
1277
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001278status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1279 HdrCapabilities* outCapabilities) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001280 Mutex::Autolock lock(mStateLock);
Dan Stozac4f471e2016-03-24 09:31:08 -07001281
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001282 const auto display = getDisplayDeviceLocked(displayToken);
1283 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001284 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1285 return NAME_NOT_FOUND;
Dan Stozac4f471e2016-03-24 09:31:08 -07001286 }
1287
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001288 // At this point the DisplayDevice should already be set up,
Peiyong Linfb069302018-04-25 14:34:31 -07001289 // meaning the luminance information is already queried from
1290 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001291 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001292 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1293 capabilities.getDesiredMaxLuminance(),
1294 capabilities.getDesiredMaxAverageLuminance(),
1295 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001296
1297 return NO_ERROR;
1298}
1299
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001300std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1301 const DisplayDevice& display) const {
1302 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1303 // avoid repetitive HAL IPC and EDID parsing.
1304 const auto displayId = display.getId();
1305 LOG_FATAL_IF(!displayId);
1306
1307 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1308 LOG_FATAL_IF(!hwcDisplayId);
1309
1310 uint8_t port;
1311 DisplayIdentificationData data;
1312 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1313 ALOGV("%s: No identification data.", __FUNCTION__);
1314 return {};
1315 }
1316
1317 const auto info = parseDisplayIdentificationData(port, data);
1318 if (!info) {
1319 return {};
1320 }
1321 return info->deviceProductInfo;
1322}
1323
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001324status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1325 ui::PixelFormat* outFormat,
1326 ui::Dataspace* outDataspace,
1327 uint8_t* outComponentMask) const {
1328 if (!outFormat || !outDataspace || !outComponentMask) {
1329 return BAD_VALUE;
1330 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001331
1332 Mutex::Autolock lock(mStateLock);
1333
1334 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1335 if (!displayId) {
1336 return NAME_NOT_FOUND;
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001337 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001338
1339 return getHwComposer().getDisplayedContentSamplingAttributes(*displayId, outFormat,
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001340 outDataspace, outComponentMask);
1341}
1342
Kevin DuBois74e53772018-11-19 10:52:38 -08001343status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1344 bool enable, uint8_t componentMask,
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001345 uint64_t maxFrames) {
1346 status_t result = NAME_NOT_FOUND;
Kevin DuBois74e53772018-11-19 10:52:38 -08001347
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001348 postMessageSync(new LambdaMessage([&] {
1349 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1350 result = getHwComposer().setDisplayContentSamplingEnabled(*displayId, enable,
1351 componentMask, maxFrames);
1352 } else {
1353 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1354 }
1355 }));
1356
1357 return result;
Kevin DuBois74e53772018-11-19 10:52:38 -08001358}
1359
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001360status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1361 uint64_t maxFrames, uint64_t timestamp,
1362 DisplayedFrameStats* outStats) const {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001363 Mutex::Autolock lock(mStateLock);
1364
1365 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1366 if (!displayId) {
1367 return NAME_NOT_FOUND;
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001368 }
1369
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001370 return getHwComposer().getDisplayedContentSample(*displayId, maxFrames, timestamp, outStats);
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001371}
1372
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001373status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1374 if (!outSupported) {
1375 return BAD_VALUE;
1376 }
1377 *outSupported = getRenderEngine().supportsProtectedContent();
1378 return NO_ERROR;
1379}
1380
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001381status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1382 bool* outIsWideColorDisplay) const {
1383 if (!displayToken || !outIsWideColorDisplay) {
1384 return BAD_VALUE;
1385 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001386
1387 Mutex::Autolock lock(mStateLock);
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001388 const auto display = getDisplayDeviceLocked(displayToken);
1389 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001390 return NAME_NOT_FOUND;
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001391 }
Peiyong Linff84a152019-05-17 18:36:19 -07001392
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001393 *outIsWideColorDisplay =
1394 display->isPrimary() ? hasWideColorDisplay : display->hasWideColorGamut();
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001395 return NO_ERROR;
1396}
1397
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001398status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001399 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001400 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001401
Dominik Laskowski6505f792019-09-18 11:10:05 -07001402 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1403 mEventQueue->setEventConnection(
1404 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001405 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001406 }));
1407
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001408 return NO_ERROR;
1409}
1410
1411status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001412 Mutex::Autolock lock(mStateLock);
1413 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001414}
1415
Lloyd Pique755e3192018-01-31 16:46:15 -08001416status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1417 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001418 // Try to acquire a lock for 1s, fail gracefully
1419 const status_t err = mStateLock.timedLock(s2ns(1));
1420 const bool locked = (err == NO_ERROR);
1421 if (!locked) {
1422 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1423 return TIMED_OUT;
1424 }
1425
1426 outLayers->clear();
1427 mCurrentState.traverseInZOrder([&](Layer* layer) {
1428 outLayers->push_back(layer->getLayerDebugInfo());
1429 });
1430
1431 mStateLock.unlock();
1432 return NO_ERROR;
1433}
1434
Peiyong Linc6780972018-10-28 15:24:08 -07001435status_t SurfaceFlinger::getCompositionPreference(
1436 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1437 Dataspace* outWideColorGamutDataspace,
1438 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001439 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001440 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001441 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001442 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001443 return NO_ERROR;
1444}
1445
Dan Stozaec460082018-12-17 15:35:09 -08001446status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1447 const sp<IBinder>& stopLayerHandle,
1448 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001449 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001450 return BAD_VALUE;
1451 }
Alec Mouri9a02eda2020-04-21 17:39:34 -07001452
1453 const wp<Layer> stopLayer = fromHandle(stopLayerHandle);
1454 mRegionSamplingThread->addListener(samplingArea, stopLayer, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001455 return NO_ERROR;
1456}
1457
Dan Stozaec460082018-12-17 15:35:09 -08001458status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001459 if (!listener) {
1460 return BAD_VALUE;
1461 }
Dan Stozaec460082018-12-17 15:35:09 -08001462 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001463 return NO_ERROR;
1464}
Dan Gittik57e63c52019-01-18 16:37:54 +00001465
1466status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1467 bool* outSupport) const {
1468 if (!displayToken || !outSupport) {
1469 return BAD_VALUE;
1470 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001471
1472 Mutex::Autolock lock(mStateLock);
1473
Dan Gittik57e63c52019-01-18 16:37:54 +00001474 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1475 if (!displayId) {
1476 return NAME_NOT_FOUND;
1477 }
1478 *outSupport =
Dominik Laskowski1162e472020-04-02 19:02:47 -07001479 getHwComposer().hasDisplayCapability(*displayId, HWC2::DisplayCapability::Brightness);
Dan Gittik57e63c52019-01-18 16:37:54 +00001480 return NO_ERROR;
1481}
1482
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001483status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken, float brightness) {
Dan Gittik57e63c52019-01-18 16:37:54 +00001484 if (!displayToken) {
1485 return BAD_VALUE;
1486 }
Dominik Laskowski470df5f2020-04-02 22:27:42 -07001487
1488 status_t result = NAME_NOT_FOUND;
1489
1490 postMessageSync(new LambdaMessage([&] {
1491 if (const auto displayId = getPhysicalDisplayIdLocked(displayToken)) {
1492 result = getHwComposer().setDisplayBrightness(*displayId, brightness);
1493 } else {
1494 ALOGE("%s: Invalid display token %p", __FUNCTION__, displayToken.get());
1495 }
1496 }));
1497
1498 return result;
Dan Gittik57e63c52019-01-18 16:37:54 +00001499}
1500
Ady Abraham8532d012019-05-08 14:50:56 -07001501status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1502 PowerHint powerHint = static_cast<PowerHint>(hintId);
1503
1504 if (powerHint == PowerHint::INTERACTION) {
1505 mScheduler->notifyTouchEvent();
1506 }
1507
1508 return NO_ERROR;
1509}
1510
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001511// ----------------------------------------------------------------------------
1512
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001513sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001514 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001515 const auto& handle =
1516 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001517
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001518 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001519}
1520
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001521// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001522
1523void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001524 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001525}
1526
1527void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001528 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001529 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001530 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001531}
1532
1533void SurfaceFlinger::signalLayerUpdate() {
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::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001540 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001541 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001542}
1543
1544status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001545 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001546 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001547}
1548
1549status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001550 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001551 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001552 if (res == NO_ERROR) {
1553 msg->wait();
1554 }
1555 return res;
1556}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001557
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001558void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001559 do {
1560 waitForEvent();
1561 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001562}
1563
Dominik Laskowski83b88212018-12-11 13:34:06 -08001564nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001565 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001566 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1567 return 0;
1568 }
1569
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001570 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001571}
1572
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001573void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001574 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001575 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001576 ATRACE_NAME("SF onVsync");
1577
Steven Thomas3cfac282017-02-06 12:29:30 -08001578 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001579 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001580 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001581 return;
1582 }
1583
Dominik Laskowski075d3172018-05-24 15:50:06 -07001584 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001585 return;
1586 }
1587
Dominik Laskowski075d3172018-05-24 15:50:06 -07001588 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001589 // For now, we don't do anything with external display vsyncs.
1590 return;
1591 }
1592
Alec Mourif8e689c2019-05-20 18:32:22 -07001593 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001594 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001595 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001596 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001597 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001598}
1599
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001600void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001601 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1602 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001603}
1604
Ady Abraham2139f732019-11-13 18:56:40 -08001605bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001606 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001607}
1608
Ady Abraham2139f732019-11-13 18:56:40 -08001609void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1610 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001611 const auto display = getDefaultDisplayDeviceLocked();
1612 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001613 return;
1614 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001615 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001616
Ana Krulec7d1d6832018-12-27 11:10:09 -08001617 // Don't do any updating if the current fps is the same as the new one.
Ady Abrahamabc27602020-04-08 17:20:29 -07001618 if (!isDisplayConfigAllowed(refreshRate.getConfigId())) {
Ady Abraham2139f732019-11-13 18:56:40 -08001619 ALOGV("Skipping config %d as it is not part of allowed configs",
Ady Abrahamabc27602020-04-08 17:20:29 -07001620 refreshRate.getConfigId().value());
Ady Abraham1902d072019-03-01 17:18:59 -08001621 return;
1622 }
1623
Ady Abrahamabc27602020-04-08 17:20:29 -07001624 setDesiredActiveConfig({refreshRate.getConfigId(), event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001625}
1626
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001627void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001628 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001629 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001630 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001631
Lloyd Piqueba04e622017-12-14 17:11:26 -08001632 // Ignore events that do not have the right sequenceId.
1633 if (sequenceId != getBE().mComposerSequenceId) {
1634 return;
1635 }
1636
Steven Thomasb02664d2017-07-26 18:48:28 -07001637 // Only lock if we're not on the main thread. This function is normally
1638 // called on a hwbinder thread, but for the primary display it's called on
1639 // the main thread with the state lock already held, so don't attempt to
1640 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001641 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001642
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001643 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001644
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001645 if (std::this_thread::get_id() == mMainThreadId) {
1646 // Process all pending hot plug events immediately if we are on the main thread.
1647 processDisplayHotplugEventsLocked();
1648 }
1649
Lloyd Piqueba04e622017-12-14 17:11:26 -08001650 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001651}
1652
Ady Abraham7159f572019-10-11 11:10:18 -07001653void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001654 int32_t sequenceId, hwc2_display_t /*display*/,
1655 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1656 Mutex::Autolock lock(mStateLock);
1657 if (sequenceId != getBE().mComposerSequenceId) {
1658 return;
1659 }
1660 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001661}
1662
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001663void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1664 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1665 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1666}
1667
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001668void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001669 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001670 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001671 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001672 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001673 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001674}
1675
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001676void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001677 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001678
1679 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1680 // display power state.
1681 postMessageAsync(new LambdaMessage(
1682 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1683}
1684
1685void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1686 ATRACE_CALL();
1687
Ady Abraham27c70212019-06-11 10:52:26 -07001688 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1689
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001690 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001691 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1692 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001693 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001694 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001695 }
Mathias Agopian86303202012-07-24 22:46:10 -07001696}
1697
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001698// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001699void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001700 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001701 // Clear the drawing state so that the logic inside of
1702 // handleTransactionLocked will fire. It will determine the delta between
1703 // mCurrentState and mDrawingState and re-apply all changes when we make the
1704 // transition.
1705 mDrawingState.displays.clear();
1706 mDisplays.clear();
1707}
1708
Steven Thomas050b2c82017-03-06 11:45:16 -08001709void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001710 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001711 if (!mVrFlinger)
1712 return;
1713 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001714 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001715 return;
1716 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001717
Lloyd Pique441d5042018-10-18 16:49:51 -07001718 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001719 ALOGE("Vr flinger is only supported for remote hardware composer"
1720 " service connections. Ignoring request to transition to vr"
1721 " flinger.");
1722 mVrFlingerRequestsDisplay = false;
1723 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001724 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001725
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001726 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001727
Steven Thomas0123ac62018-07-12 11:32:34 -07001728 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001729 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001730
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001731 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001732
1733 // Clear out all the output layers from the composition engine for all
1734 // displays before destroying the hardware composer interface. This ensures
1735 // any HWC layers are destroyed through that interface before it becomes
1736 // invalid.
1737 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001738 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001739 }
1740
Steven Thomas0123ac62018-07-12 11:32:34 -07001741 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1742 // called below. Clear the reference now so we don't accidentally use it
1743 // later.
1744 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001745
Steven Thomasb02664d2017-07-26 18:48:28 -07001746 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001747 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001748 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001749
Steven Thomasb02664d2017-07-26 18:48:28 -07001750 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001751 // Delete the current instance before creating the new one
1752 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1753 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1754 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001755 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001756
Lloyd Pique441d5042018-10-18 16:49:51 -07001757 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001758 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001759
1760 if (vrFlingerRequestsDisplay) {
1761 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001762 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001763
1764 mVisibleRegionsDirty = true;
1765 invalidateHwcGeometry();
1766
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001767 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001768 display = getDefaultDisplayDeviceLocked();
1769 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001770 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001771
Steven Thomasb02664d2017-07-26 18:48:28 -07001772 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001773 const nsecs_t vsyncPeriod = getVsyncPeriod();
1774 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001775
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001776 // The present fences returned from vr_hwc are not an accurate
1777 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001778 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001779
Steven Thomasb02664d2017-07-26 18:48:28 -07001780 // Use phase of 0 since phase is not known.
1781 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001782 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001783 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001784
Ana Krulecc2870422019-01-29 19:00:58 -08001785 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001786
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001787 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001788 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001789}
1790
Alec Mouri6d414b52020-03-17 11:18:05 -07001791sp<Fence> SurfaceFlinger::previousFrameFence() NO_THREAD_SAFETY_ANALYSIS {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001792 // We are storing the last 2 present fences. If sf's phase offset is to be
1793 // woken up before the actual vsync but targeting the next vsync, we need to check
1794 // fence N-2
Alec Mouri6d414b52020-03-17 11:18:05 -07001795 return mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1796 : mPreviousPresentFences[1];
1797}
1798
1799bool SurfaceFlinger::previousFramePending(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1800 ATRACE_CALL();
1801 const sp<Fence>& fence = previousFrameFence();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001802
Ady Abraham11579302019-09-19 12:35:58 -07001803 if (fence == Fence::NO_FENCE) {
1804 return false;
1805 }
1806
1807 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1808 fence->wait(graceTimeMs);
1809 }
1810
1811 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001812}
1813
Alec Mouri6d414b52020-03-17 11:18:05 -07001814nsecs_t SurfaceFlinger::previousFramePresentTime() NO_THREAD_SAFETY_ANALYSIS {
1815 const sp<Fence>& fence = previousFrameFence();
1816
1817 if (fence == Fence::NO_FENCE) {
1818 return Fence::SIGNAL_TIME_INVALID;
1819 }
1820
1821 return fence->getSignalTime();
1822}
1823
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001824void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001825 DisplayStatInfo stats;
1826 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001827 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001828 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001829 mExpectedPresentTime.store(
1830 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001831}
1832
Dominik Laskowski22488f62019-03-28 09:53:04 -07001833void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001834 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001835 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001836 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001837 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001838 // calculate the expected present time once and use the cached
1839 // value throughout this frame to make sure all layers are
1840 // seeing this same value.
Alec Mouri6d414b52020-03-17 11:18:05 -07001841 const nsecs_t lastExpectedPresentTime = mExpectedPresentTime.load();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001842 populateExpectedPresentTime();
1843
Ady Abraham11579302019-09-19 12:35:58 -07001844 // When Backpressure propagation is enabled we want to give a small grace period
1845 // for the present fence to fire instead of just giving up on this frame to handle cases
1846 // where present fence is just about to get signaled.
1847 const int graceTimeForPresentFenceMs =
1848 (mPropagateBackpressure &&
1849 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1850 ? 1
1851 : 0;
Alec Mouri6d414b52020-03-17 11:18:05 -07001852
1853 // Pending frames may trigger backpressure propagation.
1854 const TracedOrdinal<bool> framePending = {"PrevFramePending",
1855 previousFramePending(
1856 graceTimeForPresentFenceMs)};
1857
1858 // Frame missed counts for metrics tracking.
1859 // A frame is missed if the prior frame is still pending. If no longer pending,
1860 // then we still count the frame as missed if the predicted present time
1861 // was further in the past than when the fence actually fired.
1862
1863 // Add some slop to correct for drift. This should generally be
1864 // smaller than a typical frame duration, but should not be so small
1865 // that it reports reasonable drift as a missed frame.
1866 DisplayStatInfo stats;
1867 mScheduler->getDisplayStatInfo(&stats);
1868 const nsecs_t frameMissedSlop = stats.vsyncPeriod / 2;
1869 const nsecs_t previousPresentTime = previousFramePresentTime();
1870 const TracedOrdinal<bool> frameMissed =
1871 {"PrevFrameMissed",
1872 framePending ||
1873 (previousPresentTime >= 0 &&
1874 (lastExpectedPresentTime < previousPresentTime - frameMissedSlop))};
1875 const TracedOrdinal<bool> hwcFrameMissed = {"PrevHwcFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001876 mHadDeviceComposition && frameMissed};
Alec Mouri6d414b52020-03-17 11:18:05 -07001877 const TracedOrdinal<bool> gpuFrameMissed = {"PrevGpuFrameMissed",
Ady Abraham50204dd2019-07-19 15:47:11 -07001878 mHadClientComposition && frameMissed};
1879
Alec Mouricc0fc602019-02-26 21:45:19 -08001880 if (frameMissed) {
1881 mFrameMissedCount++;
1882 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001883 if (mMissedFrameJankCount == 0) {
1884 mMissedFrameJankStart = systemTime();
1885 }
1886 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001887 }
1888
Alec Mouri40189b02019-03-05 15:07:54 -08001889 if (hwcFrameMissed) {
1890 mHwcFrameMissedCount++;
1891 }
1892
1893 if (gpuFrameMissed) {
1894 mGpuFrameMissedCount++;
1895 }
1896
Ady Abraham27cbed72020-04-10 12:56:59 -07001897 // If we are in the middle of a config change and the fence hasn't
1898 // fired yet just wait for the next invalidate
1899 if (mSetActiveConfigPending) {
1900 if (framePending) {
1901 mEventQueue->invalidate();
1902 break;
1903 }
1904
1905 // We received the present fence from the HWC, so we assume it successfully updated
1906 // the config, hence we update SF.
1907 mSetActiveConfigPending = false;
1908 setActiveConfigInternal();
1909 }
1910
Alec Mouri6d414b52020-03-17 11:18:05 -07001911 if (framePending && mPropagateBackpressure) {
Ady Abrahamadb9a992019-09-19 21:21:55 +00001912 if ((hwcFrameMissed && !gpuFrameMissed) ||
1913 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001914 signalLayerUpdate();
1915 break;
1916 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001917 }
Dan Stoza50182882016-07-08 12:02:20 -07001918
Alec Mouri989ddbe2020-02-06 09:26:19 -08001919 // Our jank window is always at least 100ms since we missed a
1920 // frame...
1921 static constexpr nsecs_t kMinJankyDuration =
1922 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1923 // ...but if it's larger than 1s then we missed the trace cutoff.
1924 static constexpr nsecs_t kMaxJankyDuration =
1925 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1926 // If we're in a user build then don't push any atoms
1927 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1928 const auto displayDevice = getDefaultDisplayDeviceLocked();
1929 // Only report jank when the display is on, as displays in DOZE
1930 // power mode may operate at a different frame rate than is
1931 // reported in their config, which causes noticeable (but less
1932 // severe) jank.
1933 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1934 const nsecs_t currentTime = systemTime();
1935 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1936 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1937 ATRACE_NAME("Jank detected");
1938 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1939 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1940 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1941 jankyDurationMillis, mMissedFrameJankCount);
1942 }
1943
1944 // We either reported a jank event or we missed the trace
1945 // window, so clear counters here.
1946 if (jankDuration > kMinJankyDuration) {
1947 mMissedFrameJankCount = 0;
1948 mMissedFrameJankStart = 0;
1949 }
1950 }
1951 }
1952
Steven Thomas050b2c82017-03-06 11:45:16 -08001953 // Now that we're going to make it to the handleMessageTransaction()
1954 // call below it's safe to call updateVrFlinger(), which will
1955 // potentially trigger a display handoff.
1956 updateVrFlinger();
1957
Vishnu Nair60db8c02020-04-02 11:55:16 -07001958 bool refreshNeeded;
1959 withTracingLock([&]() {
1960 refreshNeeded = handleMessageTransaction();
1961 refreshNeeded |= handleMessageInvalidate();
1962 if (mTracingEnabled) {
1963 mAddCompositionStateToTrace =
1964 mTracing.flagIsSetLocked(SurfaceTracing::TRACE_COMPOSITION);
1965 if (mVisibleRegionsDirty && !mAddCompositionStateToTrace) {
1966 mTracing.notifyLocked("visibleRegionsDirty");
1967 }
1968 }
1969 });
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001970
Ana Krulecc84d09b2019-11-02 23:10:29 +01001971 // Layers need to get updated (in the previous line) before we can use them for
1972 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001973 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1974 // and may eventually call to ~Layer() if it holds the last reference
1975 {
1976 Mutex::Autolock _l(mStateLock);
1977 mScheduler->chooseRefreshRateForContent();
1978 }
1979
Ady Abraham27cbed72020-04-10 12:56:59 -07001980 performSetActiveConfig();
Ana Krulecc84d09b2019-11-02 23:10:29 +01001981
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001982 updateCursorAsync();
1983 updateInputFlinger();
1984
Dan Stoza58784442014-12-02 16:58:17 -08001985 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001986 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001987 // Signal a refresh if a transaction modified the window state,
1988 // a new buffer was latched, or if HWC has requested a full
1989 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001990 if (mFrameStartTime <= 0) {
1991 // We should only use the time of the first invalidate
1992 // message that signals a refresh as the beginning of the
1993 // frame. Otherwise the real frame time will be
1994 // underestimated.
1995 mFrameStartTime = frameStart;
1996 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001997 signalRefresh();
1998 }
1999 break;
2000 }
2001 case MessageQueue::REFRESH: {
2002 handleMessageRefresh();
2003 break;
2004 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002005 }
2006}
2007
Dan Stoza6b9454d2014-11-07 16:00:59 -08002008bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08002009 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002010 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07002011
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002012 bool flushedATransaction = flushTransactionQueues();
2013
2014 bool runHandleTransaction = transactionFlags &&
2015 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
2016
2017 if (runHandleTransaction) {
2018 handleTransaction(eTransactionMask);
2019 } else {
2020 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002021 }
2022
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002023 if (transactionFlushNeeded()) {
2024 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002025 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002026
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002027 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002028}
2029
Mathias Agopian4fec8732012-06-29 14:12:52 -07002030void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07002031 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07002032
Dan Stoza2b6d38e2017-06-01 16:40:30 -07002033 mRefreshPending = false;
2034
Lloyd Piqueab039b52019-02-13 14:22:42 -08002035 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002036 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08002037 for (const auto& [_, display] : mDisplays) {
2038 refreshArgs.outputs.push_back(display->getCompositionDisplay());
2039 }
2040 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08002041 if (auto layerFE = layer->getCompositionEngineLayerFE())
2042 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08002043 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002044 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
2045 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08002046 if (auto layerFE = layer->getCompositionEngineLayerFE())
2047 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002048 }
2049
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002050 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002051 refreshArgs.outputColorSetting = useColorManagement
2052 ? mDisplayColorSetting
2053 : compositionengine::OutputColorSetting::kUnmanaged;
2054 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
2055 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002056
2057 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
2058 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08002059 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002060
2061 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
2062 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
2063 mDrawingState.colorMatrixChanged = false;
2064 }
2065
2066 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
2067
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08002068 if (mDebugRegion != 0) {
2069 refreshArgs.devOptFlashDirtyRegionsDelay =
2070 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
2071 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002072
Lloyd Pique3eb1b212019-03-07 21:15:40 -08002073 mGeometryInvalid = false;
2074
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002075 // Store the present time just before calling to the composition engine so we could notify
2076 // the scheduler.
2077 const auto presentTime = systemTime();
2078
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002079 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08002080 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
2081 // Reset the frame start time now that we've recorded this frame.
2082 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002083
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002084 mScheduler->onDisplayRefreshed(presentTime);
2085
David Sodmanfa9b2af2017-12-24 13:28:59 -08002086 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002087 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002088
Lloyd Pique66d68602019-02-13 14:23:31 -08002089 mHadClientComposition =
2090 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2091 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002092 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2093 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002094 });
2095 mHadDeviceComposition =
2096 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2097 auto& displayDevice = tokenDisplayPair.second;
2098 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2099 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002100 mReusedClientComposition =
2101 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2102 auto& displayDevice = tokenDisplayPair.second;
2103 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2104 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002105
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002106 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002107
David Sodman7e4ae112018-02-09 15:02:28 -08002108 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002109 if (mVisibleRegionsDirty) {
2110 mVisibleRegionsDirty = false;
Vishnu Nair60db8c02020-04-02 11:55:16 -07002111 if (mTracingEnabled && mAddCompositionStateToTrace) {
Vishnu Nairdf529052019-06-07 14:53:14 -07002112 mTracing.notify("visibleRegionsDirty");
2113 }
2114 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002115
2116 if (mCompositionEngine->needsAnotherUpdate()) {
2117 signalLayerUpdate();
2118 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002119}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002120
David Sodmanfa9b2af2017-12-24 13:28:59 -08002121
2122bool SurfaceFlinger::handleMessageInvalidate() {
2123 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002124 bool refreshNeeded = handlePageFlip();
2125
Vishnu Nair4351ad52019-02-11 14:13:02 -08002126 if (mVisibleRegionsDirty) {
2127 computeLayerBounds();
2128 }
2129
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002130 for (auto& layer : mLayersPendingRefresh) {
2131 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002132 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002133 invalidateLayerStack(layer, visibleReg);
2134 }
2135 mLayersPendingRefresh.clear();
2136 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002137}
2138
Ana Krulece588e312018-09-18 12:32:24 -07002139void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2140 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002141 // Update queue of past composite+present times and determine the
2142 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002143 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002144 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002145 while (!getBE().mCompositePresentTimes.empty()) {
2146 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002147 // Cached values should have been updated before calling this method,
2148 // which helps avoid duplicate syscalls.
2149 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2150 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2151 break;
2152 }
2153 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002154 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002155 }
2156
2157 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002158 while (getBE().mCompositePresentTimes.size() > 16) {
2159 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002160 }
2161
Ana Krulece588e312018-09-18 12:32:24 -07002162 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002163}
2164
Ana Krulece588e312018-09-18 12:32:24 -07002165void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2166 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002167 // Integer division and modulo round toward 0 not -inf, so we need to
2168 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002169 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2170 ? (stats.vsyncPeriod -
2171 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2172 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002173
Ady Abraham9e16a482019-12-03 17:19:41 -08002174 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002175 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002176 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002177 }
2178
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002179 // Snap the latency to a value that removes scheduling jitter from the
2180 // composition and present times, which often have >1ms of jitter.
2181 // Reducing jitter is important if an app attempts to extrapolate
2182 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002183 // Snapping also allows an app to precisely calculate
2184 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002185 nsecs_t bias = stats.vsyncPeriod / 2;
2186 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2187 nsecs_t snappedCompositeToPresentLatency =
2188 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002189
David Sodman99974d22017-11-28 12:04:33 -08002190 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002191 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2192 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002193 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002194}
2195
David Sodman2b406362017-12-15 13:33:47 -08002196void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002197{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002198 ATRACE_CALL();
2199 ALOGV("postComposition");
2200
Brian Andersonf6386862016-10-31 16:34:13 -07002201 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002202 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002203 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002204 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002205 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002206 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002207
David Sodman73beded2017-11-15 11:56:06 -08002208 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002209 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002210 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002211 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002212 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2213 ->getRenderSurface()
2214 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002215 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002216 } else {
2217 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2218 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002219
David Sodman73beded2017-11-15 11:56:06 -08002220 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002221 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2222 mPreviousPresentFences[0] = displayDevice
2223 ? getHwComposer().getPresentFence(*displayDevice->getId())
2224 : Fence::NO_FENCE;
2225 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002226 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002227
Ana Krulece588e312018-09-18 12:32:24 -07002228 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002229 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002230
Lloyd Piqueab039b52019-02-13 14:22:42 -08002231 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2232 // be sampled a little later than when we started doing work for this frame,
2233 // but that should be okay since updateCompositorTiming has snapping logic.
2234 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2235 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002236 CompositorTiming compositorTiming;
2237 {
David Sodman99974d22017-11-28 12:04:33 -08002238 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2239 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002240 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002241
Edgar Arriaga844fa672020-01-16 14:21:42 -08002242 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002243 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2244 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002245 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002246 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002247 }
Robert Carr2047fae2016-11-28 14:09:09 -08002248 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002249
Valerie Hau4b678442020-04-14 10:50:42 -07002250 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
2251 mTransactionCompletedThread.sendCallbacks();
2252
Ady Abraham92fa2f42020-02-11 15:33:56 -08002253 if (displayDevice && displayDevice->isPrimary() &&
2254 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002255 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002256 }
2257
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002258 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002259 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2260 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002261 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002262 }
2263 }
2264
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002265 if (mAnimCompositionPending) {
2266 mAnimCompositionPending = false;
2267
Brian Anderson4e606e32017-03-16 15:34:57 -07002268 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002269 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002270 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002271 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002272 // The HWC doesn't support present fences, so use the refresh
2273 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002274 const nsecs_t presentTime =
2275 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002276 mAnimFrameTracker.setActualPresentTime(presentTime);
2277 }
2278 mAnimFrameTracker.advanceFrame();
2279 }
Dan Stozab90cf072015-03-05 11:05:59 -08002280
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002281 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002282 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002283 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002284 }
2285
Vishnu Nair9b079a22020-01-21 14:36:08 -08002286 if (mReusedClientComposition) {
2287 mTimeStats->incrementClientCompositionReusedFrames();
2288 }
2289
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002290 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002291
Alec Mouri717bcb62020-02-10 17:07:19 -08002292 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2293 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2294 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2295
Lloyd Pique32cbe282018-10-19 13:09:22 -07002296 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2297 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002298 return;
2299 }
2300
2301 nsecs_t currentTime = systemTime();
2302 if (mHasPoweredOff) {
2303 mHasPoweredOff = false;
2304 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002305 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002306 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002307 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2308 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002309 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002310 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002311 }
David Sodman4a36e932017-11-07 14:29:47 -08002312 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002313 }
David Sodman4a36e932017-11-07 14:29:47 -08002314 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002315
2316 {
2317 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002318 if (mTexturePool.size() < mTexturePoolSize) {
2319 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002320 const size_t offset = mTexturePool.size();
2321 mTexturePool.resize(mTexturePoolSize);
2322 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2323 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002324 } else if (mTexturePool.size() > mTexturePoolSize) {
2325 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2326 const size_t offset = mTexturePoolSize;
2327 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2328 mTexturePool.resize(mTexturePoolSize);
2329 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002330 }
2331 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002332
Kevin DuBois413287f2019-02-25 08:46:47 -08002333 if (mLumaSampling && mRegionSamplingThread) {
2334 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002335 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002336
2337 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2338 // side-effect of getTotalSize(), so we check that again here
2339 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002340 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002341 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2342 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002343}
2344
Vishnu Nair4351ad52019-02-11 14:13:02 -08002345void SurfaceFlinger::computeLayerBounds() {
2346 for (const auto& pair : mDisplays) {
2347 const auto& displayDevice = pair.second;
2348 const auto display = displayDevice->getCompositionDisplay();
2349 for (const auto& layer : mDrawingState.layersSortedByZ) {
2350 // only consider the layers on the given layer stack
2351 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002352 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002353 }
2354
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002355 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2356 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002357 }
2358 }
2359}
2360
David Sodmanfa9b2af2017-12-24 13:28:59 -08002361void SurfaceFlinger::postFrame()
2362{
2363 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002364 const auto display = getDefaultDisplayDeviceLocked();
2365 if (display && getHwComposer().isConnected(*display->getId())) {
2366 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002367 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2368 logFrameStats();
2369 }
2370 }
2371}
2372
Mathias Agopian87baae12012-07-31 12:38:26 -07002373void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002374{
Mathias Agopian841cde52012-03-01 15:44:37 -08002375 ATRACE_CALL();
2376
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002377 // here we keep a copy of the drawing state (that is the state that's
2378 // going to be overwritten by handleTransactionLocked()) outside of
2379 // mStateLock so that the side-effects of the State assignment
2380 // don't happen with mStateLock held (which can cause deadlocks).
2381 State drawingState(mDrawingState);
2382
Mathias Agopianca4d3602011-05-19 15:38:14 -07002383 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002384 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002385
Mathias Agopianca4d3602011-05-19 15:38:14 -07002386 // Here we're guaranteed that some transaction flags are set
2387 // so we can call handleTransactionLocked() unconditionally.
2388 // We call getTransactionFlags(), which will also clear the flags,
2389 // with mStateLock held to guarantee that mCurrentState won't change
2390 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002391
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002392 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002393 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002394 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002395
Mathias Agopianca4d3602011-05-19 15:38:14 -07002396 mDebugInTransaction = 0;
2397 invalidateHwcGeometry();
2398 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002399}
2400
Lloyd Piqueba04e622017-12-14 17:11:26 -08002401void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2402 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002403 const std::optional<DisplayIdentificationInfo> info =
2404 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002405
Dominik Laskowski075d3172018-05-24 15:50:06 -07002406 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002407 continue;
2408 }
2409
Dominik Laskowski55c85402020-01-21 16:25:47 -08002410 const DisplayId displayId = info->id;
2411 const auto it = mPhysicalDisplayTokens.find(displayId);
2412
Lloyd Piqueba04e622017-12-14 17:11:26 -08002413 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002414 if (it == mPhysicalDisplayTokens.end()) {
2415 ALOGV("Creating display %s", to_string(displayId).c_str());
2416
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002417 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002418 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002419 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002420
Dominik Laskowski075d3172018-05-24 15:50:06 -07002421 DisplayDeviceState state;
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002422 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId),
2423 event.hwcDisplayId};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002424 state.isSecure = true; // All physical displays are currently considered secure.
2425 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002426
2427 sp<IBinder> token = new BBinder();
2428 mCurrentState.displays.add(token, state);
2429 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2430
Dominik Laskowski075d3172018-05-24 15:50:06 -07002431 mInterceptor->saveDisplayCreation(state);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002432 } else {
2433 ALOGV("Recreating display %s", to_string(displayId).c_str());
2434
2435 const auto token = it->second;
2436 auto& state = mCurrentState.displays.editValueFor(token);
2437 state.sequenceId = DisplayDeviceState{}.sequenceId;
Steven Thomaseb6d2052018-03-20 15:40:48 -07002438 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002439 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002440 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002441
Dominik Laskowski55c85402020-01-21 16:25:47 -08002442 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002443 if (index >= 0) {
2444 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2445 mInterceptor->saveDisplayDeletion(state.sequenceId);
2446 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002447 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002448 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002449 }
2450
2451 processDisplayChangesLocked();
2452 }
2453
2454 mPendingHotplugEvents.clear();
2455}
2456
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002457void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002458 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2459 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002460}
2461
Lloyd Pique99d3da52018-01-22 17:48:03 -08002462sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002463 const wp<IBinder>& displayToken,
2464 std::shared_ptr<compositionengine::Display> compositionDisplay,
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002465 const DisplayDeviceState& state,
2466 const sp<compositionengine::DisplaySurface>& displaySurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002467 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002468 auto displayId = compositionDisplay->getDisplayId();
2469 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002470 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002471 creationArgs.isSecure = state.isSecure;
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002472 creationArgs.displaySurface = displaySurface;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002473 creationArgs.hasWideColorGamut = false;
2474 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002475
Dominik Laskowski55c85402020-01-21 16:25:47 -08002476 if (const auto& physical = state.physical) {
2477 creationArgs.connectionType = physical->type;
2478 }
2479
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002480 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002481 creationArgs.isPrimary = isInternalDisplay;
2482
2483 if (useColorManagement && displayId) {
2484 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002485 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002486 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002487 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002488 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002489
Dominik Laskowski7e045462018-05-30 13:02:02 -07002490 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002491 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002492 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002493 }
tangrobin6753a022018-08-10 10:58:54 +08002494 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002495
Dominik Laskowski075d3172018-05-24 15:50:06 -07002496 if (displayId) {
2497 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002498 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002499 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002500 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002501
Lloyd Pique90c115d2018-09-18 21:39:42 -07002502 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002503 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002504 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002505
Lloyd Pique99d3da52018-01-22 17:48:03 -08002506 // Make sure that composition can never be stalled by a virtual display
2507 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002508 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002509 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002510 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2511 }
2512
Dominik Laskowski718f9602019-11-09 20:01:35 -08002513 creationArgs.physicalOrientation =
2514 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002515
Lloyd Pique99d3da52018-01-22 17:48:03 -08002516 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002517 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002518
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002519 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002520
2521 if (maxFrameBufferAcquiredBuffers >= 3) {
2522 nativeWindowSurface->preallocateBuffers();
2523 }
2524
2525 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002526 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002527 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002528 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002529 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002530 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002531 display->getCompositionDisplay()->setColorProfile(
2532 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2533 RenderIntent::COLORIMETRIC,
2534 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002535 if (!state.isVirtual()) {
2536 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002537 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2538 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002539 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002540
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002541 display->setLayerStack(state.layerStack);
2542 display->setProjection(state.orientation, state.viewport, state.frame);
2543 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002544
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002545 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002546}
2547
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002548void SurfaceFlinger::processDisplayAdded(const wp<IBinder>& displayToken,
2549 const DisplayDeviceState& state) {
2550 int width = 0;
2551 int height = 0;
2552 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2553 if (state.physical) {
2554 const auto& activeConfig =
2555 getCompositionEngine().getHwComposer().getActiveConfig(state.physical->id);
2556 width = activeConfig->getWidth();
2557 height = activeConfig->getHeight();
2558 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2559 } else if (state.surface != nullptr) {
2560 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2561 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2562 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2563 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2564 int intPixelFormat;
2565 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2566 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2567 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2568 } else {
2569 // Virtual displays without a surface are dormant:
2570 // they have external state (layer stack, projection,
2571 // etc.) but no internal state (i.e. a DisplayDevice).
2572 return;
2573 }
2574
2575 compositionengine::DisplayCreationArgsBuilder builder;
2576 if (const auto& physical = state.physical) {
2577 builder.setPhysical({physical->id, physical->type});
2578 }
2579 builder.setPixels(ui::Size(width, height));
2580 builder.setPixelFormat(pixelFormat);
2581 builder.setIsSecure(state.isSecure);
2582 builder.setLayerStackId(state.layerStack);
2583 builder.setPowerAdvisor(&mPowerAdvisor);
2584 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer());
2585 builder.setName(state.displayName);
2586 const auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2587
2588 sp<compositionengine::DisplaySurface> displaySurface;
2589 sp<IGraphicBufferProducer> producer;
2590 sp<IGraphicBufferProducer> bqProducer;
2591 sp<IGraphicBufferConsumer> bqConsumer;
2592 getFactory().createBufferQueue(&bqProducer, &bqConsumer, /*consumerIsSurfaceFlinger =*/false);
2593
2594 std::optional<DisplayId> displayId = compositionDisplay->getId();
2595
2596 if (state.isVirtual()) {
2597 sp<VirtualDisplaySurface> vds =
2598 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface, bqProducer,
2599 bqConsumer, state.displayName);
2600
2601 displaySurface = vds;
2602 producer = vds;
2603 } else {
2604 ALOGE_IF(state.surface != nullptr,
2605 "adding a supported display, but rendering "
2606 "surface is provided (%p), ignoring it",
2607 state.surface.get());
2608
2609 LOG_ALWAYS_FATAL_IF(!displayId);
2610 displaySurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer,
2611 maxGraphicsWidth, maxGraphicsHeight);
2612 producer = bqProducer;
2613 }
2614
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002615 LOG_FATAL_IF(!displaySurface);
2616 const auto display = setupNewDisplayDeviceInternal(displayToken, compositionDisplay, state,
2617 displaySurface, producer);
2618 mDisplays.emplace(displayToken, display);
2619 if (!state.isVirtual()) {
2620 LOG_FATAL_IF(!displayId);
2621 dispatchDisplayHotplugEvent(displayId->value, true);
2622 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002623
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002624 if (display->isPrimary()) {
2625 mScheduler->onPrimaryDisplayAreaChanged(display->getWidth() * display->getHeight());
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002626 }
2627}
2628
2629void SurfaceFlinger::processDisplayRemoved(const wp<IBinder>& displayToken) {
2630 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2631 // Save display ID before disconnecting.
2632 const auto displayId = display->getId();
2633 display->disconnect();
2634
2635 if (!display->isVirtual()) {
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002636 LOG_FATAL_IF(!displayId);
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002637 dispatchDisplayHotplugEvent(displayId->value, false);
2638 }
2639 }
2640
2641 mDisplays.erase(displayToken);
2642}
2643
2644void SurfaceFlinger::processDisplayChanged(const wp<IBinder>& displayToken,
2645 const DisplayDeviceState& currentState,
2646 const DisplayDeviceState& drawingState) {
2647 const sp<IBinder> currentBinder = IInterface::asBinder(currentState.surface);
2648 const sp<IBinder> drawingBinder = IInterface::asBinder(drawingState.surface);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002649 if (currentBinder != drawingBinder || currentState.sequenceId != drawingState.sequenceId) {
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002650 // changing the surface is like destroying and recreating the DisplayDevice
2651 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2652 display->disconnect();
2653 }
2654 mDisplays.erase(displayToken);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002655 if (const auto& physical = currentState.physical) {
2656 getHwComposer().allocatePhysicalDisplay(physical->hwcDisplayId, physical->id);
2657 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002658 processDisplayAdded(displayToken, currentState);
Marin Shalamanov4a42d432020-02-12 20:22:26 +01002659 if (currentState.physical) {
2660 initializeDisplays();
2661 }
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002662 return;
2663 }
2664
2665 if (const auto display = getDisplayDeviceLocked(displayToken)) {
2666 if (currentState.layerStack != drawingState.layerStack) {
2667 display->setLayerStack(currentState.layerStack);
2668 }
2669 if ((currentState.orientation != drawingState.orientation) ||
2670 (currentState.viewport != drawingState.viewport) ||
2671 (currentState.frame != drawingState.frame)) {
2672 display->setProjection(currentState.orientation, currentState.viewport,
2673 currentState.frame);
2674 }
2675 if (currentState.width != drawingState.width ||
2676 currentState.height != drawingState.height) {
2677 display->setDisplaySize(currentState.width, currentState.height);
2678 if (display->isPrimary()) {
2679 mScheduler->onPrimaryDisplayAreaChanged(currentState.width * currentState.height);
2680 }
2681 }
2682 }
2683}
2684
Lloyd Pique347200f2017-12-14 17:00:15 -08002685void SurfaceFlinger::processDisplayChangesLocked() {
2686 // here we take advantage of Vector's copy-on-write semantics to
2687 // improve performance by skipping the transaction entirely when
2688 // know that the lists are identical
2689 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2690 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2691 if (!curr.isIdenticalTo(draw)) {
2692 mVisibleRegionsDirty = true;
Lloyd Pique347200f2017-12-14 17:00:15 -08002693
2694 // find the displays that were removed
2695 // (ie: in drawing state but not in current state)
2696 // also handle displays that changed
2697 // (ie: displays that are in both lists)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002698 for (size_t i = 0; i < draw.size(); i++) {
2699 const wp<IBinder>& displayToken = draw.keyAt(i);
2700 const ssize_t j = curr.indexOfKey(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002701 if (j < 0) {
2702 // in drawing state but not in current state
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002703 processDisplayRemoved(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002704 } else {
2705 // this display is in both lists. see if something changed.
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002706 const DisplayDeviceState& currentState = curr[j];
2707 const DisplayDeviceState& drawingState = draw[i];
2708 processDisplayChanged(displayToken, currentState, drawingState);
Lloyd Pique347200f2017-12-14 17:00:15 -08002709 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002710 }
2711
2712 // find displays that were added
2713 // (ie: in current state but not in drawing state)
Marin Shalamanov4ef04252020-02-12 17:12:22 +01002714 for (size_t i = 0; i < curr.size(); i++) {
2715 const wp<IBinder>& displayToken = curr.keyAt(i);
2716 if (draw.indexOfKey(displayToken) < 0) {
2717 processDisplayAdded(displayToken, curr[i]);
Lloyd Pique347200f2017-12-14 17:00:15 -08002718 }
2719 }
2720 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002721
2722 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002723}
2724
Mathias Agopian87baae12012-07-31 12:38:26 -07002725void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002726{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002727 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2728
Dan Stoza7dde5992015-05-22 09:51:44 -07002729 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002730 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002731 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002732 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002733
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002734 /*
2735 * Traversal of the children
2736 * (perform the transaction for each of them if needed)
2737 */
2738
Marissa Wall06255332019-03-27 13:48:27 -07002739 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002740 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002742 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002743
2744 const uint32_t flags = layer->doTransaction(0);
2745 if (flags & Layer::eVisibleRegion)
2746 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002747
2748 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002749 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002750 }
Robert Carr2047fae2016-11-28 14:09:09 -08002751 });
Marissa Wall06255332019-03-27 13:48:27 -07002752 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002753 }
2754
2755 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002756 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002757 */
2758
Mathias Agopiane57f2922012-08-09 16:29:12 -07002759 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002760 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002761 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002762 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002763
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002764 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002765 // The transform hint might have changed for some layers
2766 // (either because a display has changed, or because a layer
2767 // as changed).
2768 //
2769 // Walk through all the layers in currentLayers,
2770 // and update their transform hint.
2771 //
2772 // If a layer is visible only on a single display, then that
2773 // display is used to calculate the hint, otherwise we use the
2774 // default display.
2775 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002776 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002777 // the hint is set before we acquire a buffer from the surface texture.
2778 //
2779 // NOTE: layer transactions have taken place already, so we use their
2780 // drawing state. However, SurfaceFlinger's own transaction has not
2781 // happened yet, so we must use the current state layer list
2782 // (soon to become the drawing state list).
2783 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002784 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002785 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002786 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002787 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002788 // NOTE: we rely on the fact that layers are sorted by
2789 // layerStack first (so we don't have to traverse the list
2790 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002791 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002792 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002793 currentlayerStack = layerStack;
2794 // figure out if this layerstack is mirrored
2795 // (more than one display) if so, pick the default display,
2796 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002797 hintDisplay = nullptr;
2798 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002799 if (display->getCompositionDisplay()
2800 ->belongsInOutput(layer->getLayerStack(),
2801 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002802 if (hintDisplay) {
2803 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002804 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002805 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002806 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002807 }
2808 }
2809 }
2810 }
Chet Haase91d25932013-04-11 15:24:55 -07002811
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002812 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002813 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2814 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002815
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002816 // could be null when this layer is using a layerStack
2817 // that is not visible on any display. Also can occur at
2818 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002819 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002820 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002821
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002822 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002823 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002824 if (hintDisplay) {
2825 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002826 }
Robert Carr2047fae2016-11-28 14:09:09 -08002827
2828 first = false;
2829 });
Mathias Agopian84300952012-11-21 16:02:13 -08002830 }
2831
2832
Mathias Agopian3559b072012-08-15 13:46:03 -07002833 /*
2834 * Perform our own transaction if needed
2835 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002836
2837 if (mLayersAdded) {
2838 mLayersAdded = false;
2839 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002840 mVisibleRegionsDirty = true;
2841 }
2842
2843 // some layers might have been removed, so
2844 // we need to update the regions they're exposing.
2845 if (mLayersRemoved) {
2846 mLayersRemoved = false;
2847 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002848 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002849 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002850 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002851 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002852 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002853 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002854 }
Robert Carr2047fae2016-11-28 14:09:09 -08002855 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002856 }
2857
Vishnu Nairec0ab382019-02-13 15:32:56 -08002858 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002859 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002860}
2861
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002862void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002863 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002864 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002865 return;
2866 }
2867
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002868 if (mVisibleRegionsDirty || mInputInfoChanged) {
2869 mInputInfoChanged = false;
2870 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002871 } else if (mInputWindowCommands.syncInputWindows) {
2872 // If the caller requested to sync input windows, but there are no
2873 // changes to input windows, notify immediately.
2874 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002875 }
2876
Arthur Hung6cbb9752019-09-05 16:38:18 +08002877 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002878}
2879
2880void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002881 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002882
Robert Carra1257842020-01-31 13:48:28 -08002883 // We use a simple caching algorithm here. mInputDirty begins as true,
2884 // after we call setInputWindows we set it to false, so
2885 // in the future we wont call it again.. We set input dirty to true again
2886 // when any layer that hasInput() has a transaction performed on it
2887 // or when any parent or relative parent of such a layer has a transaction
2888 // performed on it. Not all of these transactions will really result in
2889 // input changes but all input changes will spring from these transactions
2890 // so the cache is safe but not optimal. It seems like it might be annoyingly
2891 // costly to cache and comapre the actual InputWindowHandle vector though.
Robert Carr0854b992020-03-11 12:09:42 -07002892 if (!mInputDirty && !mInputWindowCommands.syncInputWindows) {
Robert Carra1257842020-01-31 13:48:28 -08002893 return;
2894 }
2895
Robert Carr720e5062018-07-30 17:45:14 -07002896 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2897 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002898 // When calculating the screen bounds we ignore the transparent region since it may
2899 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002900 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002901 }
2902 });
chaviw291d88a2019-02-14 10:33:58 -08002903
2904 mInputFlinger->setInputWindows(inputHandles,
2905 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2906 : nullptr);
Robert Carra1257842020-01-31 13:48:28 -08002907
2908 mInputDirty = false;
Robert Carr720e5062018-07-30 17:45:14 -07002909}
2910
Vishnu Nairec0ab382019-02-13 15:32:56 -08002911void SurfaceFlinger::commitInputWindowCommands() {
Rob Carr9a2cc992020-03-06 12:44:45 -08002912 mInputWindowCommands.merge(mPendingInputWindowCommands);
Vishnu Nairec0ab382019-02-13 15:32:56 -08002913 mPendingInputWindowCommands.clear();
2914}
2915
Riley Andrews03414a12014-07-01 14:22:59 -07002916void SurfaceFlinger::updateCursorAsync()
2917{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002918 compositionengine::CompositionRefreshArgs refreshArgs;
2919 for (const auto& [_, display] : mDisplays) {
2920 if (display->getId()) {
2921 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002922 }
2923 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002924
2925 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002926}
2927
Ady Abraham2139f732019-11-13 18:56:40 -08002928void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002929 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2930 // If this is called from the main thread mStateLock must be locked before
2931 // Currently the only way to call this function from the main thread is from
2932 // Sheduler::chooseRefreshRateForContent
2933
2934 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002935 changeRefreshRateLocked(refreshRate, event);
2936}
2937
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002938void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2939 if (mScheduler) {
2940 // In practice it's not allowed to hotplug in/out the primary display once it's been
2941 // connected during startup, but some tests do it, so just warn and return.
2942 ALOGW("Can't re-init scheduler");
2943 return;
2944 }
2945
Ady Abraham2139f732019-11-13 18:56:40 -08002946 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002947 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002948 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002949 primaryDisplayId),
2950 currentConfig);
2951 mRefreshRateStats =
2952 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2953 currentConfig, HWC_POWER_MODE_OFF);
2954 mRefreshRateStats->setConfigMode(currentConfig);
2955
Ady Abraham9e16a482019-12-03 17:19:41 -08002956 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2957
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002958 // start the EventThread
2959 mScheduler =
2960 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002961 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002962 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002963 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002964 impl::EventThread::InterceptVSyncsCallback());
2965 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002966 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002967 [this](nsecs_t timestamp) {
2968 mInterceptor->saveVSyncEvent(timestamp);
2969 });
2970
2971 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2972 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002973 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002974
2975 mRegionSamplingThread =
2976 new RegionSamplingThread(*this, *mScheduler,
2977 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002978 // Dispatch a config change request for the primary display on scheduler
2979 // initialization, so that the EventThreads always contain a reference to a
2980 // prior configuration.
2981 //
2982 // This is a bit hacky, but this avoids a back-pointer into the main SF
2983 // classes from EventThread, and there should be no run-time binder cost
2984 // anyway since there are no connected apps at this point.
2985 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07002986 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).getVsyncPeriod();
Alec Mouri60aee1c2019-10-28 16:18:59 -07002987 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2988 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002989}
2990
Mathias Agopian4fec8732012-06-29 14:12:52 -07002991void SurfaceFlinger::commitTransaction()
2992{
Vishnu Nair60db8c02020-04-02 11:55:16 -07002993 commitTransactionLocked();
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002994 mTransactionPending = false;
2995 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002996 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002997}
2998
Lloyd Pique58e24a32019-08-01 15:50:14 -07002999void SurfaceFlinger::commitTransactionLocked() {
3000 if (!mLayersPendingRemoval.isEmpty()) {
3001 // Notify removed layers now that they can't be drawn from
3002 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003003 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07003004
3005 // Ensure any buffers set to display on any children are released.
3006 if (l->isRemovedFromCurrentState()) {
3007 l->latchAndReleaseBuffer();
3008 }
3009
3010 // If the layer has been removed and has no parent, then it will not be reachable
3011 // when traversing layers on screen. Add the layer to the offscreenLayers set to
3012 // ensure we can copy its current to drawing state.
3013 if (!l->getParent()) {
3014 mOffscreenLayers.emplace(l.get());
3015 }
3016 }
3017 mLayersPendingRemoval.clear();
3018 }
3019
3020 // If this transaction is part of a window animation then the next frame
3021 // we composite should be considered an animation as well.
3022 mAnimCompositionPending = mAnimTransactionPending;
3023
3024 mDrawingState = mCurrentState;
3025 // clear the "changed" flags in current state
3026 mCurrentState.colorMatrixChanged = false;
3027
Edgar Arriaga844fa672020-01-16 14:21:42 -08003028 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07003029 layer->commitChildList();
3030
3031 // If the layer can be reached when traversing mDrawingState, then the layer is no
3032 // longer offscreen. Remove the layer from the offscreenLayer set.
3033 if (mOffscreenLayers.count(layer)) {
3034 mOffscreenLayers.erase(layer);
3035 }
3036 });
3037
3038 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08003039 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07003040}
3041
Nataniel Borges2b796da2019-02-15 13:32:18 -08003042void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
3043 if (mTracingEnabledChanged) {
3044 mTracingEnabled = mTracing.isEnabled();
3045 mTracingEnabledChanged = false;
3046 }
3047
3048 // Synchronize with Tracing thread
3049 std::unique_lock<std::mutex> lock;
3050 if (mTracingEnabled) {
3051 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
3052 }
3053
3054 lockedOperation();
3055
3056 // Synchronize with Tracing thread
3057 if (mTracingEnabled) {
3058 lock.unlock();
3059 }
3060}
3061
chaviw74d90ad2019-04-26 14:45:26 -07003062void SurfaceFlinger::commitOffscreenLayers() {
3063 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003064 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07003065 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
3066 if (!trFlags) return;
3067
3068 layer->doTransaction(0);
3069 layer->commitChildList();
3070 });
3071 }
3072}
3073
Chia-I Wuab0c3192017-08-01 11:29:00 -07003074void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003075 for (const auto& [token, displayDevice] : mDisplays) {
3076 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08003077 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07003078 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07003079 }
3080 }
Mathias Agopian87baae12012-07-31 12:38:26 -07003081}
3082
Dan Stoza6b9454d2014-11-07 16:00:59 -08003083bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003084{
Ady Abraham09bd3922019-04-08 10:44:56 -07003085 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08003086 ALOGV("handlePageFlip");
3087
Brian Andersond6927fb2016-07-23 23:37:30 -07003088 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003089
Mathias Agopian4fec8732012-06-29 14:12:52 -07003090 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003091 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06003092 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07003093
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003094 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
3095
Eric Penner51c59cd2014-07-28 19:51:58 -07003096 // Store the set of layers that need updates. This set must not change as
3097 // buffers are being latched, as this could result in a deadlock.
3098 // Example: Two producers share the same command stream and:
3099 // 1.) Layer 0 is latched
3100 // 2.) Layer 0 gets a new frame
3101 // 2.) Layer 1 gets a new frame
3102 // 3.) Layer 1 is latched.
3103 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3104 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003105 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003106 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003107 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003108 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003109 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003110 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003111 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003112 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003113 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003114 } else {
3115 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003116 }
Robert Carr2047fae2016-11-28 14:09:09 -08003117 });
3118
chaviw49a108c2019-08-12 11:23:06 -07003119 // The client can continue submitting buffers for offscreen layers, but they will not
3120 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3121 // layers to ensure dequeueBuffer doesn't block indefinitely.
3122 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003123 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003124 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3125 }
3126
Lloyd Piquef2c79392018-12-20 16:23:33 -08003127 if (!mLayersWithQueuedFrames.empty()) {
3128 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3129 // writes to Layer current state. See also b/119481871
3130 Mutex::Autolock lock(mStateLock);
3131
3132 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003133 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003134 mLayersPendingRefresh.push_back(layer);
3135 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003136 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003137 if (layer->isBufferLatched()) {
3138 newDataLatched = true;
3139 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003140 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003141 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003142
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003143 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003144
3145 // If we will need to wake up at some time in the future to deal with a
3146 // queued frame that shouldn't be displayed during this vsync period, wake
3147 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003148 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003149 signalLayerUpdate();
3150 }
3151
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003152 // enter boot animation on first buffer latch
3153 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3154 ALOGI("Enter boot animation");
3155 mBootStage = BootStage::BOOTANIMATION;
3156 }
3157
Edgar Arriaga844fa672020-01-16 14:21:42 -08003158 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003159
Dan Stoza6b9454d2014-11-07 16:00:59 -08003160 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003161 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003162}
3163
Mathias Agopianad456f92011-01-13 17:53:01 -08003164void SurfaceFlinger::invalidateHwcGeometry()
3165{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003166 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003167}
3168
Robert Carrc0df3122019-04-11 13:18:21 -07003169status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3170 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3171 const sp<IBinder>& parentHandle,
3172 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003173 // add this layer to the current state list
3174 {
3175 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003176 sp<Layer> parent;
3177 if (parentHandle != nullptr) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003178 parent = fromHandleLocked(parentHandle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07003179 if (parent == nullptr) {
3180 return NAME_NOT_FOUND;
3181 }
3182 } else {
3183 parent = parentLayer;
3184 }
3185
Ady Abraham0a525092020-03-03 12:51:24 -08003186 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003187 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003188 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003189 return NO_MEMORY;
3190 }
Robert Carrc0df3122019-04-11 13:18:21 -07003191
3192 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3193
Robert Carrb89ea9d2018-12-10 13:01:14 -08003194 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003195 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003196 } else if (parent == nullptr) {
3197 lbc->onRemovedFromCurrentState();
3198 } else if (parent->isRemovedFromCurrentState()) {
3199 parent->addChild(lbc);
3200 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003201 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003202 parent->addChild(lbc);
3203 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003204
Yiwei Zhang243b3782018-05-15 17:40:04 -07003205 if (gbc != nullptr) {
3206 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3207 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3208 mMaxGraphicBufferProducerListSize,
3209 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3210 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003211 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003212 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003213 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003214 }
3215
Mathias Agopian96f08192010-06-02 23:28:45 -07003216 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003217 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003218
Dan Stoza7d89d062015-04-30 13:29:25 -07003219 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003220}
3221
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003222uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003223 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003224}
3225
Mathias Agopian3f844832013-08-07 21:24:32 -07003226uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003227 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003228}
3229
Mathias Agopian3f844832013-08-07 21:24:32 -07003230uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003231 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003232}
3233
3234uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003235 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003236 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003237 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003238 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003239 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003240 }
3241 return old;
3242}
3243
Marissa Wall713b63f2018-10-17 15:42:43 -07003244bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003245 // to prevent onHandleDestroyed from being called while the lock is held,
3246 // we must keep a copy of the transactions (specifically the composer
3247 // states) around outside the scope of the lock
3248 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003249 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003250 {
3251 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003252
Valerie Haufce31b82019-04-30 16:41:14 -07003253 auto it = mTransactionQueues.begin();
3254 while (it != mTransactionQueues.end()) {
3255 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003256
Valerie Haufce31b82019-04-30 16:41:14 -07003257 while (!transactionQueue.empty()) {
3258 const auto& transaction = transactionQueue.front();
3259 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003260 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003261 transaction.states)) {
3262 setTransactionFlags(eTransactionFlushNeeded);
3263 break;
3264 }
3265 transactions.push_back(transaction);
3266 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3267 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003268 transaction.buffer, transaction.postTime,
3269 transaction.privileged, transaction.hasListenerCallbacks,
3270 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003271 transactionQueue.pop();
3272 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003273 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003274
Valerie Haufce31b82019-04-30 16:41:14 -07003275 if (transactionQueue.empty()) {
3276 it = mTransactionQueues.erase(it);
3277 mTransactionCV.broadcast();
3278 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003279 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003280 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003281 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003282 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003283 return flushedATransaction;
3284}
3285
3286bool SurfaceFlinger::transactionFlushNeeded() {
3287 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003288}
3289
chaviwca27f252018-02-06 16:46:39 -08003290
Marissa Wall17b4e452018-12-26 16:32:34 -08003291bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003292 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003293 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003294 if (!useCachedExpectedPresentTime)
3295 populateExpectedPresentTime();
3296
3297 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003298 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3299 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3300 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3301 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3302 return false;
3303 }
3304
Marissa Wall713b63f2018-10-17 15:42:43 -07003305 for (const ComposerState& state : states) {
3306 const layer_state_t& s = state.state;
3307 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3308 continue;
3309 }
3310 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003311 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003312 }
3313 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003314 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003315}
3316
Valerie Hau9dab9732019-08-20 09:29:25 -07003317void SurfaceFlinger::setTransactionState(
3318 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3319 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3320 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3321 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003322 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003323
Valerie Haubc6ddb12019-03-08 11:10:15 -08003324 const int64_t postTime = systemTime();
3325
Robert Carr14167e02019-02-13 13:50:55 -08003326 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3327
Mathias Agopian698c0872011-06-28 19:09:31 -07003328 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003329
Marissa Wall713b63f2018-10-17 15:42:43 -07003330 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003331 auto itr = mTransactionQueues.find(applyToken);
3332 // if this is an animation frame, wait until prior animation frame has
3333 // been applied by SF
3334 if (flags & eAnimation) {
3335 while (itr != mTransactionQueues.end()) {
3336 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3337 if (CC_UNLIKELY(err != NO_ERROR)) {
3338 ALOGW_IF(err == TIMED_OUT,
3339 "setTransactionState timed out "
3340 "waiting for animation frame to apply");
3341 break;
3342 }
3343 itr = mTransactionQueues.find(applyToken);
3344 }
3345 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003346
3347 // Expected present time is computed and cached on invalidate, so it may be stale.
3348 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3349 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003350 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003351 uncacheBuffer, postTime, privileged,
3352 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003353 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003354 return;
3355 }
3356
Valerie Haubc6ddb12019-03-08 11:10:15 -08003357 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003358 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3359 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003360}
3361
Valerie Hau9dab9732019-08-20 09:29:25 -07003362void SurfaceFlinger::applyTransactionState(
3363 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3364 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3365 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3366 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3367 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003368 uint32_t transactionFlags = 0;
3369
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003370 if (flags & eAnimation) {
3371 // For window updates that are part of an animation we must wait for
3372 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003373 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003374 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003375 if (CC_UNLIKELY(err != NO_ERROR)) {
3376 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003377 // caller after a few seconds.
3378 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3379 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003380 mAnimTransactionPending = false;
3381 break;
3382 }
3383 }
3384 }
3385
chaviwca27f252018-02-06 16:46:39 -08003386 for (const DisplayState& display : displays) {
3387 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003388 }
3389
Valerie Hau9dab9732019-08-20 09:29:25 -07003390 // start and end registration for listeners w/ no surface so they can get their callback. Note
3391 // that listeners with SurfaceControls will start registration during setClientStateLocked
3392 // below.
3393 for (const auto& listener : listenerCallbacks) {
3394 mTransactionCompletedThread.startRegistration(listener);
3395 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003396 }
3397
Valerie Hau9dab9732019-08-20 09:29:25 -07003398 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003399 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003400 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003401 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3402 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003403 }
3404
Valerie Hau9dab9732019-08-20 09:29:25 -07003405 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003406 mTransactionCompletedThread.endRegistration(listenerCallback);
3407 }
3408
Marissa Walle2ffb422018-10-12 11:33:52 -07003409 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003410 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003411 mTransactionCompletedThread.sendCallbacks();
3412 }
3413 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003414
chaviw273171b2018-12-26 11:46:30 -08003415 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3416
Marissa Wall947d34e2019-03-29 14:03:53 -07003417 if (uncacheBuffer.isValid()) {
3418 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003419 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003420 }
3421
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003422 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3423 // anyway. This can be used as a flush mechanism for previous async transactions.
3424 // Empty animation transaction can be used to simulate back-pressure, so also force a
3425 // transaction for empty animation transactions.
3426 if (transactionFlags == 0 &&
3427 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003428 transactionFlags = eTransactionNeeded;
3429 }
3430
Marissa Wall06255332019-03-27 13:48:27 -07003431 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3432 // so we don't have to wake up again next frame to preform an uneeded traversal.
3433 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3434 transactionFlags = transactionFlags & (~eTraversalNeeded);
3435 mTraversalNeededMainThread = true;
3436 }
3437
Mathias Agopian386aa982011-11-07 21:58:03 -08003438 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003439 if (mInterceptor->isEnabled()) {
3440 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003441 }
Irvel468051e2016-06-13 16:44:44 -07003442
Mathias Agopian386aa982011-11-07 21:58:03 -08003443 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003444 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3445 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003446 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003447
3448 // if this is a synchronous transaction, wait for it to take effect
3449 // before returning.
3450 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003451 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003452 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003453 if (flags & eAnimation) {
3454 mAnimTransactionPending = true;
3455 }
chaviw4fe36852019-04-15 16:25:49 -07003456 if (mPendingInputWindowCommands.syncInputWindows) {
3457 mPendingSyncInputWindows = true;
3458 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003459
3460 // applyTransactionState can be called by either the main SF thread or by
3461 // another process through setTransactionState. While a given process may wish
3462 // to wait on synchronous transactions, the main SF thread should never
3463 // be blocked. Therefore, we only wait if isMainThread is false.
3464 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003465 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3466 if (CC_UNLIKELY(err != NO_ERROR)) {
3467 // just in case something goes wrong in SF, return to the
3468 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003469 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3470 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003471 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003472 break;
3473 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003474 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003475 }
3476}
3477
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003478uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3479 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3480 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003481
Mathias Agopiane57f2922012-08-09 16:29:12 -07003482 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003483 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3484
3485 const uint32_t what = s.what;
3486 if (what & DisplayState::eSurfaceChanged) {
3487 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3488 state.surface = s.surface;
3489 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003490 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003491 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003492 if (what & DisplayState::eLayerStackChanged) {
3493 if (state.layerStack != s.layerStack) {
3494 state.layerStack = s.layerStack;
3495 flags |= eDisplayTransactionNeeded;
3496 }
3497 }
3498 if (what & DisplayState::eDisplayProjectionChanged) {
3499 if (state.orientation != s.orientation) {
3500 state.orientation = s.orientation;
3501 flags |= eDisplayTransactionNeeded;
3502 }
3503 if (state.frame != s.frame) {
3504 state.frame = s.frame;
3505 flags |= eDisplayTransactionNeeded;
3506 }
3507 if (state.viewport != s.viewport) {
3508 state.viewport = s.viewport;
3509 flags |= eDisplayTransactionNeeded;
3510 }
3511 }
3512 if (what & DisplayState::eDisplaySizeChanged) {
3513 if (state.width != s.width) {
3514 state.width = s.width;
3515 flags |= eDisplayTransactionNeeded;
3516 }
3517 if (state.height != s.height) {
3518 state.height = s.height;
3519 flags |= eDisplayTransactionNeeded;
3520 }
3521 }
3522
Mathias Agopiane57f2922012-08-09 16:29:12 -07003523 return flags;
3524}
3525
Steven Thomasd4071902020-03-24 16:02:53 -07003526bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess(bool usePermissionCache) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003527 IPCThreadState* ipc = IPCThreadState::self();
3528 const int pid = ipc->getCallingPid();
3529 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003530 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Steven Thomasd4071902020-03-24 16:02:53 -07003531 (usePermissionCache ? !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)
3532 : !checkPermission(sAccessSurfaceFlinger, pid, uid))) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003533 return false;
3534 }
3535 return true;
3536}
3537
Marissa Wall3dad52d2019-03-22 14:03:19 -07003538uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003539 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3540 bool privileged,
3541 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003542 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003543
Valerie Hau9dab9732019-08-20 09:29:25 -07003544 for (auto& listener : s.listeners) {
3545 // note that startRegistration will not re-register if the listener has
3546 // already be registered for a prior surface control
3547 mTransactionCompletedThread.startRegistration(listener);
3548 listenerCallbacks.insert(listener);
3549 }
3550
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003551 sp<Layer> layer = nullptr;
3552 if (s.surface) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07003553 layer = fromHandleLocked(s.surface).promote();
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003554 } else {
3555 // The client may provide us a null handle. Treat it as if the layer was removed.
3556 ALOGW("Attempt to set client state with a null layer handle");
3557 }
chaviw8b3871a2017-11-01 17:41:01 -07003558 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003559 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003560 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003561 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003562 }
chaviw8b3871a2017-11-01 17:41:01 -07003563 return 0;
3564 }
3565
chaviw8b3871a2017-11-01 17:41:01 -07003566 uint32_t flags = 0;
3567
Garfield Tan8a3083e2018-12-03 13:21:07 -08003568 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003569
3570 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3571 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003572 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003573 layer->pushPendingState();
3574 }
3575
Valerie Hau871d6352020-01-29 08:44:02 -08003576 // Only set by BLAST adapter layers
3577 if (what & layer_state_t::eProducerDisconnect) {
3578 layer->onDisconnect();
3579 }
3580
chaviw8b3871a2017-11-01 17:41:01 -07003581 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003582 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003583 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003584 }
chaviw8b3871a2017-11-01 17:41:01 -07003585 }
3586 if (what & layer_state_t::eLayerChanged) {
3587 // NOTE: index needs to be calculated before we update the state
3588 const auto& p = layer->getParent();
3589 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003590 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003591 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003592 mCurrentState.layersSortedByZ.removeAt(idx);
3593 mCurrentState.layersSortedByZ.add(layer);
3594 // we need traversal (state changed)
3595 // AND transaction (list changed)
3596 flags |= eTransactionNeeded|eTraversalNeeded;
3597 }
chaviw8b3871a2017-11-01 17:41:01 -07003598 } else {
3599 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003600 flags |= eTransactionNeeded|eTraversalNeeded;
3601 }
3602 }
chaviw8b3871a2017-11-01 17:41:01 -07003603 }
3604 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003605 // NOTE: index needs to be calculated before we update the state
3606 const auto& p = layer->getParent();
3607 if (p == nullptr) {
3608 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3609 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3610 mCurrentState.layersSortedByZ.removeAt(idx);
3611 mCurrentState.layersSortedByZ.add(layer);
3612 // we need traversal (state changed)
3613 // AND transaction (list changed)
3614 flags |= eTransactionNeeded|eTraversalNeeded;
3615 }
3616 } else {
3617 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3618 flags |= eTransactionNeeded|eTraversalNeeded;
3619 }
chaviw8b3871a2017-11-01 17:41:01 -07003620 }
3621 }
3622 if (what & layer_state_t::eSizeChanged) {
3623 if (layer->setSize(s.w, s.h)) {
3624 flags |= eTraversalNeeded;
3625 }
3626 }
3627 if (what & layer_state_t::eAlphaChanged) {
3628 if (layer->setAlpha(s.alpha))
3629 flags |= eTraversalNeeded;
3630 }
3631 if (what & layer_state_t::eColorChanged) {
3632 if (layer->setColor(s.color))
3633 flags |= eTraversalNeeded;
3634 }
Peiyong Lind3788632018-09-18 16:01:31 -07003635 if (what & layer_state_t::eColorTransformChanged) {
3636 if (layer->setColorTransform(s.colorTransform)) {
3637 flags |= eTraversalNeeded;
3638 }
3639 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003640 if (what & layer_state_t::eBackgroundColorChanged) {
3641 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3642 flags |= eTraversalNeeded;
3643 }
3644 }
chaviw8b3871a2017-11-01 17:41:01 -07003645 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003646 // TODO: b/109894387
3647 //
3648 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3649 // rotation. To see the problem observe that if we have a square parent, and a child
3650 // of the same size, then we rotate the child 45 degrees around it's center, the child
3651 // must now be cropped to a non rectangular 8 sided region.
3652 //
3653 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3654 // private API, and the WindowManager only uses rotation in one case, which is on a top
3655 // level layer in which cropping is not an issue.
3656 //
3657 // However given that abuse of rotation matrices could lead to surfaces extending outside
3658 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3659 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3660 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003661 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003662 flags |= eTraversalNeeded;
3663 }
3664 if (what & layer_state_t::eTransparentRegionChanged) {
3665 if (layer->setTransparentRegionHint(s.transparentRegion))
3666 flags |= eTraversalNeeded;
3667 }
3668 if (what & layer_state_t::eFlagsChanged) {
3669 if (layer->setFlags(s.flags, s.mask))
3670 flags |= eTraversalNeeded;
3671 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003672 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003673 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003674 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003675 if (what & layer_state_t::eCornerRadiusChanged) {
3676 if (layer->setCornerRadius(s.cornerRadius))
3677 flags |= eTraversalNeeded;
3678 }
Lucas Dupin00f16422020-03-11 11:33:04 -07003679 if (what & layer_state_t::eBackgroundBlurRadiusChanged && !mDisableBlurs) {
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003680 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3681 }
chaviw8b3871a2017-11-01 17:41:01 -07003682 if (what & layer_state_t::eLayerStackChanged) {
3683 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3684 // We only allow setting layer stacks for top level layers,
3685 // everything else inherits layer stack from its parent.
3686 if (layer->hasParent()) {
3687 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003688 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003689 } else if (idx < 0) {
3690 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003691 "that also does not appear in the top level layer list. Something"
3692 " has gone wrong.",
3693 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003694 } else if (layer->setLayerStack(s.layerStack)) {
3695 mCurrentState.layersSortedByZ.removeAt(idx);
3696 mCurrentState.layersSortedByZ.add(layer);
3697 // we need traversal (state changed)
3698 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003699 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003700 }
3701 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003702 if (what & layer_state_t::eDeferTransaction_legacy) {
3703 if (s.barrierHandle_legacy != nullptr) {
3704 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3705 } else if (s.barrierGbp_legacy != nullptr) {
3706 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003707 if (authenticateSurfaceTextureLocked(gbp)) {
3708 const auto& otherLayer =
3709 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003710 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003711 } else {
3712 ALOGE("Attempt to defer transaction to to an"
3713 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003714 }
3715 }
chaviw8b3871a2017-11-01 17:41:01 -07003716 // We don't trigger a traversal here because if no other state is
3717 // changed, we don't want this to cause any more work
3718 }
chaviw8b3871a2017-11-01 17:41:01 -07003719 if (what & layer_state_t::eReparentChildren) {
3720 if (layer->reparentChildren(s.reparentHandle)) {
3721 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003722 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003723 }
chaviw8b3871a2017-11-01 17:41:01 -07003724 if (what & layer_state_t::eDetachChildren) {
3725 layer->detachChildren();
3726 }
3727 if (what & layer_state_t::eOverrideScalingModeChanged) {
3728 layer->setOverrideScalingMode(s.overrideScalingMode);
3729 // We don't trigger a traversal here because if no other state is
3730 // changed, we don't want this to cause any more work
3731 }
Marissa Wall61c58622018-07-18 10:12:20 -07003732 if (what & layer_state_t::eTransformChanged) {
3733 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3734 }
3735 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3736 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3737 flags |= eTraversalNeeded;
3738 }
3739 if (what & layer_state_t::eCropChanged) {
3740 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3741 }
Marissa Wall861616d2018-10-22 12:52:23 -07003742 if (what & layer_state_t::eFrameChanged) {
3743 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3744 }
Marissa Wall61c58622018-07-18 10:12:20 -07003745 if (what & layer_state_t::eAcquireFenceChanged) {
3746 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3747 }
3748 if (what & layer_state_t::eDataspaceChanged) {
3749 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3750 }
3751 if (what & layer_state_t::eHdrMetadataChanged) {
3752 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3753 }
3754 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3755 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3756 }
3757 if (what & layer_state_t::eApiChanged) {
3758 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3759 }
3760 if (what & layer_state_t::eSidebandStreamChanged) {
3761 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3762 }
Robert Carr720e5062018-07-30 17:45:14 -07003763 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003764 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003765 layer->setInputInfo(s.inputInfo);
3766 flags |= eTraversalNeeded;
3767 } else {
3768 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3769 }
Robert Carr720e5062018-07-30 17:45:14 -07003770 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003771 if (what & layer_state_t::eMetadataChanged) {
3772 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3773 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003774 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3775 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3776 flags |= eTraversalNeeded;
3777 }
3778 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003779 if (what & layer_state_t::eShadowRadiusChanged) {
3780 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3781 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003782 if (what & layer_state_t::eFrameRateSelectionPriority) {
3783 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3784 flags |= eTraversalNeeded;
3785 }
3786 }
Steven Thomas3172e202020-01-06 19:25:30 -08003787 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003788 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3789 "SurfaceFlinger::setClientStateLocked") &&
3790 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3791 Layer::FrameRate::convertCompatibility(
3792 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003793 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003794 }
Steven Thomas3172e202020-01-06 19:25:30 -08003795 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003796 // This has to happen after we reparent children because when we reparent to null we remove
3797 // child layers from current state and remove its relative z. If the children are reparented in
3798 // the same transaction, then we have to make sure we reparent the children first so we do not
3799 // lose its relative z order.
3800 if (what & layer_state_t::eReparent) {
3801 bool hadParent = layer->hasParent();
3802 if (layer->reparent(s.parentHandleForChild)) {
3803 if (!hadParent) {
3804 mCurrentState.layersSortedByZ.remove(layer);
3805 }
3806 flags |= eTransactionNeeded | eTraversalNeeded;
3807 }
3808 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003809 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003810 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3811 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003812 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3813 }
3814 }
Marissa Wall78b72202019-03-15 14:58:34 -07003815 bool bufferChanged = what & layer_state_t::eBufferChanged;
3816 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3817 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003818 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003819 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003820 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3821 if (success) {
3822 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3823 success = ClientCache::getInstance()
3824 .registerErasedRecipient(s.cachedBuffer,
3825 wp<ClientCache::ErasedRecipient>(this));
3826 if (!success) {
3827 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3828 }
3829 }
Marissa Wall78b72202019-03-15 14:58:34 -07003830 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003831 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003832 } else if (bufferChanged) {
3833 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003834 }
Marissa Wall78b72202019-03-15 14:58:34 -07003835 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003836 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3837 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003838 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003839 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003840 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003841 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3842 // Do not put anything that updates layer state or modifies flags after
3843 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003844 return flags;
3845}
3846
chaviw273171b2018-12-26 11:46:30 -08003847uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3848 uint32_t flags = 0;
chaviwa911b102019-02-14 10:18:33 -08003849 if (inputWindowCommands.syncInputWindows) {
3850 flags |= eTraversalNeeded;
3851 }
3852
Vishnu Nairec0ab382019-02-13 15:32:56 -08003853 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003854 return flags;
3855}
3856
chaviwfe94a222019-08-21 13:52:59 -07003857status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3858 sp<IBinder>* outHandle) {
3859 if (!mirrorFromHandle) {
3860 return NAME_NOT_FOUND;
3861 }
3862
3863 sp<Layer> mirrorLayer;
3864 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003865 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003866
3867 {
3868 Mutex::Autolock _l(mStateLock);
Alec Mouri9a02eda2020-04-21 17:39:34 -07003869 mirrorFrom = fromHandleLocked(mirrorFromHandle).promote();
chaviwfe94a222019-08-21 13:52:59 -07003870 if (!mirrorFrom) {
3871 return NAME_NOT_FOUND;
3872 }
3873
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003874 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3875 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003876 if (result != NO_ERROR) {
3877 return result;
3878 }
3879
3880 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3881 }
3882
3883 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3884}
3885
Marissa Wall2d814fb2019-04-09 18:52:57 +00003886status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3887 uint32_t h, PixelFormat format, uint32_t flags,
3888 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003889 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003890 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3891 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003892 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003893 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003894 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003895 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003896 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003897
Robert Carrc0df3122019-04-11 13:18:21 -07003898 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3899 "Expected only one of parentLayer or parentHandle to be non-null. "
3900 "Programmer error?");
3901
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003902 status_t result = NO_ERROR;
3903
3904 sp<Layer> layer;
3905
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003906 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003907
Evan Roskya1f1e152019-01-24 16:17:46 -08003908 bool primaryDisplayOnly = false;
3909
3910 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3911 // TODO b/64227542
3912 if (metadata.has(METADATA_WINDOW_TYPE)) {
3913 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3914 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003915 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003916 primaryDisplayOnly = true;
3917 }
3918 }
3919
Mathias Agopian3165cc22012-08-08 19:42:09 -07003920 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003921 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003922 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3923 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003924
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003925 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003926 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003927 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003928 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003929 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003930 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003931 // check if buffer size is set for color layer.
3932 if (w > 0 || h > 0) {
3933 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3934 int(w), int(h));
3935 return BAD_VALUE;
3936 }
3937
Vishnu Nairfa247b12020-02-11 08:58:26 -08003938 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3939 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003940 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003941 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003942 // check if buffer size is set for container layer.
3943 if (w > 0 || h > 0) {
3944 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3945 int(w), int(h));
3946 return BAD_VALUE;
3947 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003948 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3949 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003950 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003951 default:
3952 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003953 break;
3954 }
3955
Dan Stoza7d89d062015-04-30 13:29:25 -07003956 if (result != NO_ERROR) {
3957 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003958 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003959
Evan Roskya1f1e152019-01-24 16:17:46 -08003960 if (primaryDisplayOnly) {
3961 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003962 }
3963
Robert Carrb89ea9d2018-12-10 13:01:14 -08003964 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003965 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3966 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003967 if (result != NO_ERROR) {
3968 return result;
3969 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003970 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003971
3972 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003973 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003974}
3975
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003976std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3977 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003978
3979 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003980 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003981
Dan Stoza436ccf32018-06-21 12:10:12 -07003982 // Grab the state lock since we're accessing mCurrentState
3983 Mutex::Autolock lock(mStateLock);
3984
Cody Northropbc755282017-03-31 12:00:08 -06003985 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003986 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003987 while (matchFound) {
3988 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003989 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003990 if (layer->getName() == uniqueName) {
3991 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003992 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003993 }
3994 });
3995 }
3996
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003997 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003998 return uniqueName;
3999}
4000
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004001status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07004002 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004003 LayerMetadata metadata, PixelFormat& format,
4004 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07004005 sp<IGraphicBufferProducer>* gbp,
4006 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004007 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07004008 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004009 case PIXEL_FORMAT_TRANSPARENT:
4010 case PIXEL_FORMAT_TRANSLUCENT:
4011 format = PIXEL_FORMAT_RGBA_8888;
4012 break;
4013 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07004014 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004015 break;
4016 }
4017
chaviwb4c6e582019-08-16 14:35:07 -07004018 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004019 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004020 args.textureName = getNewTexture();
4021 {
4022 // Grab the SF state lock during this since it's the only safe way to access
4023 // RenderEngine when creating a BufferLayerConsumer
4024 // TODO: Check if this lock is still needed here
4025 Mutex::Autolock lock(mStateLock);
4026 layer = getFactory().createBufferQueueLayer(args);
4027 }
4028
Marissa Wallfd668622018-05-10 10:21:13 -07004029 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004030 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07004031 *handle = layer->getHandle();
4032 *gbp = layer->getProducer();
4033 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004034 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004035
Marissa Wallfd668622018-05-10 10:21:13 -07004036 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004037 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004038}
4039
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004040status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07004041 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08004042 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07004043 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004044 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07004045 args.displayDevice = getDefaultDisplayDevice();
4046 args.textureName = getNewTexture();
4047 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07004048 if (outTransformHint) {
4049 *outTransformHint = layer->getTransformHint();
4050 }
Marissa Wall61c58622018-07-18 10:12:20 -07004051 *handle = layer->getHandle();
4052 *outLayer = layer;
4053
4054 return NO_ERROR;
4055}
4056
Vishnu Nairfa247b12020-02-11 08:58:26 -08004057status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
4058 uint32_t h, uint32_t flags, LayerMetadata metadata,
4059 sp<IBinder>* handle, sp<Layer>* outLayer) {
4060 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004061 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004062 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07004063 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07004064}
4065
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004066status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08004067 uint32_t w, uint32_t h, uint32_t flags,
4068 LayerMetadata metadata, sp<IBinder>* handle,
4069 sp<Layer>* outLayer) {
4070 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004071 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07004072 *handle = (*outLayer)->getHandle();
4073 return NO_ERROR;
4074}
4075
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004076void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07004077 mLayersPendingRemoval.add(layer);
4078 mLayersRemoved = true;
4079 setTransactionFlags(eTransactionNeeded);
4080}
4081
Robert Carr695d5282018-12-18 15:27:58 -08004082void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00004083{
Robert Carr2e102c92018-10-23 12:11:15 -07004084 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08004085 // If a layer has a parent, we allow it to out-live it's handle
4086 // with the idea that the parent holds a reference and will eventually
4087 // be cleaned up. However no one cleans up the top-level so we do so
4088 // here.
4089 if (layer->getParent() == nullptr) {
4090 mCurrentState.layersSortedByZ.remove(layer);
4091 }
4092 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07004093
4094 auto it = mLayersByLocalBinderToken.begin();
4095 while (it != mLayersByLocalBinderToken.end()) {
4096 if (it->second == layer) {
4097 it = mLayersByLocalBinderToken.erase(it);
4098 } else {
4099 it++;
4100 }
4101 }
4102
Robert Carr695d5282018-12-18 15:27:58 -08004103 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004104}
4105
Mathias Agopianb60314a2012-04-10 22:09:54 -07004106// ---------------------------------------------------------------------------
4107
Andy McFadden13a082e2012-08-24 10:16:42 -07004108void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004109 const auto display = getDefaultDisplayDeviceLocked();
4110 if (!display) return;
4111
4112 const sp<IBinder> token = display->getDisplayToken().promote();
4113 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004114
Jesse Hall01e29052013-02-19 16:13:35 -08004115 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004116 Vector<ComposerState> state;
4117 Vector<DisplayState> displays;
4118 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004119 d.what = DisplayState::eDisplayProjectionChanged |
4120 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004121 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004122 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004123 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004124 d.frame.makeInvalid();
4125 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004126 d.width = 0;
4127 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004128 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004129 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4130 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004131
Dominik Laskowskie9774092018-12-11 10:04:24 -08004132 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004133
Dominik Laskowski83b88212018-12-11 13:34:06 -08004134 const nsecs_t vsyncPeriod = getVsyncPeriod();
4135 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004136
Brian Andersond0010582017-03-07 13:20:31 -08004137 // Use phase of 0 since phase is not known.
4138 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004139 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004140 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004141}
4142
4143void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004144 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004145 postMessageAsync(
4146 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004147}
4148
Ady Abraham27c70212019-06-11 10:52:26 -07004149void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4150 if (mHWCVsyncState != enabled) {
4151 getHwComposer().setVsyncEnabled(displayId, enabled);
4152 mHWCVsyncState = enabled;
4153 }
4154}
4155
Dominik Laskowskie9774092018-12-11 10:04:24 -08004156void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004157 if (display->isVirtual()) {
4158 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004159 return;
4160 }
4161
Dominik Laskowski075d3172018-05-24 15:50:06 -07004162 const auto displayId = display->getId();
4163 LOG_ALWAYS_FATAL_IF(!displayId);
4164
Dominik Laskowski34157762018-10-31 13:07:19 -07004165 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004166
4167 int currentMode = display->getPowerMode();
4168 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004169 return;
4170 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004171
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004172 display->setPowerMode(mode);
4173
Lloyd Pique4dccc412018-01-22 17:21:36 -08004174 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004175 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004176 }
4177
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004178 if (currentMode == HWC_POWER_MODE_OFF) {
Martin Liu4a322352020-03-24 21:30:38 +08004179 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
4180 ALOGW("Couldn't set SCHED_FIFO on display on: %s\n", strerror(errno));
4181 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004182 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004183 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004184 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004185 mScheduler->onScreenAcquired(mAppConnectionHandle);
4186 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004187 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004188
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004189 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004190 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004191 repaintEverything();
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004192 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004193 // Turn off the display
Martin Liu4a322352020-03-24 21:30:38 +08004194 if (SurfaceFlinger::setSchedFifo(false) != NO_ERROR) {
4195 ALOGW("Couldn't set SCHED_OTHER on display off: %s\n", strerror(errno));
Tim Murrayf9d4e442016-08-02 15:43:59 -07004196 }
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->disableHardwareVsync(true);
4199 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004200 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004201
Ady Abraham27c70212019-06-11 10:52:26 -07004202 // Make sure HWVsync is disabled before turning off the display
4203 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4204
Dominik Laskowski075d3172018-05-24 15:50:06 -07004205 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004206 mVisibleRegionsDirty = true;
4207 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004208 } else if (mode == HWC_POWER_MODE_DOZE ||
4209 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004210 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004211 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004212 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004213 mScheduler->onScreenAcquired(mAppConnectionHandle);
4214 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004215 }
4216 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4217 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004218 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004219 mScheduler->disableHardwareVsync(true);
4220 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004221 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004222 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004223 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004224 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004225 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004226 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004227
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004228 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004229 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004230 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004231 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004232 }
4233
Dominik Laskowski34157762018-10-31 13:07:19 -07004234 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004235}
4236
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004237void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004238 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07004239 const auto display = getDisplayDeviceLocked(displayToken);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004240 if (!display) {
4241 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4242 displayToken.get());
4243 } else if (display->isVirtual()) {
4244 ALOGW("Attempt to set power mode %d for virtual display", mode);
4245 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004246 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004247 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004248 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004249}
4250
4251// ---------------------------------------------------------------------------
4252
Dominik Laskowskic2867142019-01-21 11:33:38 -08004253status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4254 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004255 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004256
Mathias Agopianbd115332013-04-18 16:41:04 -07004257 IPCThreadState* ipc = IPCThreadState::self();
4258 const int pid = ipc->getCallingPid();
4259 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004260
Mathias Agopianbd115332013-04-18 16:41:04 -07004261 if ((uid != AID_SHELL) &&
4262 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004263 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4264 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004265 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004266 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004267 // (this would indicate SF is stuck, but we want to be able to
4268 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004269 status_t err = mStateLock.timedLock(s2ns(1));
4270 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004271 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004272 StringAppendF(&result,
4273 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4274 "(no locks held)\n",
4275 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004276 }
4277
Dominik Laskowskic2867142019-01-21 11:33:38 -08004278 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004279 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004280 {"--dispsync"s,
4281 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004282 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004283 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4284 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4285 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4286 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4287 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4288 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004289 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004290 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4291 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004292
Dominik Laskowskic2867142019-01-21 11:33:38 -08004293 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004294
Dominik Laskowski46470112019-08-02 13:13:11 -07004295 const auto it = dumpers.find(flag);
4296 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004297 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004298 } else if (!asProto) {
4299 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004300 }
4301
Mathias Agopian9795c422009-08-26 16:36:26 -07004302 if (locked) {
4303 mStateLock.unlock();
4304 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004305
Dominik Laskowski46470112019-08-02 13:13:11 -07004306 if (it == dumpers.end()) {
4307 const LayersProto layersProto = dumpProtoFromMainThread();
4308 if (asProto) {
4309 result.append(layersProto.SerializeAsString());
4310 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004311 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004312 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4313 result.append(LayerProtoParser::layerTreeToString(layerTree));
4314 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004315 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004316 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004317 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004318 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004319 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004320 return NO_ERROR;
4321}
4322
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004323status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4324 if (asProto && mTracing.isEnabled()) {
4325 mTracing.writeToFileAsync();
4326 }
4327
4328 return doDump(fd, DumpArgs(), asProto);
4329}
4330
Dominik Laskowskic2867142019-01-21 11:33:38 -08004331void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004332 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004333 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004334}
4335
Dominik Laskowskic2867142019-01-21 11:33:38 -08004336void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004337 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004338
Dominik Laskowskic2867142019-01-21 11:33:38 -08004339 if (args.size() > 1) {
4340 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004341 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004342 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004343 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004344 }
Robert Carr2047fae2016-11-28 14:09:09 -08004345 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004346 } else {
4347 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004348 }
4349}
4350
Dominik Laskowskic2867142019-01-21 11:33:38 -08004351void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004352 const bool clearAll = args.size() < 2;
4353 const auto name = clearAll ? String8() : String8(args[1]);
4354
Edgar Arriaga844fa672020-01-16 14:21:42 -08004355 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004356 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004357 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004358 }
Robert Carr2047fae2016-11-28 14:09:09 -08004359 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004360
Svetoslavd85084b2014-03-20 10:28:31 -07004361 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004362}
4363
Dominik Laskowskic2867142019-01-21 11:33:38 -08004364void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4365 mTimeStats->parseArgs(asProto, args, result);
4366}
4367
Jamie Gennis6547ff42013-07-16 20:12:42 -07004368// This should only be called from the main thread. Otherwise it would need
4369// the lock and should use mCurrentState rather than mDrawingState.
4370void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004371 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004372 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004373 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004374
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004375 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004376}
4377
Yiwei Zhang5434a782018-12-05 18:06:32 -08004378void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004379 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004380
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004381 if (isLayerTripleBufferingDisabled())
4382 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004383
Yiwei Zhang5434a782018-12-05 18:06:32 -08004384 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4385 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4386 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4387 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4388 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4389 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004390 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004391}
4392
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004393void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004394 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004395
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004396 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004397 result.append("\n");
4398
Ady Abraham9e16a482019-12-03 17:19:41 -08004399 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004400 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004401 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004402 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004403
Steven Thomasd4071902020-03-24 16:02:53 -07004404 scheduler::RefreshRateConfigs::Policy policy = mRefreshRateConfigs->getDisplayManagerPolicy();
Ana Krulec234bb162019-11-10 22:55:55 +01004405 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004406 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004407 ", min: %.2f Hz, max: %.2f Hz",
Steven Thomasd4071902020-03-24 16:02:53 -07004408 policy.defaultConfig.value(), policy.minRefreshRate, policy.maxRefreshRate);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004409 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4410 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004411
Ana Krulecc2870422019-01-29 19:00:58 -08004412 mScheduler->dump(mAppConnectionHandle, result);
Ady Abraham75398722020-04-07 14:08:45 -07004413 mScheduler->getPrimaryDispSync().dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004414}
4415
Yiwei Zhang5434a782018-12-05 18:06:32 -08004416void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4417 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004418 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4419 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004420 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004421 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004422 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004423 }
David Sodman4a36e932017-11-07 14:29:47 -08004424 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004425 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004426 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004427 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4428 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004429}
4430
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004431void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4432 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004433 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4434 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004435 for (const auto& segment : history) {
4436 if (!segment.usedThirdBuffer) {
4437 stats.twoBufferTime += segment.totalTime;
4438 }
4439 if (segment.occupancyAverage < 1.0f) {
4440 stats.doubleBufferedTime += segment.totalTime;
4441 } else if (segment.occupancyAverage < 2.0f) {
4442 stats.tripleBufferedTime += segment.totalTime;
4443 }
4444 ++stats.numSegments;
4445 stats.totalTime += segment.totalTime;
4446 }
4447}
4448
Yiwei Zhang5434a782018-12-05 18:06:32 -08004449void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4450 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004451
4452 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4453 const size_t count = currentLayers.size();
4454 for (size_t i=0 ; i<count ; i++) {
4455 currentLayers[i]->dumpFrameEvents(result);
4456 }
4457}
4458
Yiwei Zhang5434a782018-12-05 18:06:32 -08004459void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004460 result.append("Buffering stats:\n");
4461 result.append(" [Layer name] <Active time> <Two buffer> "
4462 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004463 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004464 typedef std::tuple<std::string, float, float, float> BufferTuple;
4465 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004466 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004467 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004468 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004469 if (stats.numSegments == 0) {
4470 continue;
4471 }
4472 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4473 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4474 stats.totalTime;
4475 float doubleBufferRatio = static_cast<float>(
4476 stats.doubleBufferedTime) / stats.totalTime;
4477 float tripleBufferRatio = static_cast<float>(
4478 stats.tripleBufferedTime) / stats.totalTime;
4479 sorted.insert({activeTime, {name, twoBufferRatio,
4480 doubleBufferRatio, tripleBufferRatio}});
4481 }
4482 for (const auto& sortedPair : sorted) {
4483 float activeTime = sortedPair.first;
4484 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004485 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4486 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004487 }
4488 result.append("\n");
4489}
4490
Yiwei Zhang5434a782018-12-05 18:06:32 -08004491void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004492 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004493 const auto displayId = display->getId();
4494 if (!displayId) {
4495 continue;
4496 }
4497 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004498 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004499 continue;
4500 }
4501
Yiwei Zhang5434a782018-12-05 18:06:32 -08004502 StringAppendF(&result,
4503 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4504 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004505 uint8_t port;
4506 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004507 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004508 result.append("no identification data\n");
4509 continue;
4510 }
4511
4512 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004513 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004514 continue;
4515 }
4516
4517 const auto edid = parseEdid(data);
4518 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004519 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004520 continue;
4521 }
4522
Yiwei Zhang5434a782018-12-05 18:06:32 -08004523 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004524 result.append(edid->displayName.data(), edid->displayName.length());
4525 result.append("\"\n");
4526 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004527}
4528
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004529void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4530 std::string& result) const {
4531 hwc2_display_t hwcDisplayId;
4532 uint8_t port;
4533 DisplayIdentificationData data;
4534
4535 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4536 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4537 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4538 }
4539}
4540
Yiwei Zhang5434a782018-12-05 18:06:32 -08004541void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004542 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004543 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4544 StringAppendF(&result, "DisplayColorSetting: %s\n",
4545 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004546
4547 // TODO: print out if wide-color mode is active or not
4548
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004549 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004550 const auto displayId = display->getId();
4551 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004552 continue;
4553 }
4554
Yiwei Zhang5434a782018-12-05 18:06:32 -08004555 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004556 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004557 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004558 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004559 }
4560
Lloyd Pique32cbe282018-10-19 13:09:22 -07004561 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004562 StringAppendF(&result, " Current color mode: %s (%d)\n",
4563 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004564 }
4565 result.append("\n");
4566}
4567
Alec Mouri5793c7d2020-03-10 19:55:50 -07004568LayersProto SurfaceFlinger::dumpDrawingStateProto(
4569 uint32_t traceFlags, const sp<const DisplayDevice>& displayDevice) const {
chaviw1d044282017-09-27 12:19:28 -07004570 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004571 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Alec Mouri5793c7d2020-03-10 19:55:50 -07004572 layer->writeToProto(layersProto, traceFlags, displayDevice);
chaviw08f3cb22020-01-13 13:17:21 -08004573 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004574
chaviw1d044282017-09-27 12:19:28 -07004575 return layersProto;
4576}
4577
Alec Mouri6b9e9912020-01-21 10:50:24 -08004578void SurfaceFlinger::dumpHwc(std::string& result) const {
4579 getHwComposer().dump(result);
4580}
4581
Vishnu Nair0f085c62019-08-30 08:49:12 -07004582void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4583 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4584 // it.
4585 LayerProto* rootProto = layersProto.add_layers();
4586 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4587 rootProto->set_id(offscreenRootLayerId);
4588 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004589 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004590
4591 for (Layer* offscreenLayer : mOffscreenLayers) {
4592 // Add layer as child of the fake root
4593 rootProto->add_children(offscreenLayer->sequence);
4594
4595 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004596 LayerProto* layerProto =
4597 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004598 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004599 }
4600}
4601
Vishnu Nair8406fd72019-07-30 11:29:31 -07004602LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4603 LayersProto layersProto;
Alec Mouri5793c7d2020-03-10 19:55:50 -07004604 postMessageSync(new LambdaMessage([&]() {
4605 const auto& displayDevice = getDefaultDisplayDeviceLocked();
4606 layersProto = dumpDrawingStateProto(traceFlags, displayDevice);
4607 }));
Vishnu Nair8406fd72019-07-30 11:29:31 -07004608 return layersProto;
4609}
4610
Vishnu Nair0f085c62019-08-30 08:49:12 -07004611void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4612 result.append("Offscreen Layers:\n");
4613 postMessageSync(new LambdaMessage([&]() {
4614 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004615 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004616 layer->dumpCallingUidPid(result);
4617 });
4618 }
4619 }));
4620}
4621
Dominik Laskowskic2867142019-01-21 11:33:38 -08004622void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4623 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004624 Colorizer colorizer(colorize);
4625
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004626 // figure out if we're stuck somewhere
4627 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004628 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004629 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4630
4631 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004632 * Dump library configuration.
4633 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004634
4635 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004636 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004637 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004638 appendSfConfigString(result);
4639 appendUiConfigString(result);
4640 appendGuiConfigString(result);
4641 result.append("\n");
4642
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004643 result.append("\nDisplay identification data:\n");
4644 dumpDisplayIdentificationData(result);
4645
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004646 result.append("\nWide-Color information:\n");
4647 dumpWideColorInfo(result);
4648
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004649 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004650 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004651 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004652 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004653 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004654
Andy McFadden41d67d72014-04-25 16:58:34 -07004655 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004656 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004657 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004658 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004659 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004660
Dan Stozab90cf072015-03-05 11:05:59 -08004661 dumpStaticScreenStats(result);
4662 result.append("\n");
4663
Alec Mouri40189b02019-03-05 15:07:54 -08004664 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4665 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4666 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004667
Dan Stozae77c7662016-05-13 11:37:28 -07004668 dumpBufferingStats(result);
4669
Andy McFadden4803b742012-09-24 19:07:20 -07004670 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004671 * Dump the visible layer list
4672 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004673 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004674 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004675 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4676 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004677 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004678
Chia-I Wu2f884132018-09-13 15:17:58 -07004679 {
Lloyd Pique207def92019-02-28 16:09:52 -08004680 StringAppendF(&result, "Composition layers\n");
4681 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004682 auto* compositionState = layer->getCompositionState();
4683 if (!compositionState) return;
4684
4685 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4686 layer->getDebugName() ? layer->getDebugName()
4687 : "<unknown>");
4688 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004689 });
4690 }
4691
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004692 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004693 * Dump Display state
4694 */
4695
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004696 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004697 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004698 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004699 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004700 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004701 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004702 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004703
4704 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004705 * Dump CompositionEngine state
4706 */
4707
4708 mCompositionEngine->dump(result);
4709
4710 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004711 * Dump SurfaceFlinger global state
4712 */
4713
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004714 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004715 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004716 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004717
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004718 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004719
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004720 DebugEGLImageTracker::getInstance()->dump(result);
4721
Dominik Laskowski075d3172018-05-24 15:50:06 -07004722 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004723 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4724 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004725 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4726 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004727 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004728 StringAppendF(&result,
4729 " transaction-flags : %08x\n"
4730 " gpu_to_cpu_unsupported : %d\n",
4731 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004732
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004733 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004734 displayId && getHwComposer().isConnected(*displayId)) {
4735 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004736 StringAppendF(&result,
4737 " refresh-rate : %f fps\n"
4738 " x-dpi : %f\n"
4739 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004740 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4741 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004742 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004743
Yiwei Zhang5434a782018-12-05 18:06:32 -08004744 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004745
Dan Stozae22aec72016-08-01 13:20:59 -07004746 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004747 * Tracing state
4748 */
4749 mTracing.dump(result);
4750 result.append("\n");
4751
4752 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004753 * HWC layer minidump
4754 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004755 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004756 const auto displayId = display->getId();
4757 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004758 continue;
4759 }
4760
Yiwei Zhang5434a782018-12-05 18:06:32 -08004761 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004762 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004763 const sp<DisplayDevice> displayDevice = display;
4764 mCurrentState.traverseInZOrder(
4765 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004766 result.append("\n");
4767 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004768
4769 /*
4770 * Dump HWComposer state
4771 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004772 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004773 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004774 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004775 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004776 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004777 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004778
4779 /*
4780 * Dump gralloc state
4781 */
4782 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4783 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004784
4785 /*
4786 * Dump VrFlinger state if in use.
4787 */
4788 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4789 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004790 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004791 result.append("\n");
4792 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004793
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004794 result.append(mTimeStats->miniDump());
4795 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004796}
4797
Chia-I Wu28f320b2018-05-03 11:02:56 -07004798void SurfaceFlinger::updateColorMatrixLocked() {
4799 mat4 colorMatrix;
4800 if (mGlobalSaturationFactor != 1.0f) {
4801 // Rec.709 luma coefficients
4802 float3 luminance{0.213f, 0.715f, 0.072f};
4803 luminance *= 1.0f - mGlobalSaturationFactor;
4804 mat4 saturationMatrix = mat4(
4805 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4806 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4807 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4808 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4809 );
4810 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4811 } else {
4812 colorMatrix = mClientColorMatrix * mDaltonizer();
4813 }
4814
4815 if (mCurrentState.colorMatrix != colorMatrix) {
4816 mCurrentState.colorMatrix = colorMatrix;
4817 mCurrentState.colorMatrixChanged = true;
4818 setTransactionFlags(eTransactionNeeded);
4819 }
4820}
4821
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004822status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004823#pragma clang diagnostic push
4824#pragma clang diagnostic error "-Wswitch-enum"
4825 switch (static_cast<ISurfaceComposerTag>(code)) {
4826 // These methods should at minimum make sure that the client requested
4827 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004828 case BOOT_FINISHED:
4829 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004830 case CREATE_DISPLAY:
4831 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004832 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004833 case GET_ANIMATION_FRAME_STATS:
4834 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004835 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004836 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004837 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004838 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4839 case SET_AUTO_LOW_LATENCY_MODE:
4840 case GET_GAME_CONTENT_TYPE_SUPPORT:
4841 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004842 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004843 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004844 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004845 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004846 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004847 case NOTIFY_POWER_HINT:
Steven Thomasd4071902020-03-24 16:02:53 -07004848 case SET_GLOBAL_SHADOW_SETTINGS:
4849 case ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN: {
4850 // ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN is used by CTS tests, which acquire the
4851 // necessary permission dynamically. Don't use the permission cache for this check.
4852 bool usePermissionCache = code != ACQUIRE_FRAME_RATE_FLEXIBILITY_TOKEN;
4853 if (!callingThreadHasUnscopedSurfaceFlingerAccess(usePermissionCache)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004854 IPCThreadState* ipc = IPCThreadState::self();
4855 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4856 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004857 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004858 }
Robert Carr1db73f62016-12-21 12:58:51 -08004859 return OK;
4860 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004861 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004862 IPCThreadState* ipc = IPCThreadState::self();
4863 const int pid = ipc->getCallingPid();
4864 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004865 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4866 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004867 return PERMISSION_DENIED;
4868 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004869 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004870 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004871 // Used by apps to hook Choreographer to SurfaceFlinger.
4872 case CREATE_DISPLAY_EVENT_CONNECTION:
4873 // The following calls are currently used by clients that do not
4874 // request necessary permissions. However, they do not expose any secret
4875 // information, so it is OK to pass them.
4876 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004877 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004878 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004879 case GET_PHYSICAL_DISPLAY_IDS:
4880 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004881 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004882 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004883 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004884 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004885 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004886 case GET_DISPLAY_STATS:
4887 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4888 // Calling setTransactionState is safe, because you need to have been
4889 // granted a reference to Client* and Handle* to do anything with it.
4890 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004891 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004892 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004893 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004894 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004895 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004896 // setFrameRate() is deliberately available for apps to call without any
4897 // special permissions.
4898 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004899 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4900 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004901 return OK;
4902 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004903 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004904 case CAPTURE_SCREEN:
4905 case ADD_REGION_SAMPLING_LISTENER:
4906 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004907 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004908 IPCThreadState* ipc = IPCThreadState::self();
4909 const int pid = ipc->getCallingPid();
4910 const int uid = ipc->getCallingUid();
4911 if ((uid != AID_GRAPHICS) &&
4912 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4913 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4914 return PERMISSION_DENIED;
4915 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004916 return OK;
4917 }
chaviw93df2ea2019-04-30 16:45:12 -07004918 case CAPTURE_SCREEN_BY_ID: {
4919 IPCThreadState* ipc = IPCThreadState::self();
4920 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004921 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004922 return OK;
4923 }
4924 return PERMISSION_DENIED;
4925 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004926 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004927
4928 // These codes are used for the IBinder protocol to either interrogate the recipient
4929 // side of the transaction for its canonical interface descriptor or to dump its state.
4930 // We let them pass by default.
4931 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4932 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4933 code == IBinder::SYSPROPS_TRANSACTION) {
4934 return OK;
4935 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004936 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004937 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004938 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004939 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4940 return OK;
4941 }
4942 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4943 return PERMISSION_DENIED;
4944#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004945}
4946
Ana Krulec13be8ad2018-08-21 02:43:56 +00004947status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4948 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004949 status_t credentialCheck = CheckTransactCodeCredentials(code);
4950 if (credentialCheck != OK) {
4951 return credentialCheck;
4952 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004953
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004954 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4955 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004956 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004957 IPCThreadState* ipc = IPCThreadState::self();
4958 const int uid = ipc->getCallingUid();
4959 if (CC_UNLIKELY(uid != AID_SYSTEM
4960 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004961 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004962 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004963 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004964 return PERMISSION_DENIED;
4965 }
4966 int n;
4967 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004968 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004969 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004970 return NO_ERROR;
4971 case 1002: // SHOW_UPDATES
4972 n = data.readInt32();
4973 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004974 invalidateHwcGeometry();
4975 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004976 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004977 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004978 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004979 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004980 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004981 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004982 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004983 setTransactionFlags(
4984 eTransactionNeeded|
4985 eDisplayTransactionNeeded|
4986 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004987 return NO_ERROR;
4988 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004989 case 1006:{ // send empty update
4990 signalRefresh();
4991 return NO_ERROR;
4992 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004993 case 1008: // toggle use of hw composer
4994 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004995 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004996 invalidateHwcGeometry();
4997 repaintEverything();
4998 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004999 case 1009: // toggle use of transform hint
5000 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005001 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07005002 invalidateHwcGeometry();
5003 repaintEverything();
5004 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005005 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07005006 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005007 reply->writeInt32(0);
5008 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07005009 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08005010 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005011 return NO_ERROR;
5012 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005013 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07005014 if (!display) {
5015 return NAME_NOT_FOUND;
5016 }
5017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005018 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07005019 return NO_ERROR;
5020 }
5021 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005022 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005023 // daltonize
5024 n = data.readInt32();
5025 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005026 case 1:
5027 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
5028 break;
5029 case 2:
5030 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
5031 break;
5032 case 3:
5033 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
5034 break;
5035 default:
5036 mDaltonizer.setType(ColorBlindnessType::None);
5037 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07005038 }
5039 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005040 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005041 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005042 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07005043 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07005044
5045 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005046 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005047 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005048 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005049 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07005050 // apply a color matrix
5051 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005052 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07005053 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07005054 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005055 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005056 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07005057 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005058 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07005059 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07005060 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005061 }
Romain Guy88d37dd2017-05-26 17:57:05 -07005062
5063 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
5064 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07005065 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07005066 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
5067 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
5068 }
5069
Chia-I Wu28f320b2018-05-03 11:02:56 -07005070 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07005071 return NO_ERROR;
5072 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07005073 case 1016: { // Unused.
5074 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07005075 }
Dan Stozaee44edd2015-03-23 15:50:23 -07005076 case 1017: {
5077 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005078 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07005079 return NO_ERROR;
5080 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005081 case 1018: { // Modify Choreographer's phase offset
5082 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005083 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005084 return NO_ERROR;
5085 }
5086 case 1019: { // Modify SurfaceFlinger's phase offset
5087 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08005088 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07005089 return NO_ERROR;
5090 }
Irvel468051e2016-06-13 16:44:44 -07005091 case 1020: { // Layer updates interceptor
5092 n = data.readInt32();
5093 if (n) {
5094 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005095 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07005096 }
5097 else{
5098 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005099 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005100 }
5101 return NO_ERROR;
5102 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005103 case 1021: { // Disable HWC virtual displays
5104 n = data.readInt32();
5105 mUseHwcVirtualDisplays = !n;
5106 return NO_ERROR;
5107 }
Romain Guy0147a172017-06-01 13:53:56 -07005108 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005109 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005110 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005111
Chia-I Wu28f320b2018-05-03 11:02:56 -07005112 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005113 return NO_ERROR;
5114 }
Romain Guy54f154a2017-10-24 21:40:32 +01005115 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005116 int32_t colorMode;
5117
Chia-I Wu0d711262018-05-21 15:19:35 -07005118 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005119 if (data.readInt32(&colorMode) == NO_ERROR) {
5120 mForceColorMode = static_cast<ColorMode>(colorMode);
5121 }
Romain Guy54f154a2017-10-24 21:40:32 +01005122 invalidateHwcGeometry();
5123 repaintEverything();
5124 return NO_ERROR;
5125 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005126 // Deprecate, use 1030 to check whether the device is color managed.
5127 case 1024: {
5128 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005129 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005130 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005131 n = data.readInt32();
5132 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005133 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005134 Mutex::Autolock lock(mStateLock);
5135 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005136 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005137 reply->writeInt32(NO_ERROR);
5138 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005139 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005140 bool writeFile = false;
5141 {
5142 Mutex::Autolock lock(mStateLock);
5143 mTracingEnabledChanged = true;
5144 writeFile = mTracing.disable();
5145 }
5146
5147 if (writeFile) {
5148 reply->writeInt32(mTracing.writeToFile());
5149 } else {
5150 reply->writeInt32(NO_ERROR);
5151 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005152 }
5153 return NO_ERROR;
5154 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005155 case 1026: { // Get layer tracing status
5156 reply->writeBool(mTracing.isEnabled());
5157 return NO_ERROR;
5158 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005159 // Is a DisplayColorSetting supported?
5160 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005161 const auto display = getDefaultDisplayDevice();
5162 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005163 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005164 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005165
5166 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5167 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005168 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005169 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005170 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005171 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005172 reply->writeBool(true);
5173 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005174 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005175 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005176 break;
5177 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005178 reply->writeBool(
5179 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005180 break;
5181 }
5182 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005183 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005184 // Is VrFlinger active?
5185 case 1028: {
5186 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005187 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005188 return NO_ERROR;
5189 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005190 // Set buffer size for SF tracing (value in KB)
5191 case 1029: {
5192 n = data.readInt32();
5193 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5194 ALOGW("Invalid buffer size: %d KB", n);
5195 reply->writeInt32(BAD_VALUE);
5196 return BAD_VALUE;
5197 }
5198
5199 ALOGD("Updating trace buffer to %d KB", n);
5200 mTracing.setBufferSize(n * 1024);
5201 reply->writeInt32(NO_ERROR);
5202 return NO_ERROR;
5203 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005204 // Is device color managed?
5205 case 1030: {
5206 reply->writeBool(useColorManagement);
5207 return NO_ERROR;
5208 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005209 // Override default composition data space
5210 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5211 // && adb shell stop zygote && adb shell start zygote
5212 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5213 // adb shell stop zygote && adb shell start zygote
5214 case 1031: {
5215 Mutex::Autolock _l(mStateLock);
5216 n = data.readInt32();
5217 if (n) {
5218 n = data.readInt32();
5219 if (n) {
5220 Dataspace dataspace = static_cast<Dataspace>(n);
5221 if (!validateCompositionDataspace(dataspace)) {
5222 return BAD_VALUE;
5223 }
5224 mDefaultCompositionDataspace = dataspace;
5225 }
5226 n = data.readInt32();
5227 if (n) {
5228 Dataspace dataspace = static_cast<Dataspace>(n);
5229 if (!validateCompositionDataspace(dataspace)) {
5230 return BAD_VALUE;
5231 }
5232 mWideColorGamutCompositionDataspace = dataspace;
5233 }
5234 } else {
5235 // restore composition data space.
5236 mDefaultCompositionDataspace = defaultCompositionDataspace;
5237 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5238 }
5239 return NO_ERROR;
5240 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005241 // Set trace flags
5242 case 1033: {
5243 n = data.readUint32();
5244 ALOGD("Updating trace flags to 0x%x", n);
5245 mTracing.setTraceFlags(n);
5246 reply->writeInt32(NO_ERROR);
5247 return NO_ERROR;
5248 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005249 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005250 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005251 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005252 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005253 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005254 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005255 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005256 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005257 } else {
5258 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005259 }
5260 return NO_ERROR;
5261 }
Ady Abraham34392f72019-04-10 11:29:27 -07005262 case 1035: {
5263 n = data.readInt32();
5264 mDebugDisplayConfigSetByBackdoor = false;
5265 if (n >= 0) {
5266 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005267 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005268 if (result != NO_ERROR) {
5269 return result;
5270 }
5271 mDebugDisplayConfigSetByBackdoor = true;
5272 }
5273 return NO_ERROR;
5274 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005275 }
5276 }
5277 return err;
5278}
5279
Steven Thomas6d8110b2017-08-31 18:24:21 -07005280void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005281 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005282 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005283}
5284
Ana Krulec7d1d6832018-12-27 11:10:09 -08005285void SurfaceFlinger::repaintEverythingForHWC() {
5286 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005287 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005288 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005289}
5290
Ady Abrahama09852a2020-02-20 14:23:42 -08005291void SurfaceFlinger::kernelTimerChanged(bool expired) {
5292 static bool updateOverlay =
5293 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5294 if (!updateOverlay || !mRefreshRateOverlay) return;
5295
5296 // Update the overlay on the main thread to avoid race conditions with
5297 // mRefreshRateConfigs->getCurrentRefreshRate()
5298 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5299 if (mRefreshRateOverlay) {
5300 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5301 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005302 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005303 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5304 if (mDesiredActiveConfigChanged) {
5305 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5306 mDesiredActiveConfig.configId);
5307 }
5308
5309 return mRefreshRateConfigs->getCurrentRefreshRate();
5310 }();
5311 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5312
5313 if (current != min) {
5314 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5315 mEventQueue->invalidate();
5316 }
5317 }
5318 }));
5319}
5320
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005321// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5322class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005323public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005324 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5325 ~WindowDisconnector() {
5326 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005327 }
5328
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005329private:
5330 ANativeWindow* mWindow;
5331 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005332};
5333
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005334status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005335 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005336 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5337 const Rect& sourceCrop, uint32_t reqWidth,
5338 uint32_t reqHeight, bool useIdentityTransform,
5339 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005340 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005341
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005342 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005343
Dominik Laskowski718f9602019-11-09 20:01:35 -08005344 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5345 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5346 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5347 renderAreaRotation = ui::Transform::ROT_0;
5348 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005349
Chia-I Wu20261cb2018-08-23 12:55:44 -07005350 sp<DisplayDevice> display;
5351 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005352 Mutex::Autolock lock(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005353
Chia-I Wu20261cb2018-08-23 12:55:44 -07005354 display = getDisplayDeviceLocked(displayToken);
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005355 if (!display) return NAME_NOT_FOUND;
Chia-I Wu20261cb2018-08-23 12:55:44 -07005356
Chia-I Wucb023152018-08-28 12:57:23 -07005357 // set the requested width/height to the logical display viewport size
5358 // by default
5359 if (reqWidth == 0 || reqHeight == 0) {
5360 reqWidth = uint32_t(display->getViewport().width());
5361 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005362 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005363 }
5364
Peiyong Lin0e003c92018-09-17 11:09:51 -07005365 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005366 renderAreaRotation, captureSecureLayers);
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005367 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5368 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005369 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005370 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005371}
5372
chaviw93df2ea2019-04-30 16:45:12 -07005373static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5374 switch (colorMode) {
5375 case ColorMode::DISPLAY_P3:
5376 case ColorMode::BT2100_PQ:
5377 case ColorMode::BT2100_HLG:
5378 case ColorMode::DISPLAY_BT2020:
5379 return Dataspace::DISPLAY_P3;
5380 default:
5381 return Dataspace::V0_SRGB;
5382 }
5383}
5384
Martin Liu4a322352020-03-24 21:30:38 +08005385status_t SurfaceFlinger::setSchedFifo(bool enabled) {
5386 static constexpr int kFifoPriority = 2;
5387 static constexpr int kOtherPriority = 0;
5388
5389 struct sched_param param = {0};
5390 int sched_policy;
5391 if (enabled) {
5392 sched_policy = SCHED_FIFO;
5393 param.sched_priority = kFifoPriority;
5394 } else {
5395 sched_policy = SCHED_OTHER;
5396 param.sched_priority = kOtherPriority;
5397 }
5398
5399 if (sched_setscheduler(0, sched_policy, &param) != 0) {
5400 return -errno;
5401 }
5402 return NO_ERROR;
5403}
5404
chaviw93df2ea2019-04-30 16:45:12 -07005405const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5406 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5407 if (displayToken) {
5408 return getDisplayDeviceLocked(displayToken);
5409 }
5410 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5411 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005412 return getDisplayByLayerStack(displayOrLayerStack);
5413}
5414
5415const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005416 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005417 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005418 return display;
5419 }
5420 }
5421 return nullptr;
5422}
5423
5424status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5425 sp<GraphicBuffer>* outBuffer) {
5426 sp<DisplayDevice> display;
5427 uint32_t width;
5428 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005429 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005430 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005431 Mutex::Autolock lock(mStateLock);
chaviw93df2ea2019-04-30 16:45:12 -07005432 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5433 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005434 return NAME_NOT_FOUND;
chaviw93df2ea2019-04-30 16:45:12 -07005435 }
5436
5437 width = uint32_t(display->getViewport().width());
5438 height = uint32_t(display->getViewport().height());
5439
Dominik Laskowski718f9602019-11-09 20:01:35 -08005440 const auto orientation = display->getOrientation();
5441 captureOrientation = ui::Transform::toRotationFlags(orientation);
5442
5443 switch (captureOrientation) {
5444 case ui::Transform::ROT_90:
5445 captureOrientation = ui::Transform::ROT_270;
5446 break;
5447
5448 case ui::Transform::ROT_270:
5449 captureOrientation = ui::Transform::ROT_90;
5450 break;
5451
5452 case ui::Transform::ROT_INVALID:
5453 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5454 captureOrientation = ui::Transform::ROT_0;
5455 break;
5456
5457 default:
5458 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005459 }
chaviw93df2ea2019-04-30 16:45:12 -07005460 *outDataspace =
5461 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5462 }
5463
5464 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5465 false /* captureSecureLayers */);
5466
5467 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5468 std::placeholders::_1);
5469 bool ignored = false;
5470 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5471 false /* useIdentityTransform */,
5472 ignored /* outCapturedSecureLayers */);
5473}
5474
Robert Carr866455f2019-04-02 16:28:26 -07005475status_t SurfaceFlinger::captureLayers(
5476 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5477 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5478 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5479 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005480 ATRACE_CALL();
5481
5482 class LayerRenderArea : public RenderArea {
5483 public:
Robert Carr578038f2018-03-09 12:25:24 -08005484 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005485 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005486 bool childrenOnly, const Rect& displayViewport)
5487 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005488 mLayer(layer),
5489 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005490 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005491 mFlinger(flinger),
5492 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005493 const ui::Transform& getTransform() const override { return mTransform; }
Alec Mouri5a6d8572020-03-23 23:56:15 -07005494 Rect getBounds() const override { return mLayer->getBufferSize(mLayer->getDrawingState()); }
Marissa Wall61c58622018-07-18 10:12:20 -07005495 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005496 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005497 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005498 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005499 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005500 }
chaviwa76b2712017-09-20 12:02:26 -07005501 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005502 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005503 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005504 Rect getSourceCrop() const override {
5505 if (mCrop.isEmpty()) {
5506 return getBounds();
5507 } else {
5508 return mCrop;
5509 }
5510 }
Robert Carr578038f2018-03-09 12:25:24 -08005511 class ReparentForDrawing {
5512 public:
5513 const sp<Layer>& oldParent;
5514 const sp<Layer>& newParent;
5515
Vishnu Nair4351ad52019-02-11 14:13:02 -08005516 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5517 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005518 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005519 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005520 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5521 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005522 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005523 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005524 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005525 };
5526
5527 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005528 const Rect sourceCrop = getSourceCrop();
5529 // no need to check rotation because there is none
5530 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5531 sourceCrop.height() != getReqHeight();
5532
Robert Carr578038f2018-03-09 12:25:24 -08005533 if (!mChildrenOnly) {
5534 mTransform = mLayer->getTransform().inverse();
5535 drawLayers();
5536 } else {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005537 uint32_t w = static_cast<uint32_t>(getWidth());
5538 uint32_t h = static_cast<uint32_t>(getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005539 // In the "childrenOnly" case we reparent the children to a screenshot
5540 // layer which has no properties set and which does not draw.
5541 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005542 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5543 "Screenshot Parent"s, w, h, 0,
5544 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005545
Vishnu Nair4351ad52019-02-11 14:13:02 -08005546 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005547 drawLayers();
5548 }
5549 }
chaviwa76b2712017-09-20 12:02:26 -07005550
chaviwa76b2712017-09-20 12:02:26 -07005551 private:
chaviw7206d492017-11-10 16:16:12 -08005552 const sp<Layer> mLayer;
5553 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005554
Peiyong Linefefaac2018-08-17 12:27:51 -07005555 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005556 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005557
5558 SurfaceFlinger* mFlinger;
5559 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005560 };
5561
Robert Carrc0df3122019-04-11 13:18:21 -07005562 int reqWidth = 0;
5563 int reqHeight = 0;
5564 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005565 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005566 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005567 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005568 {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005569 Mutex::Autolock lock(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005570
Alec Mouri9a02eda2020-04-21 17:39:34 -07005571 parent = fromHandleLocked(layerHandleBinder).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005572 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5573 ALOGE("captureLayers called with an invalid or removed parent");
5574 return NAME_NOT_FOUND;
5575 }
5576
5577 const int uid = IPCThreadState::self()->getCallingUid();
5578 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5579 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5580 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5581 return PERMISSION_DENIED;
5582 }
5583
Vishnu Nairefc42e22019-12-03 17:36:12 -08005584 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005585 if (sourceCrop.width() <= 0) {
5586 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005587 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005588 }
5589
5590 if (sourceCrop.height() <= 0) {
5591 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005592 crop.bottom = parentSourceBounds.getHeight();
5593 }
5594
5595 if (crop.isEmpty() || frameScale <= 0.0f) {
5596 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5597 // crop was not specified, or an invalid frame scale was provided.
5598 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005599 }
5600 reqWidth = crop.width() * frameScale;
5601 reqHeight = crop.height() * frameScale;
5602
5603 for (const auto& handle : excludeHandles) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07005604 sp<Layer> excludeLayer = fromHandleLocked(handle).promote();
Robert Carrc0df3122019-04-11 13:18:21 -07005605 if (excludeLayer != nullptr) {
5606 excludeLayers.emplace(excludeLayer);
5607 } else {
5608 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5609 return NAME_NOT_FOUND;
5610 }
5611 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005612
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005613 const auto display = getDisplayByLayerStack(parent->getLayerStack());
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005614 if (!display) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07005615 return NAME_NOT_FOUND;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005616 }
5617
5618 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005619 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005620
Chia-I Wu20261cb2018-08-23 12:55:44 -07005621 // really small crop or frameScale
5622 if (reqWidth <= 0) {
5623 reqWidth = 1;
5624 }
5625 if (reqHeight <= 0) {
5626 reqHeight = 1;
5627 }
5628
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005629 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5630 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005631 auto traverseLayers = [parent, childrenOnly,
5632 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005633 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5634 if (!layer->isVisible()) {
5635 return;
Robert Carr578038f2018-03-09 12:25:24 -08005636 } else if (childrenOnly && layer == parent.get()) {
5637 return;
chaviwa76b2712017-09-20 12:02:26 -07005638 }
Robert Carr866455f2019-04-02 16:28:26 -07005639
5640 sp<Layer> p = layer;
5641 while (p != nullptr) {
5642 if (excludeLayers.count(p) != 0) {
5643 return;
5644 }
5645 p = p->getParent();
5646 }
5647
chaviwa76b2712017-09-20 12:02:26 -07005648 visitor(layer);
5649 });
5650 };
Robert Carr108b2c72019-04-02 16:32:58 -07005651
5652 bool outCapturedSecureLayers = false;
5653 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5654 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005655}
5656
5657status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5658 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005659 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005660 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005661 bool useIdentityTransform,
5662 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005663 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005664
Peiyong Lin0e003c92018-09-17 11:09:51 -07005665 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005666 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5667 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005668 *outBuffer =
5669 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5670 static_cast<android_pixel_format>(reqPixelFormat), 1,
5671 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005672
Robert Carr108b2c72019-04-02 16:32:58 -07005673 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5674 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005675}
5676
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005677status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5678 TraverseLayersFunction traverseLayers,
5679 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005680 bool useIdentityTransform,
5681 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005682 // This mutex protects syncFd and captureResult for communication of the return values from the
5683 // main thread back to this Binder thread
5684 std::mutex captureMutex;
5685 std::condition_variable captureCondition;
5686 std::unique_lock<std::mutex> captureLock(captureMutex);
5687 int syncFd = -1;
5688 std::optional<status_t> captureResult;
5689
Robert Carr03480e22018-01-04 16:02:06 -08005690 const int uid = IPCThreadState::self()->getCallingUid();
5691 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5692
Dominik Laskowski8c001672018-05-30 16:52:06 -07005693 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005694 // If there is a refresh pending, bug out early and tell the binder thread to try again
5695 // after the refresh.
5696 if (mRefreshPending) {
5697 ATRACE_NAME("Skipping screenshot for now");
5698 std::unique_lock<std::mutex> captureLock(captureMutex);
5699 captureResult = std::make_optional<status_t>(EAGAIN);
5700 captureCondition.notify_one();
5701 return;
5702 }
5703
5704 status_t result = NO_ERROR;
5705 int fd = -1;
5706 {
5707 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005708 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005709 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005710 useIdentityTransform, forSystem, &fd,
5711 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005712 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005713 }
5714
5715 {
5716 std::unique_lock<std::mutex> captureLock(captureMutex);
5717 syncFd = fd;
5718 captureResult = std::make_optional<status_t>(result);
5719 captureCondition.notify_one();
5720 }
5721 });
5722
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005723 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005724 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005725 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005726 while (*captureResult == EAGAIN) {
5727 captureResult.reset();
5728 result = postMessageAsync(message);
5729 if (result != NO_ERROR) {
5730 return result;
5731 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005732 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005733 }
5734 result = *captureResult;
5735 }
5736
5737 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005738 sync_wait(syncFd, -1);
5739 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005740 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005741
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005742 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005743}
5744
chaviwa76b2712017-09-20 12:02:26 -07005745void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005746 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005747 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5748 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005749 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005750
chaviwa76b2712017-09-20 12:02:26 -07005751 const auto reqWidth = renderArea.getReqWidth();
5752 const auto reqHeight = renderArea.getReqHeight();
Alec Mouriadb75f42019-03-28 21:42:24 -07005753 const auto sourceCrop = renderArea.getSourceCrop();
Alec Mouri5a6d8572020-03-23 23:56:15 -07005754 const auto transform = renderArea.getTransform();
5755 const auto rotation = renderArea.getRotationFlags();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005756 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005757
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005758 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005759 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005760
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005761 // assume that bounds are never offset, and that they are the same as the
5762 // buffer bounds.
5763 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005764 clientCompositionDisplay.clip = sourceCrop;
Alec Mouri5a6d8572020-03-23 23:56:15 -07005765 clientCompositionDisplay.orientation = rotation;
Alec Mouriadb75f42019-03-28 21:42:24 -07005766
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005767 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5768 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005769
chaviw50da5042018-04-09 13:49:37 -07005770 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005771
Vishnu Nair9b079a22020-01-21 14:36:08 -08005772 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005773 fillLayer.source.buffer.buffer = nullptr;
5774 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
Alec Mouri5a6d8572020-03-23 23:56:15 -07005775 fillLayer.geometry.boundaries =
5776 FloatRect(sourceCrop.left, sourceCrop.top, sourceCrop.right, sourceCrop.bottom);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005777 fillLayer.alpha = half(alpha);
5778 clientCompositionLayers.push_back(fillLayer);
5779
Yichi Chen40773d92020-04-01 10:10:18 +08005780 std::vector<Layer*> renderedLayers;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005781 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005782 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005783 const bool supportProtectedContent = false;
5784 Region clip(renderArea.getBounds());
5785 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5786 clip,
5787 useIdentityTransform,
Alec Mouri5a6d8572020-03-23 23:56:15 -07005788 layer->needsFilteringForScreenshots(renderArea.getDisplayDevice(), transform) ||
5789 renderArea.needsFiltering(),
Lloyd Piquef16688f2019-02-19 17:47:57 -08005790 renderArea.isSecure(),
5791 supportProtectedContent,
5792 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005793 displayViewport,
5794 clientCompositionDisplay.outputDataspace,
5795 true, /* realContentIsVisible */
5796 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005797 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005798 std::vector<compositionengine::LayerFE::LayerSettings> results =
5799 layer->prepareClientCompositionList(targetSettings);
Yichi Chen40773d92020-04-01 10:10:18 +08005800 if (results.size() > 0) {
Alec Mouri5a6d8572020-03-23 23:56:15 -07005801 for (auto& settings : results) {
5802 settings.geometry.positionTransform =
5803 transform.asMatrix4() * settings.geometry.positionTransform;
5804 }
Yichi Chen40773d92020-04-01 10:10:18 +08005805 clientCompositionLayers.insert(clientCompositionLayers.end(),
5806 std::make_move_iterator(results.begin()),
5807 std::make_move_iterator(results.end()));
5808 renderedLayers.push_back(layer);
5809 }
chaviwa76b2712017-09-20 12:02:26 -07005810 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005811
Yichi Chen40773d92020-04-01 10:10:18 +08005812 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers(
5813 clientCompositionLayers.size());
Vishnu Nair9b079a22020-01-21 14:36:08 -08005814 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
Yichi Chen40773d92020-04-01 10:10:18 +08005815 clientCompositionLayerPointers.begin(),
5816 std::pointer_traits<renderengine::LayerSettings*>::pointer_to);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005817
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005818 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005819 // Use an empty fence for the buffer fence, since we just created the buffer so
5820 // there is no need for synchronization with the GPU.
5821 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005822 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005823 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005824 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005825 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005826
5827 *outSyncFd = drawFence.release();
Yichi Chen40773d92020-04-01 10:10:18 +08005828
5829 if (*outSyncFd >= 0) {
5830 sp<Fence> releaseFence = new Fence(dup(*outSyncFd));
5831 for (auto* layer : renderedLayers) {
5832 layer->onLayerDisplayed(releaseFence);
5833 }
5834 }
Mathias Agopian180f10d2013-04-10 22:55:41 -07005835}
5836
chaviwa76b2712017-09-20 12:02:26 -07005837status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5838 TraverseLayersFunction traverseLayers,
5839 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005840 bool useIdentityTransform, bool forSystem,
5841 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005842 ATRACE_CALL();
5843
chaviwa76b2712017-09-20 12:02:26 -07005844 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005845 outCapturedSecureLayers =
5846 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005847 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005848
Robert Carr03480e22018-01-04 16:02:06 -08005849 // We allow the system server to take screenshots of secure layers for
5850 // use in situations like the Screen-rotation animation and place
5851 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005852 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005853 ALOGW("FB is protected: PERMISSION_DENIED");
5854 return PERMISSION_DENIED;
5855 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005856 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005857 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005858}
5859
chaviw95ef3c42019-02-14 10:55:09 -08005860void SurfaceFlinger::setInputWindowsFinished() {
5861 Mutex::Autolock _l(mStateLock);
5862
5863 mPendingSyncInputWindows = false;
Rob Carr9a2cc992020-03-06 12:44:45 -08005864
chaviw95ef3c42019-02-14 10:55:09 -08005865 mTransactionCV.broadcast();
5866}
chaviw5f21a5e2019-02-14 10:00:34 -08005867
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005868// ---------------------------------------------------------------------------
5869
Edgar Arriaga844fa672020-01-16 14:21:42 -08005870void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5871 layersSortedByZ.traverse(visitor);
5872}
5873
Dan Stoza412903f2017-04-27 13:42:17 -07005874void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5875 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005876}
5877
Dan Stoza412903f2017-04-27 13:42:17 -07005878void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5879 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005880}
5881
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005882void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005883 const LayerVector::Visitor& visitor) {
5884 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005885 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005886 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005887 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005888 continue;
5889 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005890 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005891 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005892 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005893 return;
5894 }
chaviwa76b2712017-09-20 12:02:26 -07005895 if (!layer->isVisible()) {
5896 return;
5897 }
5898 visitor(layer);
5899 });
5900 }
5901}
5902
Steven Thomasd4071902020-03-24 16:02:53 -07005903status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(
5904 const sp<DisplayDevice>& display,
5905 const std::optional<scheduler::RefreshRateConfigs::Policy>& policy, bool overridePolicy) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005906 Mutex::Autolock lock(mStateLock);
5907
Steven Thomasd4071902020-03-24 16:02:53 -07005908 LOG_ALWAYS_FATAL_IF(!display->isPrimary() && overridePolicy,
5909 "Can only set override policy on the primary display");
5910 LOG_ALWAYS_FATAL_IF(!policy && !overridePolicy, "Can only clear the override policy");
5911
Dominik Laskowski22488f62019-03-28 09:53:04 -07005912 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005913 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5914 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5915 // it should go thru setDesiredActiveConfig, similar to primary display.
5916 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5917 const auto displayId = display->getId();
5918 LOG_ALWAYS_FATAL_IF(!displayId);
5919
5920 HWC2::VsyncPeriodChangeConstraints constraints;
5921 constraints.desiredTimeNanos = systemTime();
5922 constraints.seamlessRequired = false;
5923
5924 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Steven Thomasd4071902020-03-24 16:02:53 -07005925 if (getHwComposer().setActiveConfigWithConstraints(*displayId,
5926 policy->defaultConfig.value(),
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005927 constraints, &timeline) < 0) {
5928 return BAD_VALUE;
5929 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005930 if (timeline.refreshRequired) {
5931 repaintEverythingForHWC();
5932 }
5933
Steven Thomasd4071902020-03-24 16:02:53 -07005934 display->setActiveConfig(policy->defaultConfig);
5935 const nsecs_t vsyncPeriod = getHwComposer()
5936 .getConfigs(*displayId)[policy->defaultConfig.value()]
5937 ->getVsyncPeriod();
5938 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5939 policy->defaultConfig, vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005940 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005941 }
5942
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005943 if (mDebugDisplayConfigSetByBackdoor) {
5944 // ignore this request as config is overridden by backdoor
5945 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005946 }
5947
Steven Thomasd4071902020-03-24 16:02:53 -07005948 status_t setPolicyResult = overridePolicy
5949 ? mRefreshRateConfigs->setOverridePolicy(policy)
5950 : mRefreshRateConfigs->setDisplayManagerPolicy(*policy);
5951 if (setPolicyResult < 0) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005952 return BAD_VALUE;
5953 }
Steven Thomasd4071902020-03-24 16:02:53 -07005954 if (setPolicyResult == scheduler::RefreshRateConfigs::CURRENT_POLICY_UNCHANGED) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005955 return NO_ERROR;
5956 }
Steven Thomasd4071902020-03-24 16:02:53 -07005957 scheduler::RefreshRateConfigs::Policy currentPolicy = mRefreshRateConfigs->getCurrentPolicy();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005958
5959 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
Steven Thomasd4071902020-03-24 16:02:53 -07005960 currentPolicy.defaultConfig.value(), currentPolicy.minRefreshRate,
5961 currentPolicy.maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005962
5963 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5964 // that listeners that care about a change in allowed configs can get the notification.
5965 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005966 const nsecs_t vsyncPeriod =
Ady Abrahamabc27602020-04-08 17:20:29 -07005967 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig())
5968 .getVsyncPeriod();
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005969 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005970 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005971
Ana Krulec3f6a2062020-01-23 15:48:01 -08005972 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005973 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005974 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5975 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
Steven Thomasd4071902020-03-24 16:02:53 -07005976 : mRefreshRateConfigs->getRefreshRateFromConfigId(currentPolicy.defaultConfig);
Ana Krulec3f6a2062020-01-23 15:48:01 -08005977 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
Ady Abrahamabc27602020-04-08 17:20:29 -07005978 preferredRefreshRate.getConfigId().value(), preferredRefreshRate.getName().c_str());
Ana Krulec3f6a2062020-01-23 15:48:01 -08005979
Ady Abrahamabc27602020-04-08 17:20:29 -07005980 if (isDisplayConfigAllowed(preferredRefreshRate.getConfigId())) {
5981 ALOGV("switching to Scheduler preferred config %d",
5982 preferredRefreshRate.getConfigId().value());
5983 setDesiredActiveConfig(
5984 {preferredRefreshRate.getConfigId(), Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005985 } else {
Ady Abrahamabc27602020-04-08 17:20:29 -07005986 LOG_ALWAYS_FATAL("Desired config not allowed: %d",
5987 preferredRefreshRate.getConfigId().value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005988 }
5989
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005990 return NO_ERROR;
5991}
5992
Ana Krulec0782b882019-10-15 17:34:54 -07005993status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005994 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005995 float maxRefreshRate) {
5996 ATRACE_CALL();
5997
5998 if (!displayToken) {
5999 return BAD_VALUE;
6000 }
6001
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006002 status_t result = NAME_NOT_FOUND;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006003
Ana Krulec234bb162019-11-10 22:55:55 +01006004 postMessageSync(new LambdaMessage([&]() {
6005 const auto display = getDisplayDeviceLocked(displayToken);
6006 if (!display) {
6007 ALOGE("Attempt to set desired display configs for invalid display token %p",
6008 displayToken.get());
6009 } else if (display->isVirtual()) {
6010 ALOGW("Attempt to set desired display configs for virtual display");
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006011 result = INVALID_OPERATION;
Ana Krulec234bb162019-11-10 22:55:55 +01006012 } else {
Steven Thomasd4071902020-03-24 16:02:53 -07006013 result = setDesiredDisplayConfigSpecsInternal(display,
6014 scheduler::RefreshRateConfigs::
6015 Policy{HwcConfigIndexType(
6016 defaultConfig),
6017 minRefreshRate,
6018 maxRefreshRate},
6019 /*overridePolicy=*/false);
Ana Krulec234bb162019-11-10 22:55:55 +01006020 }
6021 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006022
6023 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01006024}
6025
6026status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006027 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01006028 float* outMinRefreshRate,
6029 float* outMaxRefreshRate) {
6030 ATRACE_CALL();
6031
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006032 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01006033 return BAD_VALUE;
6034 }
6035
6036 Mutex::Autolock lock(mStateLock);
6037 const auto display = getDisplayDeviceLocked(displayToken);
6038 if (!display) {
6039 return NAME_NOT_FOUND;
6040 }
6041
6042 if (display->isPrimary()) {
Steven Thomasd4071902020-03-24 16:02:53 -07006043 scheduler::RefreshRateConfigs::Policy policy =
6044 mRefreshRateConfigs->getDisplayManagerPolicy();
6045 *outDefaultConfig = policy.defaultConfig.value();
6046 *outMinRefreshRate = policy.minRefreshRate;
6047 *outMaxRefreshRate = policy.maxRefreshRate;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006048 return NO_ERROR;
6049 } else if (display->isVirtual()) {
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006050 return INVALID_OPERATION;
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006051 } else {
6052 const auto displayId = display->getId();
Dominik Laskowski470df5f2020-04-02 22:27:42 -07006053 LOG_FATAL_IF(!displayId);
6054
Ana Kruleced3a8cc2019-11-14 00:55:07 +01006055 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
6056 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
6057 *outMinRefreshRate = 1e9f / vsyncPeriod;
6058 *outMaxRefreshRate = 1e9f / vsyncPeriod;
6059 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01006060 }
Ana Krulec0782b882019-10-15 17:34:54 -07006061}
6062
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006063void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08006064 mFlinger->setInputWindowsFinished();
6065}
6066
Alec Mouri9a02eda2020-04-21 17:39:34 -07006067wp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
6068 Mutex::Autolock _l(mStateLock);
6069 return fromHandleLocked(handle);
6070}
6071
6072wp<Layer> SurfaceFlinger::fromHandleLocked(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08006073 BBinder* b = nullptr;
6074 if (handle) {
6075 b = handle->localBinder();
6076 }
Robert Carrc0df3122019-04-11 13:18:21 -07006077 if (b == nullptr) {
6078 return nullptr;
6079 }
6080 auto it = mLayersByLocalBinderToken.find(b);
6081 if (it != mLayersByLocalBinderToken.end()) {
Alec Mouri9a02eda2020-04-21 17:39:34 -07006082 return it->second;
Robert Carrc0df3122019-04-11 13:18:21 -07006083 }
6084 return nullptr;
6085}
6086
Dominik Laskowski75848362019-11-11 17:57:20 -08006087void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006088 mNumLayers++;
6089 mScheduler->registerLayer(layer);
6090}
6091
6092void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
6093 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08006094 removeFromOffscreenLayers(layer);
6095}
6096
6097// WARNING: ONLY CALL THIS FROM LAYER DTOR
6098// Here we add children in the current state to offscreen layers and remove the
6099// layer itself from the offscreen layer list. Since
6100// this is the dtor, it is safe to access the current state. This keeps us
6101// from dangling children layers such that they are not reachable from the
6102// Drawing state nor the offscreen layer list
6103// See b/141111965
6104void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6105 for (auto& child : layer->getCurrentChildren()) {
6106 mOffscreenLayers.emplace(child.get());
6107 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006108 mOffscreenLayers.erase(layer);
6109}
6110
Alec Mouri4545a8a2019-08-08 20:05:32 -07006111void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6112 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6113}
6114
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006115status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6116 float lightPosY, float lightPosZ,
6117 float lightRadius) {
6118 Mutex::Autolock _l(mStateLock);
6119 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6120 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6121 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6122 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6123 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6124
6125 // these values are overridden when calculating the shadow settings for a layer.
6126 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6127 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006128 return NO_ERROR;
6129}
6130
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006131const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6132 const {
6133 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6134 // on the work to remove the table in that bug rather than adding more to
6135 // it.
6136 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6137 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6138 // supported, and exposed via the
6139 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6140 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6141 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6142 };
6143 return genericLayerMetadataKeyMap;
6144}
6145
Steven Thomas62a4cf82020-01-31 12:04:03 -08006146status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6147 int8_t compatibility) {
6148 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6149 return BAD_VALUE;
6150 }
6151
Ady Abraham60e42ea2020-03-09 19:17:31 -07006152 postMessageAsync(new LambdaMessage([=]() NO_THREAD_SAFETY_ANALYSIS {
6153 Mutex::Autolock lock(mStateLock);
6154 if (authenticateSurfaceTextureLocked(surface)) {
6155 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6156 if (layer->setFrameRate(
6157 Layer::FrameRate(frameRate,
6158 Layer::FrameRate::convertCompatibility(compatibility)))) {
6159 setTransactionFlags(eTraversalNeeded);
6160 }
6161 } else {
6162 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6163 return BAD_VALUE;
Steven Thomas62a4cf82020-01-31 12:04:03 -08006164 }
Ady Abraham60e42ea2020-03-09 19:17:31 -07006165 return NO_ERROR;
6166 }));
6167
Steven Thomas62a4cf82020-01-31 12:04:03 -08006168 return NO_ERROR;
6169}
6170
Steven Thomasd4071902020-03-24 16:02:53 -07006171status_t SurfaceFlinger::acquireFrameRateFlexibilityToken(sp<IBinder>* outToken) {
6172 if (!outToken) {
6173 return BAD_VALUE;
6174 }
6175 status_t result = NO_ERROR;
6176 postMessageSync(new LambdaMessage([&]() {
6177 if (mFrameRateFlexibilityTokenCount == 0) {
6178 // |mStateLock| not needed as we are on the main thread
6179 const auto display = getDefaultDisplayDeviceLocked();
6180
6181 // This is a little racy, but not in a way that hurts anything. As we grab the
6182 // defaultConfig from the display manager policy, we could be setting a new display
6183 // manager policy, leaving us using a stale defaultConfig. The defaultConfig doesn't
6184 // matter for the override policy though, since we set allowGroupSwitching to true, so
6185 // it's not a problem.
6186 scheduler::RefreshRateConfigs::Policy overridePolicy;
6187 overridePolicy.defaultConfig =
6188 mRefreshRateConfigs->getDisplayManagerPolicy().defaultConfig;
6189 overridePolicy.allowGroupSwitching = true;
6190 result = setDesiredDisplayConfigSpecsInternal(display, overridePolicy,
6191 /*overridePolicy=*/true);
6192 }
6193
6194 if (result == NO_ERROR) {
6195 mFrameRateFlexibilityTokenCount++;
6196 // Handing out a reference to the SurfaceFlinger object, as we're doing in the line
6197 // below, is something to consider carefully. The lifetime of the
6198 // FrameRateFlexibilityToken isn't tied to SurfaceFlinger object lifetime, so if this
6199 // SurfaceFlinger object were to be destroyed while the token still exists, the token
6200 // destructor would be accessing a stale SurfaceFlinger reference, and crash. This is ok
6201 // in this case, for two reasons:
6202 // 1. Once SurfaceFlinger::run() is called by main_surfaceflinger.cpp, the only way
6203 // the program exits is via a crash. So we won't have a situation where the
6204 // SurfaceFlinger object is dead but the process is still up.
6205 // 2. The frame rate flexibility token is acquired/released only by CTS tests, so even
6206 // if condition 1 were changed, the problem would only show up when running CTS tests,
6207 // not on end user devices, so we could spot it and fix it without serious impact.
6208 *outToken = new FrameRateFlexibilityToken(
6209 [this]() { onFrameRateFlexibilityTokenReleased(); });
6210 ALOGD("Frame rate flexibility token acquired. count=%d",
6211 mFrameRateFlexibilityTokenCount);
6212 }
6213 }));
6214 return result;
6215}
6216
6217void SurfaceFlinger::onFrameRateFlexibilityTokenReleased() {
6218 postMessageAsync(new LambdaMessage([&]() {
6219 LOG_ALWAYS_FATAL_IF(mFrameRateFlexibilityTokenCount == 0,
6220 "Failed tracking frame rate flexibility tokens");
6221 mFrameRateFlexibilityTokenCount--;
6222 ALOGD("Frame rate flexibility token released. count=%d", mFrameRateFlexibilityTokenCount);
6223 if (mFrameRateFlexibilityTokenCount == 0) {
6224 // |mStateLock| not needed as we are on the main thread
6225 const auto display = getDefaultDisplayDeviceLocked();
6226 status_t result =
6227 setDesiredDisplayConfigSpecsInternal(display, {}, /*overridePolicy=*/true);
6228 LOG_ALWAYS_FATAL_IF(result < 0, "Failed releasing frame rate flexibility token");
6229 }
6230 }));
6231}
6232
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006233} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006234
Mathias Agopian3f844832013-08-07 21:24:32 -07006235#if defined(__gl_h_)
6236#error "don't include gl/gl.h in this file"
6237#endif
6238
6239#if defined(__gl2_h_)
6240#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006241#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006242
6243// TODO(b/129481165): remove the #pragma below and fix conversion issues
6244#pragma clang diagnostic pop // ignored "-Wconversion"