blob: ffb8ae925aecb7ce5f052c6a12da65f90f834c18 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -080017// TODO(b/129481165): remove the #pragma below and fix conversion issues
18#pragma clang diagnostic push
19#pragma clang diagnostic ignored "-Wconversion"
20
Alec Mourie7d1d4a2019-02-05 01:13:46 +000021//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080022#define ATRACE_TAG ATRACE_TAG_GRAPHICS
23
Alec Mouri989ddbe2020-02-06 09:26:19 -080024#include "SurfaceFlinger.h"
Dominik Laskowski83b88212018-12-11 13:34:06 -080025
Alec Mouri989ddbe2020-02-06 09:26:19 -080026#include <android/configuration.h>
27#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
28#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
29#include <android/hardware/configstore/1.1/types.h>
30#include <android/hardware/power/1.0/IPower.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080031#include <android/native_window.h>
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070032#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070034#include <binder/PermissionCache.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070035#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080036#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070037#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070038#include <compositionengine/DisplayColorProfile.h>
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -070039#include <compositionengine/DisplayCreationArgs.h>
Lloyd Piquede196652020-01-22 17:29:58 -080040#include <compositionengine/LayerFECompositionState.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080041#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070042#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070043#include <compositionengine/impl/OutputCompositionState.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080044#include <configstore/Utils.h>
45#include <cutils/compiler.h>
46#include <cutils/properties.h>
47#include <dlfcn.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080048#include <dvr/vr_flinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080049#include <errno.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070050#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070051#include <gui/DebugEGLImageTracker.h>
Andy McFadden4803b742012-09-24 19:07:20 -070052#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070053#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080054#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080055#include <gui/LayerDebugInfo.h>
Lloyd Pique4603f3c2020-02-11 12:06:56 -080056#include <gui/LayerMetadata.h>
Steven Thomas62a4cf82020-01-31 12:04:03 -080057#include <gui/LayerState.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080058#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070059#include <input/IInputFlinger.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080060#include <layerproto/LayerProtoParser.h>
61#include <log/log.h>
62#include <private/android_filesystem_config.h>
63#include <private/gui/SyncFeatures.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070064#include <renderengine/RenderEngine.h>
Alec Mouri989ddbe2020-02-06 09:26:19 -080065#include <statslog.h>
66#include <sys/types.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070067#include <ui/ColorSpace.h>
68#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080069#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <ui/DisplayInfo.h>
71#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080072#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070073#include <ui/GraphicBufferAllocator.h>
74#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070075#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080076#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070077#include <utils/String16.h>
78#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070079#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080080#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070081#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080082
Alec Mouri989ddbe2020-02-06 09:26:19 -080083#include <algorithm>
84#include <cinttypes>
85#include <cmath>
86#include <cstdint>
87#include <functional>
88#include <mutex>
89#include <optional>
90#include <unordered_map>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Robert Carr578038f2018-03-09 12:25:24 -080092#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070093#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070094#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020095#include "Client.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020096#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080097#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080098#include "DisplayDevice.h"
Steven Thomasb02664d2017-07-26 18:48:28 -070099#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -0700100#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700101#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700102#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700103#include "DisplayHardware/VirtualDisplaySurface.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800104#include "EffectLayer.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700105#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700106#include "FrameTracer/FrameTracer.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800107#include "Layer.h"
108#include "LayerVector.h"
109#include "MonitoredProducer.h"
110#include "NativeWindowSurface.h"
111#include "RefreshRateOverlay.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700112#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700113#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700114#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700115#include "Scheduler/EventControlThread.h"
116#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700117#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700118#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700119#include "Scheduler/Scheduler.h"
Alec Mouri989ddbe2020-02-06 09:26:19 -0800120#include "StartPropertySetThread.h"
121#include "SurfaceFlingerProperties.h"
122#include "SurfaceInterceptor.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800123#include "TimeStats/TimeStats.h"
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700124#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800125#include "android-base/stringprintf.h"
126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Steven Thomasb02664d2017-07-26 18:48:28 -0700143namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700144
145#pragma clang diagnostic push
146#pragma clang diagnostic error "-Wswitch-enum"
147
148bool isWideColorMode(const ColorMode colorMode) {
149 switch (colorMode) {
150 case ColorMode::DISPLAY_P3:
151 case ColorMode::ADOBE_RGB:
152 case ColorMode::DCI_P3:
153 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700154 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700155 case ColorMode::BT2100_PQ:
156 case ColorMode::BT2100_HLG:
157 return true;
158 case ColorMode::NATIVE:
159 case ColorMode::STANDARD_BT601_625:
160 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
161 case ColorMode::STANDARD_BT601_525:
162 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
163 case ColorMode::STANDARD_BT709:
164 case ColorMode::SRGB:
165 return false;
166 }
167 return false;
168}
169
170#pragma clang diagnostic pop
171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172class ConditionalLock {
173public:
174 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
175 if (lock) {
176 mMutex.lock();
177 }
178 }
179 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
180private:
181 Mutex& mMutex;
182 bool mLocked;
183};
Peiyong Linfca547f2018-07-09 13:03:33 -0700184
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800185// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
186constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
187
188float getDensityFromProperty(const char* property, bool required) {
189 char value[PROPERTY_VALUE_MAX];
190 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
191 if (!density && required) {
192 ALOGE("%s must be defined as a build property", property);
193 return FALLBACK_DENSITY;
194 }
195 return density / 160.f;
196}
197
Peiyong Lin9d846a52018-11-05 13:18:20 -0800198// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
199bool validateCompositionDataspace(Dataspace dataspace) {
200 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
201}
202
Steven Thomasb02664d2017-07-26 18:48:28 -0700203} // namespace anonymous
204
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800205// ---------------------------------------------------------------------------
206
Mathias Agopian99b49842011-06-27 16:05:52 -0700207const String16 sHardwareTest("android.permission.HARDWARE_TEST");
208const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
209const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
210const String16 sDump("android.permission.DUMP");
Ady Abrahama09852a2020-02-20 14:23:42 -0800211const char* KERNEL_IDLE_TIMER_PROP = "vendor.display.enable_kernel_idle_timer";
Mathias Agopian99b49842011-06-27 16:05:52 -0700212
213// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700214int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700215bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800216uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800217bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800218bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800219int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600220bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800221ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700222bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700223bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700224Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
225ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
226Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
227ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Ana Krulec3803b8d2020-02-03 16:35:46 -0800228bool SurfaceFlinger::useFrameRateApi;
Mathias Agopian99b49842011-06-27 16:05:52 -0700229
Kalle Raitaa099a242017-01-11 11:17:29 -0800230std::string getHwcServiceName() {
231 char value[PROPERTY_VALUE_MAX] = {};
232 property_get("debug.sf.hwc_service_name", value, "default");
233 ALOGI("Using HWComposer service: '%s'", value);
234 return std::string(value);
235}
236
237bool useTrebleTestingOverride() {
238 char value[PROPERTY_VALUE_MAX] = {};
239 property_get("debug.sf.treble_testing_override", value, "false");
240 ALOGI("Treble testing override: '%s'", value);
241 return std::string(value) == "true";
242}
243
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800244std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
245 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800246 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700247 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800248 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700249 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800250 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700251 return std::string("Enhanced");
252 default:
253 return std::string("Unknown ") +
254 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800255 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256}
257
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700258SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800259
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700260SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
261 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700262 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700263 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700264 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700265 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700266 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800267 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
268 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800269
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700270SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800271 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800272
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900273 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800274
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700276
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700278
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900279 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800280
Steven Thomas050b2c82017-03-06 11:45:16 -0800281 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600289
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 mDefaultCompositionDataspace =
291 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700292 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
293 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900294 defaultCompositionDataspace = mDefaultCompositionDataspace;
295 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
296 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
297 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
298 wideColorGamutCompositionPixelFormat =
299 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700300
Yichi Chenda901bf2019-06-28 14:58:27 +0800301 mColorSpaceAgnosticDataspace =
302 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
303
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900304 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800305
Dominik Laskowski718f9602019-11-09 20:01:35 -0800306 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
307 switch (primary_display_orientation(Values::ORIENTATION_0)) {
308 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800309 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800310 case Values::ORIENTATION_90:
311 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800312 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800313 case Values::ORIENTATION_180:
314 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800315 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800316 case Values::ORIENTATION_270:
317 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800318 break;
319 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800320 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800321
Sundong Ahn85131bd2019-02-18 15:51:53 +0900322 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800323
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800324 // debugging stuff...
325 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700326
Mathias Agopianb4b17302013-03-20 18:36:41 -0700327 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700328 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700329
Alec Mouri989ddbe2020-02-06 09:26:19 -0800330 property_get("ro.build.type", value, "user");
331 mIsUserBuild = strcmp(value, "user") == 0;
332
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800333 property_get("debug.sf.showupdates", value, "0");
334 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700335
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700336 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000337
338 // DDMS debugging deprecated (b/120782499)
339 property_get("debug.sf.ddms", value, "0");
340 int debugDdms = atoi(value);
341 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700342
343 property_get("debug.sf.disable_backpressure", value, "0");
344 mPropagateBackpressure = !atoi(value);
345 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700346
Ady Abrahamadb9a992019-09-19 21:21:55 +0000347 property_get("debug.sf.enable_gl_backpressure", value, "0");
348 mPropagateBackpressureClientComposition = atoi(value);
349 ALOGI_IF(mPropagateBackpressureClientComposition,
350 "Enabling backpressure propagation for Client Composition");
351
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800352 property_get("debug.sf.enable_hwc_vds", value, "0");
353 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800354 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800355
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800356 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800357 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800358 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700359
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800360 property_get("ro.surface_flinger.supports_background_blur", value, "0");
361 bool supportsBlurs = atoi(value);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800362 property_get("debug.sf.disable_blurs", value, "0");
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800363 bool disableBlurs = atoi(value);
364 mEnableBlurs = supportsBlurs && !disableBlurs;
365 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
366 disableBlurs);
Lucas Dupin2dd6f392020-02-18 17:43:36 -0800367 property_get("ro.sf.blurs_are_expensive", value, "0");
368 mBlursAreExpensive = atoi(value);
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800369
Ady Abraham0a525092020-03-03 12:51:24 -0800370 const size_t defaultListSize = ISurfaceComposer::MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700371 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
372 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
373
Dan Stozaec460082018-12-17 15:35:09 -0800374 property_get("debug.sf.luma_sampling", value, "1");
375 mLumaSampling = atoi(value);
376
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800377 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800378 mDisableClientCompositionCache = atoi(value);
379
Romain Guy11d63f42017-07-20 12:47:14 -0700380 // We should be reading 'persist.sys.sf.color_saturation' here
381 // but since /data may be encrypted, we need to wait until after vold
382 // comes online to attempt to read the property. The property is
383 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800384
385 if (useTrebleTestingOverride()) {
386 // Without the override SurfaceFlinger cannot connect to HIDL
387 // services that are not listed in the manifests. Considered
388 // deriving the setting from the set service name, but it
389 // would be brittle if the name that's not 'default' is used
390 // for production purposes later on.
391 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
392 }
Ana Krulec3803b8d2020-02-03 16:35:46 -0800393
394 useFrameRateApi = use_frame_rate_api(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800395}
396
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800397void SurfaceFlinger::onFirstRef()
398{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800399 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800400}
401
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700402SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800403
Dan Stozac7014012014-02-14 15:03:43 -0800404void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800405{
406 // the window manager died on us. prepare its eulogy.
407
Andy McFadden13a082e2012-08-24 10:16:42 -0700408 // restore initial conditions (default device unblank, etc)
409 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800410
411 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700412 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800413}
414
Robert Carr1db73f62016-12-21 12:58:51 -0800415static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700416 status_t err = client->initCheck();
417 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800418 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800419 }
Robert Carr1db73f62016-12-21 12:58:51 -0800420 return nullptr;
421}
422
423sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
424 return initClient(new Client(this));
425}
426
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700427sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
428 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700429{
430 class DisplayToken : public BBinder {
431 sp<SurfaceFlinger> flinger;
432 virtual ~DisplayToken() {
433 // no more references, this display must be terminated
434 Mutex::Autolock _l(flinger->mStateLock);
435 flinger->mCurrentState.displays.removeItem(this);
436 flinger->setTransactionFlags(eDisplayTransactionNeeded);
437 }
438 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700439 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700440 : flinger(flinger) {
441 }
442 };
443
444 sp<BBinder> token = new DisplayToken(this);
445
446 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700447 // Display ID is assigned when virtual display is allocated by HWC.
448 DisplayDeviceState state;
449 state.isSecure = secure;
450 state.displayName = displayName;
451 mCurrentState.displays.add(token, state);
452 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700453 return token;
454}
455
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700456void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700457 Mutex::Autolock _l(mStateLock);
458
Dominik Laskowski075d3172018-05-24 15:50:06 -0700459 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
460 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700461 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700462 return;
463 }
464
Dominik Laskowski075d3172018-05-24 15:50:06 -0700465 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
466 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700467 ALOGE("destroyDisplay called for non-virtual display");
468 return;
469 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700470 mInterceptor->saveDisplayDeletion(state.sequenceId);
471 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700472 setTransactionFlags(eDisplayTransactionNeeded);
473}
474
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800475std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
476 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800478 const auto internalDisplayId = getInternalDisplayIdLocked();
479 if (!internalDisplayId) {
480 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700481 }
482
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800483 std::vector<PhysicalDisplayId> displayIds;
484 displayIds.reserve(mPhysicalDisplayTokens.size());
485 displayIds.push_back(internalDisplayId->value);
486
487 for (const auto& [id, token] : mPhysicalDisplayTokens) {
488 if (id != *internalDisplayId) {
489 displayIds.push_back(id.value);
490 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700491 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700492
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800493 return displayIds;
494}
495
496sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
497 Mutex::Autolock lock(mStateLock);
498 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700499}
500
Ady Abraham37965d42018-11-01 13:43:32 -0700501status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
502 if (!outGetColorManagement) {
503 return BAD_VALUE;
504 }
505 *outGetColorManagement = useColorManagement;
506 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700507}
508
Lloyd Pique441d5042018-10-18 16:49:51 -0700509HWComposer& SurfaceFlinger::getHwComposer() const {
510 return mCompositionEngine->getHwComposer();
511}
512
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700513renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
514 return mCompositionEngine->getRenderEngine();
515}
516
Lloyd Pique70d91362018-10-18 16:02:55 -0700517compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
518 return *mCompositionEngine.get();
519}
520
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800521void SurfaceFlinger::bootFinished()
522{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700523 if (mStartPropertySetThread->join() != NO_ERROR) {
524 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800525 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800526 const nsecs_t now = systemTime();
527 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000528 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700529
Mikael Pessa90092f42019-08-26 17:22:04 -0700530 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000531 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700532
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700533 // wait patiently for the window manager death
534 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700535 mWindowManager = defaultServiceManager()->getService(name);
536 if (mWindowManager != 0) {
537 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700538 }
Robert Carr720e5062018-07-30 17:45:14 -0700539 sp<IBinder> input(defaultServiceManager()->getService(
540 String16("inputflinger")));
541 if (input == nullptr) {
542 ALOGE("Failed to link to input service");
543 } else {
544 mInputFlinger = interface_cast<IInputFlinger>(input);
545 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700546
Steven Thomas050b2c82017-03-06 11:45:16 -0800547 if (mVrFlinger) {
548 mVrFlinger->OnBootFinished();
549 }
550
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700551 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700552 // formerly we would just kill the process, but we now ask it to exit so it
553 // can choose where to stop the animation.
554 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700555
556 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
557 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
558 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700559
Ana Krulecbd6654b2019-02-15 15:18:15 -0800560 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800561 readPersistentProperties();
562 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800563
Ady Abraham8a82ba62020-01-17 12:43:17 -0800564 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
565 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
566 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
567 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800568 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800569}
570
Dan Stoza436ccf32018-06-21 12:10:12 -0700571uint32_t SurfaceFlinger::getNewTexture() {
572 {
573 std::lock_guard lock(mTexturePoolMutex);
574 if (!mTexturePool.empty()) {
575 uint32_t name = mTexturePool.back();
576 mTexturePool.pop_back();
577 ATRACE_INT("TexturePoolSize", mTexturePool.size());
578 return name;
579 }
580
581 // The pool was too small, so increase it for the future
582 ++mTexturePoolSize;
583 }
584
585 // The pool was empty, so we need to get a new texture name directly using a
586 // blocking call to the main thread
587 uint32_t name = 0;
588 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
589 return name;
590}
591
Mathias Agopian3f844832013-08-07 21:24:32 -0700592void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700593 std::lock_guard lock(mTexturePoolMutex);
594 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
595 // to actually delete this or not based on mTexturePoolSize
596 mTexturePool.push_back(texture);
597 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700598}
599
Wei Wangf9b05ee2017-07-19 20:59:39 -0700600// Do not call property_set on main thread which will be blocked by init
601// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700602void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700603 ALOGI( "SurfaceFlinger's main thread ready to run. "
604 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700605 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800606
Steven Thomasb02664d2017-07-26 18:48:28 -0700607 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700608 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800609 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700610 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
611 renderengine::RenderEngineCreationArgs::Builder()
612 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
613 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
614 .setUseColorManagerment(useColorManagement)
615 .setEnableProtectedContext(enable_protected_contents(false))
616 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800617 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700618 .setContextPriority(useContextPriority
619 ? renderengine::RenderEngine::ContextPriority::HIGH
620 : renderengine::RenderEngine::ContextPriority::MEDIUM)
621 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800622 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700623
624 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
625 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700626 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -0800627 mCompositionEngine->getHwComposer().setConfiguration(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800628 // Process any initial hotplug and resulting display changes.
629 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700630 const auto display = getDefaultDisplayDeviceLocked();
631 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700632 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700633 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800634
Steven Thomas050b2c82017-03-06 11:45:16 -0800635 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700636 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700637 // This callback is called from the vr flinger dispatch thread. We
638 // need to call signalTransaction(), which requires holding
639 // mStateLock when we're not on the main thread. Acquiring
640 // mStateLock from the vr flinger dispatch thread might trigger a
641 // deadlock in surface flinger (see b/66916578), so post a message
642 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700643 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700644 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
645 mVrFlingerRequestsDisplay = requestDisplay;
646 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700647 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800648 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700649 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
650 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700651 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700652 .value_or(0),
653 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800654 if (!mVrFlinger) {
655 ALOGE("Failed to start vrflinger");
656 }
657 }
658
Mathias Agopian92a979a2012-08-02 18:32:23 -0700659 // initialize our drawing state
660 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700661
Andy McFadden13a082e2012-08-24 10:16:42 -0700662 // set initial conditions (e.g. unblank default device)
663 initializeDisplays();
664
Steven Thomas137d4bc2019-07-25 16:55:14 -0700665 char primeShaderCache[PROPERTY_VALUE_MAX];
666 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
667 if (atoi(primeShaderCache)) {
668 getRenderEngine().primeCache();
669 }
Dan Stoza4e637772016-07-28 13:31:51 -0700670
Wei Wangf9b05ee2017-07-19 20:59:39 -0700671 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700672
673 const bool presentFenceReliable =
674 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
675 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700676
677 if (mStartPropertySetThread->Start() != NO_ERROR) {
678 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800679 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800680
Dan Stoza9e56aa02015-11-02 13:00:03 -0800681 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700682}
683
Romain Guy11d63f42017-07-20 12:47:14 -0700684void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700685 Mutex::Autolock _l(mStateLock);
686
Romain Guy11d63f42017-07-20 12:47:14 -0700687 char value[PROPERTY_VALUE_MAX];
688
689 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800690 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700691 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800692 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100693
694 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700695 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800696
697 property_get("persist.sys.sf.color_mode", value, "0");
698 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700699}
700
Mathias Agopiana67e4182012-06-19 17:26:12 -0700701void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800702 // Start boot animation service by setting a property mailbox
703 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700704 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800705 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700706 if (mStartPropertySetThread->join() != NO_ERROR) {
707 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800708 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700709}
710
Mathias Agopian875d8e12013-06-07 15:35:48 -0700711size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700712 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700713}
714
Mathias Agopian875d8e12013-06-07 15:35:48 -0700715size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700716 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700717}
718
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800719// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800720
Jamie Gennis582270d2011-08-17 18:19:00 -0700721bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800722 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800723 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800724 return authenticateSurfaceTextureLocked(bufferProducer);
725}
726
727bool SurfaceFlinger::authenticateSurfaceTextureLocked(
728 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800729 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800730 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800731}
732
Brian Anderson6b376712017-04-04 10:51:39 -0700733status_t SurfaceFlinger::getSupportedFrameTimestamps(
734 std::vector<FrameEvent>* outSupported) const {
735 *outSupported = {
736 FrameEvent::REQUESTED_PRESENT,
737 FrameEvent::ACQUIRE,
738 FrameEvent::LATCH,
739 FrameEvent::FIRST_REFRESH_START,
740 FrameEvent::LAST_REFRESH_START,
741 FrameEvent::GPU_COMPOSITION_DONE,
742 FrameEvent::DEQUEUE_READY,
743 FrameEvent::RELEASE,
744 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700745 ConditionalLock _l(mStateLock,
746 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700747 if (!getHwComposer().hasCapability(
748 HWC2::Capability::PresentFenceIsNotReliable)) {
749 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
750 }
751 return NO_ERROR;
752}
753
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800754status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
755 if (!displayToken || !state) {
756 return BAD_VALUE;
757 }
758
759 Mutex::Autolock lock(mStateLock);
760
761 const auto display = getDisplayDeviceLocked(displayToken);
762 if (!display) {
763 return NAME_NOT_FOUND;
764 }
765
766 state->layerStack = display->getLayerStack();
767 state->orientation = display->getOrientation();
768
769 const Rect viewport = display->getViewport();
770 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
771
772 return NO_ERROR;
773}
774
775status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
776 if (!displayToken || !info) {
777 return BAD_VALUE;
778 }
779
780 Mutex::Autolock lock(mStateLock);
781
782 const auto display = getDisplayDeviceLocked(displayToken);
783 if (!display) {
784 return NAME_NOT_FOUND;
785 }
786
Dominik Laskowski55c85402020-01-21 16:25:47 -0800787 if (const auto connectionType = display->getConnectionType())
788 info->connectionType = *connectionType;
789 else {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800790 return INVALID_OPERATION;
791 }
792
793 if (mEmulatedDisplayDensity) {
794 info->density = mEmulatedDisplayDensity;
795 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -0800796 info->density = info->connectionType == DisplayConnectionType::Internal
797 ? mInternalDisplayDensity
798 : FALLBACK_DENSITY;
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800799 }
800
801 info->secure = display->isSecure();
Marin Shalamanovf5de90d2019-10-08 10:57:25 +0200802 info->deviceProductInfo = getDeviceProductInfoLocked(*display);
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800803
804 return NO_ERROR;
805}
806
Dominik Laskowski22488f62019-03-28 09:53:04 -0700807status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800808 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700809 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700810 return BAD_VALUE;
811 }
812
Dominik Laskowski22488f62019-03-28 09:53:04 -0700813 Mutex::Autolock lock(mStateLock);
814
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800815 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700816 if (!displayId) {
817 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700818 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700819
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800820 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700821
Dan Stoza7f7da322014-05-02 15:26:25 -0700822 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700823
Dominik Laskowski075d3172018-05-24 15:50:06 -0700824 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800825 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700826
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800827 auto width = hwConfig->getWidth();
828 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700829
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800830 auto xDpi = hwConfig->getDpiX();
831 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700832
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800833 if (isInternal &&
834 (internalDisplayOrientation == ui::ROTATION_90 ||
835 internalDisplayOrientation == ui::ROTATION_270)) {
836 std::swap(width, height);
837 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700838 }
839
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800840 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800841
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800842 if (mEmulatedDisplayDensity) {
843 config.xDpi = mEmulatedDisplayDensity;
844 config.yDpi = mEmulatedDisplayDensity;
845 } else {
846 config.xDpi = xDpi;
847 config.yDpi = yDpi;
848 }
849
850 const nsecs_t period = hwConfig->getVsyncPeriod();
851 config.refreshRate = 1e9f / period;
852
853 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
854 config.appVsyncOffset = offsets.late.app;
855 config.sfVsyncOffset = offsets.late.sf;
Ady Abrahamff731d82020-02-18 17:22:46 -0800856 config.configGroup = hwConfig->getConfigGroup();
Dan Stoza9e56aa02015-11-02 13:00:03 -0800857
Andy McFadden91b2ca82014-06-13 14:04:23 -0700858 // This is how far in advance a buffer must be queued for
859 // presentation at a given time. If you want a buffer to appear
860 // on the screen at time N, you must submit the buffer before
861 // (N - presentationDeadline).
862 //
863 // Normally it's one full refresh period (to give SF a chance to
864 // latch the buffer), but this can be reduced by configuring a
865 // DispSync offset. Any additional delays introduced by the hardware
866 // composer or panel must be accounted for here.
867 //
868 // We add an additional 1ms to allow for processing time and
869 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800870 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700871
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800872 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700873 }
874
Dan Stoza7f7da322014-05-02 15:26:25 -0700875 return NO_ERROR;
876}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700877
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700878status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
879 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700880 return BAD_VALUE;
881 }
882
Ana Krulecc2870422019-01-29 19:00:58 -0800883 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700884 return NO_ERROR;
885}
886
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700887int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
888 const auto display = getDisplayDevice(displayToken);
889 if (!display) {
890 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800891 return BAD_VALUE;
892 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700893
Steven Thomasc9098452019-09-30 17:15:05 -0700894 if (display->isPrimary()) {
895 std::lock_guard<std::mutex> lock(mActiveConfigLock);
896 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800897 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700898 }
Steven Thomasc9098452019-09-30 17:15:05 -0700899 }
Ady Abraham2139f732019-11-13 18:56:40 -0800900
901 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700902}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700903
Ady Abraham03b02dd2019-03-21 15:40:11 -0700904void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800905 ATRACE_CALL();
Ady Abraham2e1dd892020-03-05 13:48:36 -0800906 auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
Ady Abraham2139f732019-11-13 18:56:40 -0800907 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800908
Ady Abrahamb838aed2019-02-12 15:30:16 -0800909 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham59db0a32020-03-02 18:04:20 -0800910 if (mDesiredActiveConfigChanged) {
911 // If a config change is pending, just cache the latest request in
912 // mDesiredActiveConfig
913 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
914 mDesiredActiveConfig = info;
915 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
916 } else {
917 // Check is we are already at the desired config
918 const auto display = getDefaultDisplayDeviceLocked();
919 if (!display || display->getActiveConfig() == refreshRate.configId) {
920 return;
921 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800922
Ady Abraham59db0a32020-03-02 18:04:20 -0800923 // Initiate a config change.
924 mDesiredActiveConfigChanged = true;
925 mDesiredActiveConfig = info;
926
Ady Abrahamb838aed2019-02-12 15:30:16 -0800927 // This will trigger HWC refresh without resetting the idle timer.
928 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700929 // Start receiving vsync samples now, so that we can detect a period
930 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800931 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700932 // As we called to set period, we will call to onRefreshRateChangeCompleted once
933 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700934 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800935
Ady Abraham9e16a482019-12-03 17:19:41 -0800936 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
937 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800938 }
Ady Abraham03b02dd2019-03-21 15:40:11 -0700939
940 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800941 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700942 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800943}
944
945status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
946 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800947
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100948 if (!displayToken) {
949 return BAD_VALUE;
950 }
Ady Abraham838de062019-02-04 10:24:03 -0800951
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100952 status_t result = NO_ERROR;
953
954 postMessageSync(new LambdaMessage([&]() {
955 const auto display = getDisplayDeviceLocked(displayToken);
956 if (!display) {
957 ALOGE("Attempt to set allowed display configs for invalid display token %p",
958 displayToken.get());
959 result = BAD_VALUE;
960 } else if (display->isVirtual()) {
961 ALOGW("Attempt to set allowed display configs for virtual display");
962 result = BAD_VALUE;
963 } else {
964 HwcConfigIndexType config(mode);
965 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
966 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
967 refreshRate.fps);
968 }
969 }));
970
971 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800972}
973
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800974void SurfaceFlinger::setActiveConfigInternal() {
975 ATRACE_CALL();
976
Dominik Laskowski22488f62019-03-28 09:53:04 -0700977 const auto display = getDefaultDisplayDeviceLocked();
978 if (!display) {
979 return;
980 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800981
Dominik Laskowski22488f62019-03-28 09:53:04 -0700982 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800983 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700984 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800985 display->setActiveConfig(mUpcomingActiveConfig.configId);
986
Ady Abraham2e1dd892020-03-05 13:48:36 -0800987 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -0800988 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800989 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
990 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800991 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700992
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800993 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700994 const nsecs_t vsyncPeriod =
995 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
996 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800997 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700998 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800999 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001000}
1001
Ady Abraham53852a52019-05-28 18:07:44 -07001002void SurfaceFlinger::desiredActiveConfigChangeDone() {
1003 std::lock_guard<std::mutex> lock(mActiveConfigLock);
1004 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
1005 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -07001006
Ady Abraham2e1dd892020-03-05 13:48:36 -08001007 const auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001008 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -08001009 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -08001010 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
1011 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -07001012}
1013
Dominik Laskowski22488f62019-03-28 09:53:04 -07001014bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -08001015 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -08001016 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -08001017 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -07001018 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -08001019 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001020 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001021 return true;
1022 }
1023
1024 // We received the present fence from the HWC, so we assume it successfully updated
1025 // the config, hence we update SF.
1026 mCheckPendingFence = false;
1027 setActiveConfigInternal();
1028 }
1029
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001030 // Store the local variable to release the lock.
1031 ActiveConfigInfo desiredActiveConfig;
1032 {
1033 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001034 if (!mDesiredActiveConfigChanged) {
1035 return false;
1036 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001037 desiredActiveConfig = mDesiredActiveConfig;
1038 }
1039
Ady Abraham2e1dd892020-03-05 13:48:36 -08001040 auto& refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -08001041 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1042 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1043 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001044 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001045 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1046 // display is not valid or we are already in the requested mode
1047 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001048 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001049 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001050 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001051
Ady Abraham838de062019-02-04 10:24:03 -08001052 // Desired active config was set, it is different than the config currently in use, however
1053 // allowed configs might have change by the time we process the refresh.
1054 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001055 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001056 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001057 return false;
1058 }
Alec Mouri7f015182019-07-11 13:56:22 -07001059
Ady Abrahamb838aed2019-02-12 15:30:16 -08001060 mUpcomingActiveConfig = desiredActiveConfig;
1061 const auto displayId = display->getId();
1062 LOG_ALWAYS_FATAL_IF(!displayId);
1063
Ady Abraham2139f732019-11-13 18:56:40 -08001064 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001065
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001066 // TODO(b/142753666) use constrains
1067 HWC2::VsyncPeriodChangeConstraints constraints;
1068 constraints.desiredTimeNanos = systemTime();
1069 constraints.seamlessRequired = false;
1070
1071 HWC2::VsyncPeriodChangeTimeline outTimeline;
1072 auto status =
1073 getHwComposer().setActiveConfigWithConstraints(*displayId,
1074 mUpcomingActiveConfig.configId.value(),
1075 constraints, &outTimeline);
1076 if (status != NO_ERROR) {
Ady Abraham5e95aa22020-03-04 10:26:05 -08001077 // setActiveConfigWithConstraints may fail if a hotplug event is just about
1078 // to be sent. We just log the error in this case.
1079 ALOGW("setActiveConfigWithConstraints failed: %d", status);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001080 return false;
1081 }
1082
1083 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1084 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001085 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001086 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001087}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001088
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001089status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1090 Vector<ColorMode>* outColorModes) {
1091 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001092 return BAD_VALUE;
1093 }
1094
Peiyong Lina52f0292018-03-14 17:26:31 -07001095 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001096 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001097 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001098 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1099
1100 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1101 if (!displayId) {
1102 return NAME_NOT_FOUND;
1103 }
1104
Dominik Laskowski075d3172018-05-24 15:50:06 -07001105 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001106 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001107 }
Michael Wright28f24d02016-07-12 13:30:53 -07001108 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001109
1110 // If it's built-in display and the configuration claims it's not wide color capable,
1111 // filter out all wide color modes. The typical reason why this happens is that the
1112 // hardware is not good enough to support GPU composition of wide color, and thus the
1113 // OEMs choose to disable this capability.
1114 if (isInternalDisplay && !hasWideColorDisplay) {
1115 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1116 isWideColorMode);
1117 } else {
1118 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1119 }
Michael Wright28f24d02016-07-12 13:30:53 -07001120
1121 return NO_ERROR;
1122}
1123
Daniel Solomon42d04562019-01-20 21:03:19 -08001124status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1125 ui::DisplayPrimaries &primaries) {
1126 if (!displayToken) {
1127 return BAD_VALUE;
1128 }
1129
1130 // Currently we only support this API for a single internal display.
1131 if (getInternalDisplayToken() != displayToken) {
1132 return BAD_VALUE;
1133 }
1134
1135 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1136 return NO_ERROR;
1137}
1138
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001139ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1140 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001141 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001142 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001143 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001144}
1145
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001146status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001147 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001148 Vector<ColorMode> modes;
1149 getDisplayColorModes(displayToken, &modes);
1150 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1151 if (mode < ColorMode::NATIVE || !exists) {
1152 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1153 decodeColorMode(mode).c_str(), mode, displayToken.get());
1154 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001155 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001156 const auto display = getDisplayDevice(displayToken);
1157 if (!display) {
1158 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1159 decodeColorMode(mode).c_str(), mode, displayToken.get());
1160 } else if (display->isVirtual()) {
1161 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1162 decodeColorMode(mode).c_str(), mode);
1163 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001164 display->getCompositionDisplay()->setColorProfile(
1165 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1166 RenderIntent::COLORIMETRIC,
1167 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001168 }
1169 }));
1170
Michael Wright28f24d02016-07-12 13:30:53 -07001171 return NO_ERROR;
1172}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001173
Galia Peycheva5492cb52019-10-30 14:13:16 +01001174status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1175 bool* outSupport) const {
1176 Mutex::Autolock _l(mStateLock);
1177
1178 if (!displayToken) {
1179 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1180 return BAD_VALUE;
1181 }
1182 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1183 if (!displayId) {
1184 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1185 displayToken.get());
1186 return NAME_NOT_FOUND;
1187 }
1188 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1189 HWC2::DisplayCapability::AutoLowLatencyMode);
1190 return NO_ERROR;
1191}
1192
1193void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1194 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1195}
1196
1197void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1198 if (!displayToken) {
1199 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1200 return;
1201 }
1202 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1203 if (!displayId) {
1204 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1205 displayToken.get());
1206 return;
1207 }
1208
1209 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1210}
1211
1212status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1213 bool* outSupport) const {
1214 Mutex::Autolock _l(mStateLock);
1215
1216 if (!displayToken) {
1217 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1218 return BAD_VALUE;
1219 }
1220 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1221 if (!displayId) {
1222 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1223 displayToken.get());
1224 return NAME_NOT_FOUND;
1225 }
1226
1227 std::vector<HWC2::ContentType> outSupportedContentTypes;
1228 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1229 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1230 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1231 return NO_ERROR;
1232}
1233
1234void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1235 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1236}
1237
1238void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1239 if (!displayToken) {
1240 ALOGE("setGameContentType() failed. Missing display token.");
1241 return;
1242 }
1243 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1244 if (!displayId) {
1245 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1246 displayToken.get());
1247 return;
1248 }
1249
1250 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1251 getHwComposer().setContentType(*displayId, type);
1252}
1253
Svetoslavd85084b2014-03-20 10:28:31 -07001254status_t SurfaceFlinger::clearAnimationFrameStats() {
1255 Mutex::Autolock _l(mStateLock);
1256 mAnimFrameTracker.clearStats();
1257 return NO_ERROR;
1258}
1259
1260status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1261 Mutex::Autolock _l(mStateLock);
1262 mAnimFrameTracker.getStats(outStats);
1263 return NO_ERROR;
1264}
1265
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001266status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1267 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001268 Mutex::Autolock _l(mStateLock);
1269
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001270 const auto display = getDisplayDeviceLocked(displayToken);
1271 if (!display) {
1272 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001273 return BAD_VALUE;
1274 }
1275
Peiyong Linfb069302018-04-25 14:34:31 -07001276 // At this point the DisplayDeivce should already be set up,
1277 // meaning the luminance information is already queried from
1278 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001279 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001280 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1281 capabilities.getDesiredMaxLuminance(),
1282 capabilities.getDesiredMaxAverageLuminance(),
1283 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001284
1285 return NO_ERROR;
1286}
1287
Marin Shalamanovf5de90d2019-10-08 10:57:25 +02001288std::optional<DeviceProductInfo> SurfaceFlinger::getDeviceProductInfoLocked(
1289 const DisplayDevice& display) const {
1290 // TODO(b/149075047): Populate DeviceProductInfo on hotplug and store it in DisplayDevice to
1291 // avoid repetitive HAL IPC and EDID parsing.
1292 const auto displayId = display.getId();
1293 LOG_FATAL_IF(!displayId);
1294
1295 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
1296 LOG_FATAL_IF(!hwcDisplayId);
1297
1298 uint8_t port;
1299 DisplayIdentificationData data;
1300 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
1301 ALOGV("%s: No identification data.", __FUNCTION__);
1302 return {};
1303 }
1304
1305 const auto info = parseDisplayIdentificationData(port, data);
1306 if (!info) {
1307 return {};
1308 }
1309 return info->deviceProductInfo;
1310}
1311
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001312status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1313 ui::PixelFormat* outFormat,
1314 ui::Dataspace* outDataspace,
1315 uint8_t* outComponentMask) const {
1316 if (!outFormat || !outDataspace || !outComponentMask) {
1317 return BAD_VALUE;
1318 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001319 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001320 if (!display || !display->getId()) {
1321 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1322 return BAD_VALUE;
1323 }
1324 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1325 outDataspace, outComponentMask);
1326}
1327
Kevin DuBois74e53772018-11-19 10:52:38 -08001328status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1329 bool enable, uint8_t componentMask,
1330 uint64_t maxFrames) const {
1331 const auto display = getDisplayDevice(displayToken);
1332 if (!display || !display->getId()) {
1333 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1334 return BAD_VALUE;
1335 }
1336
1337 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1338 componentMask, maxFrames);
1339}
1340
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001341status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1342 uint64_t maxFrames, uint64_t timestamp,
1343 DisplayedFrameStats* outStats) const {
1344 const auto display = getDisplayDevice(displayToken);
1345 if (!display || !display->getId()) {
1346 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1347 return BAD_VALUE;
1348 }
1349
1350 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1351 outStats);
1352}
1353
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001354status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1355 if (!outSupported) {
1356 return BAD_VALUE;
1357 }
1358 *outSupported = getRenderEngine().supportsProtectedContent();
1359 return NO_ERROR;
1360}
1361
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001362status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1363 bool* outIsWideColorDisplay) const {
1364 if (!displayToken || !outIsWideColorDisplay) {
1365 return BAD_VALUE;
1366 }
1367 Mutex::Autolock _l(mStateLock);
1368 const auto display = getDisplayDeviceLocked(displayToken);
1369 if (!display) {
1370 return BAD_VALUE;
1371 }
Peiyong Linff84a152019-05-17 18:36:19 -07001372
1373 // Use hasWideColorDisplay to override built-in display.
1374 const auto displayId = display->getId();
1375 if (displayId && displayId == getInternalDisplayIdLocked()) {
1376 *outIsWideColorDisplay = hasWideColorDisplay;
1377 return NO_ERROR;
1378 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001379 *outIsWideColorDisplay = display->hasWideColorGamut();
1380 return NO_ERROR;
1381}
1382
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001383status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001384 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001385 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001386
Dominik Laskowski6505f792019-09-18 11:10:05 -07001387 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1388 mEventQueue->setEventConnection(
1389 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001390 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001391 }));
1392
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001393 return NO_ERROR;
1394}
1395
1396status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001397 Mutex::Autolock lock(mStateLock);
1398 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001399}
1400
Lloyd Pique755e3192018-01-31 16:46:15 -08001401status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1402 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001403 // Try to acquire a lock for 1s, fail gracefully
1404 const status_t err = mStateLock.timedLock(s2ns(1));
1405 const bool locked = (err == NO_ERROR);
1406 if (!locked) {
1407 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1408 return TIMED_OUT;
1409 }
1410
1411 outLayers->clear();
1412 mCurrentState.traverseInZOrder([&](Layer* layer) {
1413 outLayers->push_back(layer->getLayerDebugInfo());
1414 });
1415
1416 mStateLock.unlock();
1417 return NO_ERROR;
1418}
1419
Peiyong Linc6780972018-10-28 15:24:08 -07001420status_t SurfaceFlinger::getCompositionPreference(
1421 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1422 Dataspace* outWideColorGamutDataspace,
1423 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001424 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001425 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001426 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001427 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001428 return NO_ERROR;
1429}
1430
Dan Stozaec460082018-12-17 15:35:09 -08001431status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1432 const sp<IBinder>& stopLayerHandle,
1433 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001434 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001435 return BAD_VALUE;
1436 }
1437 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001438 return NO_ERROR;
1439}
1440
Dan Stozaec460082018-12-17 15:35:09 -08001441status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001442 if (!listener) {
1443 return BAD_VALUE;
1444 }
Dan Stozaec460082018-12-17 15:35:09 -08001445 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001446 return NO_ERROR;
1447}
Dan Gittik57e63c52019-01-18 16:37:54 +00001448
1449status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1450 bool* outSupport) const {
1451 if (!displayToken || !outSupport) {
1452 return BAD_VALUE;
1453 }
1454 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1455 if (!displayId) {
1456 return NAME_NOT_FOUND;
1457 }
1458 *outSupport =
1459 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1460 return NO_ERROR;
1461}
1462
1463status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1464 float brightness) const {
1465 if (!displayToken) {
1466 return BAD_VALUE;
1467 }
1468 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1469 if (!displayId) {
1470 return NAME_NOT_FOUND;
1471 }
1472 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1473}
1474
Ady Abraham8532d012019-05-08 14:50:56 -07001475status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1476 PowerHint powerHint = static_cast<PowerHint>(hintId);
1477
1478 if (powerHint == PowerHint::INTERACTION) {
1479 mScheduler->notifyTouchEvent();
1480 }
1481
1482 return NO_ERROR;
1483}
1484
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001485// ----------------------------------------------------------------------------
1486
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001487sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001488 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001489 const auto& handle =
1490 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001491
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001492 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001493}
1494
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001495// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001496
1497void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001498 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001499}
1500
1501void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001502 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001503 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001504 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001505}
1506
1507void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001508 mScheduler->resetIdleTimer();
Dan Stoza030fbc12020-02-19 15:32:01 -08001509 mPowerAdvisor.notifyDisplayUpdateImminent();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001510 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001511}
1512
1513void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001514 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001515 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001516}
1517
1518status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001519 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001520 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001521}
1522
1523status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001524 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001525 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001526 if (res == NO_ERROR) {
1527 msg->wait();
1528 }
1529 return res;
1530}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001531
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001532void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001533 do {
1534 waitForEvent();
1535 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001536}
1537
Dominik Laskowski83b88212018-12-11 13:34:06 -08001538nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001539 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001540 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1541 return 0;
1542 }
1543
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001544 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001545}
1546
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001547void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001548 int64_t timestamp,
Ady Abraham5dee2f12020-02-05 17:49:47 -08001549 std::optional<hwc2_vsync_period_t> vsyncPeriod) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001550 ATRACE_NAME("SF onVsync");
1551
Steven Thomas3cfac282017-02-06 12:29:30 -08001552 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001553 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001554 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001555 return;
1556 }
1557
Dominik Laskowski075d3172018-05-24 15:50:06 -07001558 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001559 return;
1560 }
1561
Dominik Laskowski075d3172018-05-24 15:50:06 -07001562 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001563 // For now, we don't do anything with external display vsyncs.
1564 return;
1565 }
1566
Alec Mourif8e689c2019-05-20 18:32:22 -07001567 bool periodFlushed = false;
Ady Abraham5dee2f12020-02-05 17:49:47 -08001568 mScheduler->addResyncSample(timestamp, vsyncPeriod, &periodFlushed);
Alec Mourif8e689c2019-05-20 18:32:22 -07001569 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001570 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001571 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001572}
1573
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001574void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001575 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1576 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001577}
1578
Ady Abraham2139f732019-11-13 18:56:40 -08001579bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001580 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001581}
1582
Ady Abraham2139f732019-11-13 18:56:40 -08001583void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1584 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001585 const auto display = getDefaultDisplayDeviceLocked();
1586 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001587 return;
1588 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001589 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001590
Ana Krulec7d1d6832018-12-27 11:10:09 -08001591 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001592 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1593 ALOGV("Skipping config %d as it is not part of allowed configs",
1594 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001595 return;
1596 }
1597
Ady Abraham2139f732019-11-13 18:56:40 -08001598 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001599}
1600
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001601void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001602 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001603 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001604 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001605
Lloyd Piqueba04e622017-12-14 17:11:26 -08001606 // Ignore events that do not have the right sequenceId.
1607 if (sequenceId != getBE().mComposerSequenceId) {
1608 return;
1609 }
1610
Steven Thomasb02664d2017-07-26 18:48:28 -07001611 // Only lock if we're not on the main thread. This function is normally
1612 // called on a hwbinder thread, but for the primary display it's called on
1613 // the main thread with the state lock already held, so don't attempt to
1614 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001615 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001616
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001617 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001618
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001619 if (std::this_thread::get_id() == mMainThreadId) {
1620 // Process all pending hot plug events immediately if we are on the main thread.
1621 processDisplayHotplugEventsLocked();
1622 }
1623
Lloyd Piqueba04e622017-12-14 17:11:26 -08001624 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001625}
1626
Ady Abraham7159f572019-10-11 11:10:18 -07001627void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001628 int32_t sequenceId, hwc2_display_t /*display*/,
1629 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1630 Mutex::Autolock lock(mStateLock);
1631 if (sequenceId != getBE().mComposerSequenceId) {
1632 return;
1633 }
1634 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001635}
1636
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001637void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1638 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1639 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1640}
1641
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001642void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001643 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001644 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001645 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001646 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001647 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001648}
1649
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001650void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001651 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001652
1653 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1654 // display power state.
1655 postMessageAsync(new LambdaMessage(
1656 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1657}
1658
1659void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1660 ATRACE_CALL();
1661
Ady Abraham27c70212019-06-11 10:52:26 -07001662 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1663
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001664 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001665 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1666 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001667 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001668 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001669 }
Mathias Agopian86303202012-07-24 22:46:10 -07001670}
1671
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001672// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001673void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001674 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001675 // Clear the drawing state so that the logic inside of
1676 // handleTransactionLocked will fire. It will determine the delta between
1677 // mCurrentState and mDrawingState and re-apply all changes when we make the
1678 // transition.
1679 mDrawingState.displays.clear();
1680 mDisplays.clear();
1681}
1682
Steven Thomas050b2c82017-03-06 11:45:16 -08001683void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001684 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001685 if (!mVrFlinger)
1686 return;
1687 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001688 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001689 return;
1690 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001691
Lloyd Pique441d5042018-10-18 16:49:51 -07001692 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001693 ALOGE("Vr flinger is only supported for remote hardware composer"
1694 " service connections. Ignoring request to transition to vr"
1695 " flinger.");
1696 mVrFlingerRequestsDisplay = false;
1697 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001698 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001699
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001700 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001701
Steven Thomas0123ac62018-07-12 11:32:34 -07001702 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001703 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001704
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001705 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001706
1707 // Clear out all the output layers from the composition engine for all
1708 // displays before destroying the hardware composer interface. This ensures
1709 // any HWC layers are destroyed through that interface before it becomes
1710 // invalid.
1711 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001712 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001713 }
1714
Steven Thomas0123ac62018-07-12 11:32:34 -07001715 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1716 // called below. Clear the reference now so we don't accidentally use it
1717 // later.
1718 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001719
Steven Thomasb02664d2017-07-26 18:48:28 -07001720 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001721 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001722 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001723
Steven Thomasb02664d2017-07-26 18:48:28 -07001724 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001725 // Delete the current instance before creating the new one
1726 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1727 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1728 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
Lloyd Pique4603f3c2020-02-11 12:06:56 -08001729 mCompositionEngine->getHwComposer().setConfiguration(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001730
Lloyd Pique441d5042018-10-18 16:49:51 -07001731 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001732 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001733
1734 if (vrFlingerRequestsDisplay) {
1735 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001736 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001737
1738 mVisibleRegionsDirty = true;
1739 invalidateHwcGeometry();
1740
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001741 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001742 display = getDefaultDisplayDeviceLocked();
1743 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001744 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001745
Steven Thomasb02664d2017-07-26 18:48:28 -07001746 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001747 const nsecs_t vsyncPeriod = getVsyncPeriod();
1748 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001749
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001750 // The present fences returned from vr_hwc are not an accurate
1751 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001752 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001753
Steven Thomasb02664d2017-07-26 18:48:28 -07001754 // Use phase of 0 since phase is not known.
1755 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001756 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001757 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001758
Ana Krulecc2870422019-01-29 19:00:58 -08001759 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001760
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001761 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001762 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001763}
1764
Ady Abraham11579302019-09-19 12:35:58 -07001765bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1766 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001767 // We are storing the last 2 present fences. If sf's phase offset is to be
1768 // woken up before the actual vsync but targeting the next vsync, we need to check
1769 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001770 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1771 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001772
Ady Abraham11579302019-09-19 12:35:58 -07001773 if (fence == Fence::NO_FENCE) {
1774 return false;
1775 }
1776
1777 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1778 fence->wait(graceTimeMs);
1779 }
1780
1781 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001782}
1783
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001784void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001785 DisplayStatInfo stats;
1786 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001787 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001788 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001789 mExpectedPresentTime.store(
1790 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001791}
1792
Dominik Laskowski22488f62019-03-28 09:53:04 -07001793void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001794 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001795 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001796 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001797 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001798 // calculate the expected present time once and use the cached
1799 // value throughout this frame to make sure all layers are
1800 // seeing this same value.
1801 populateExpectedPresentTime();
1802
Ady Abraham11579302019-09-19 12:35:58 -07001803 // When Backpressure propagation is enabled we want to give a small grace period
1804 // for the present fence to fire instead of just giving up on this frame to handle cases
1805 // where present fence is just about to get signaled.
1806 const int graceTimeForPresentFenceMs =
1807 (mPropagateBackpressure &&
1808 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1809 ? 1
1810 : 0;
1811 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1812 previousFrameMissed(
1813 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001814 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1815 mHadDeviceComposition && frameMissed};
1816 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1817 mHadClientComposition && frameMissed};
1818
Alec Mouricc0fc602019-02-26 21:45:19 -08001819 if (frameMissed) {
1820 mFrameMissedCount++;
1821 mTimeStats->incrementMissedFrames();
Alec Mouri989ddbe2020-02-06 09:26:19 -08001822 if (mMissedFrameJankCount == 0) {
1823 mMissedFrameJankStart = systemTime();
1824 }
1825 mMissedFrameJankCount++;
Alec Mouricc0fc602019-02-26 21:45:19 -08001826 }
1827
Alec Mouri40189b02019-03-05 15:07:54 -08001828 if (hwcFrameMissed) {
1829 mHwcFrameMissedCount++;
1830 }
1831
1832 if (gpuFrameMissed) {
1833 mGpuFrameMissedCount++;
1834 }
1835
Ady Abrahamadb9a992019-09-19 21:21:55 +00001836 if (frameMissed && mPropagateBackpressure) {
1837 if ((hwcFrameMissed && !gpuFrameMissed) ||
1838 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001839 signalLayerUpdate();
1840 break;
1841 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001842 }
Dan Stoza50182882016-07-08 12:02:20 -07001843
Alec Mouri989ddbe2020-02-06 09:26:19 -08001844 // Our jank window is always at least 100ms since we missed a
1845 // frame...
1846 static constexpr nsecs_t kMinJankyDuration =
1847 std::chrono::duration_cast<std::chrono::nanoseconds>(100ms).count();
1848 // ...but if it's larger than 1s then we missed the trace cutoff.
1849 static constexpr nsecs_t kMaxJankyDuration =
1850 std::chrono::duration_cast<std::chrono::nanoseconds>(1s).count();
1851 // If we're in a user build then don't push any atoms
1852 if (!mIsUserBuild && mMissedFrameJankCount > 0) {
1853 const auto displayDevice = getDefaultDisplayDeviceLocked();
1854 // Only report jank when the display is on, as displays in DOZE
1855 // power mode may operate at a different frame rate than is
1856 // reported in their config, which causes noticeable (but less
1857 // severe) jank.
1858 if (displayDevice && displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL) {
1859 const nsecs_t currentTime = systemTime();
1860 const nsecs_t jankDuration = currentTime - mMissedFrameJankStart;
1861 if (jankDuration > kMinJankyDuration && jankDuration < kMaxJankyDuration) {
1862 ATRACE_NAME("Jank detected");
1863 ALOGD("Detected janky event. Missed frames: %d", mMissedFrameJankCount);
1864 const int32_t jankyDurationMillis = jankDuration / (1000 * 1000);
1865 android::util::stats_write(android::util::DISPLAY_JANK_REPORTED,
1866 jankyDurationMillis, mMissedFrameJankCount);
1867 }
1868
1869 // We either reported a jank event or we missed the trace
1870 // window, so clear counters here.
1871 if (jankDuration > kMinJankyDuration) {
1872 mMissedFrameJankCount = 0;
1873 mMissedFrameJankStart = 0;
1874 }
1875 }
1876 }
1877
Steven Thomas050b2c82017-03-06 11:45:16 -08001878 // Now that we're going to make it to the handleMessageTransaction()
1879 // call below it's safe to call updateVrFlinger(), which will
1880 // potentially trigger a display handoff.
1881 updateVrFlinger();
1882
Dan Stoza6b9454d2014-11-07 16:00:59 -08001883 bool refreshNeeded = handleMessageTransaction();
1884 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001885
Ana Krulecc84d09b2019-11-02 23:10:29 +01001886 // Layers need to get updated (in the previous line) before we can use them for
1887 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001888 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1889 // and may eventually call to ~Layer() if it holds the last reference
1890 {
1891 Mutex::Autolock _l(mStateLock);
1892 mScheduler->chooseRefreshRateForContent();
1893 }
1894
Ana Krulecc84d09b2019-11-02 23:10:29 +01001895 if (performSetActiveConfig()) {
1896 break;
1897 }
1898
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001899 updateCursorAsync();
1900 updateInputFlinger();
1901
Dan Stoza58784442014-12-02 16:58:17 -08001902 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001903 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001904 // Signal a refresh if a transaction modified the window state,
1905 // a new buffer was latched, or if HWC has requested a full
1906 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001907 if (mFrameStartTime <= 0) {
1908 // We should only use the time of the first invalidate
1909 // message that signals a refresh as the beginning of the
1910 // frame. Otherwise the real frame time will be
1911 // underestimated.
1912 mFrameStartTime = frameStart;
1913 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001914 signalRefresh();
1915 }
1916 break;
1917 }
1918 case MessageQueue::REFRESH: {
1919 handleMessageRefresh();
1920 break;
1921 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001922 }
1923}
1924
Dan Stoza6b9454d2014-11-07 16:00:59 -08001925bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001926 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001927 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001928
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001929 bool flushedATransaction = flushTransactionQueues();
1930
1931 bool runHandleTransaction = transactionFlags &&
1932 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1933
1934 if (runHandleTransaction) {
1935 handleTransaction(eTransactionMask);
1936 } else {
1937 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001938 }
1939
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001940 if (transactionFlushNeeded()) {
1941 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001942 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001943
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001944 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001945}
1946
Mathias Agopian4fec8732012-06-29 14:12:52 -07001947void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001948 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001949
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001950 mRefreshPending = false;
1951
Lloyd Piqueab039b52019-02-13 14:22:42 -08001952 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001953 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001954 for (const auto& [_, display] : mDisplays) {
1955 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1956 }
1957 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08001958 if (auto layerFE = layer->getCompositionEngineLayerFE())
1959 refreshArgs.layers.push_back(layerFE);
Lloyd Piqueab039b52019-02-13 14:22:42 -08001960 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001961 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1962 for (sp<Layer> layer : mLayersWithQueuedFrames) {
Lloyd Piquede196652020-01-22 17:29:58 -08001963 if (auto layerFE = layer->getCompositionEngineLayerFE())
1964 refreshArgs.layersWithQueuedFrames.push_back(layerFE);
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001965 }
1966
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001967 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001968 refreshArgs.outputColorSetting = useColorManagement
1969 ? mDisplayColorSetting
1970 : compositionengine::OutputColorSetting::kUnmanaged;
1971 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1972 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001973
1974 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1975 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lucas Dupin2dd6f392020-02-18 17:43:36 -08001976 refreshArgs.blursAreExpensive = mBlursAreExpensive;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001977
1978 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1979 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1980 mDrawingState.colorMatrixChanged = false;
1981 }
1982
1983 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1984
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001985 if (mDebugRegion != 0) {
1986 refreshArgs.devOptFlashDirtyRegionsDelay =
1987 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1988 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001989
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001990 mGeometryInvalid = false;
1991
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001992 // Store the present time just before calling to the composition engine so we could notify
1993 // the scheduler.
1994 const auto presentTime = systemTime();
1995
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001996 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001997 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1998 // Reset the frame start time now that we've recorded this frame.
1999 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002000
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002001 mScheduler->onDisplayRefreshed(presentTime);
2002
David Sodmanfa9b2af2017-12-24 13:28:59 -08002003 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08002004 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07002005
Lloyd Pique66d68602019-02-13 14:23:31 -08002006 mHadClientComposition =
2007 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2008 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08002009 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
2010 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08002011 });
2012 mHadDeviceComposition =
2013 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2014 auto& displayDevice = tokenDisplayPair.second;
2015 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
2016 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08002017 mReusedClientComposition =
2018 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
2019 auto& displayDevice = tokenDisplayPair.second;
2020 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
2021 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08002022
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002023 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07002024
David Sodman7e4ae112018-02-09 15:02:28 -08002025 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07002026 if (mVisibleRegionsDirty) {
2027 mVisibleRegionsDirty = false;
2028 if (mTracingEnabled) {
2029 mTracing.notify("visibleRegionsDirty");
2030 }
2031 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08002032
2033 if (mCompositionEngine->needsAnotherUpdate()) {
2034 signalLayerUpdate();
2035 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002036}
Mathias Agopian4fec8732012-06-29 14:12:52 -07002037
David Sodmanfa9b2af2017-12-24 13:28:59 -08002038
2039bool SurfaceFlinger::handleMessageInvalidate() {
2040 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002041 bool refreshNeeded = handlePageFlip();
2042
Vishnu Nair4351ad52019-02-11 14:13:02 -08002043 if (mVisibleRegionsDirty) {
2044 computeLayerBounds();
2045 }
2046
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002047 for (auto& layer : mLayersPendingRefresh) {
2048 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002049 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002050 invalidateLayerStack(layer, visibleReg);
2051 }
2052 mLayersPendingRefresh.clear();
2053 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002054}
2055
Ana Krulece588e312018-09-18 12:32:24 -07002056void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
2057 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002058 // Update queue of past composite+present times and determine the
2059 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08002060 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002061 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08002062 while (!getBE().mCompositePresentTimes.empty()) {
2063 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002064 // Cached values should have been updated before calling this method,
2065 // which helps avoid duplicate syscalls.
2066 nsecs_t displayTime = cpt.display->getCachedSignalTime();
2067 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
2068 break;
2069 }
2070 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08002071 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002072 }
2073
2074 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08002075 while (getBE().mCompositePresentTimes.size() > 16) {
2076 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002077 }
2078
Ana Krulece588e312018-09-18 12:32:24 -07002079 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08002080}
2081
Ana Krulece588e312018-09-18 12:32:24 -07002082void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
2083 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002084 // Integer division and modulo round toward 0 not -inf, so we need to
2085 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002086 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2087 ? (stats.vsyncPeriod -
2088 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2089 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002090
Ady Abraham9e16a482019-12-03 17:19:41 -08002091 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002092 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002093 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002094 }
2095
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002096 // Snap the latency to a value that removes scheduling jitter from the
2097 // composition and present times, which often have >1ms of jitter.
2098 // Reducing jitter is important if an app attempts to extrapolate
2099 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002100 // Snapping also allows an app to precisely calculate
2101 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002102 nsecs_t bias = stats.vsyncPeriod / 2;
2103 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2104 nsecs_t snappedCompositeToPresentLatency =
2105 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002106
David Sodman99974d22017-11-28 12:04:33 -08002107 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002108 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2109 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002110 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002111}
2112
David Sodman2b406362017-12-15 13:33:47 -08002113void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002114{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002115 ATRACE_CALL();
2116 ALOGV("postComposition");
2117
Brian Andersonf6386862016-10-31 16:34:13 -07002118 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002119 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002120 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002121 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002122 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002123 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002124
David Sodman73beded2017-11-15 11:56:06 -08002125 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002126 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002127 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002128 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002129 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2130 ->getRenderSurface()
2131 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002132 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002133 } else {
2134 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2135 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002136
David Sodman73beded2017-11-15 11:56:06 -08002137 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002138 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2139 mPreviousPresentFences[0] = displayDevice
2140 ? getHwComposer().getPresentFence(*displayDevice->getId())
2141 : Fence::NO_FENCE;
2142 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002143 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002144
Ana Krulece588e312018-09-18 12:32:24 -07002145 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002146 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002147
Lloyd Piqueab039b52019-02-13 14:22:42 -08002148 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2149 // be sampled a little later than when we started doing work for this frame,
2150 // but that should be okay since updateCompositorTiming has snapping logic.
2151 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2152 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002153 CompositorTiming compositorTiming;
2154 {
David Sodman99974d22017-11-28 12:04:33 -08002155 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2156 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002157 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002158
Edgar Arriaga844fa672020-01-16 14:21:42 -08002159 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002160 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2161 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002162 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002163 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002164 }
Robert Carr2047fae2016-11-28 14:09:09 -08002165 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002166
Ady Abraham92fa2f42020-02-11 15:33:56 -08002167 if (displayDevice && displayDevice->isPrimary() &&
2168 displayDevice->getPowerMode() == HWC_POWER_MODE_NORMAL && presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002169 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002170 }
2171
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002172 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002173 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2174 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002175 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002176 }
2177 }
2178
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002179 if (mAnimCompositionPending) {
2180 mAnimCompositionPending = false;
2181
Brian Anderson4e606e32017-03-16 15:34:57 -07002182 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002183 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002184 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002185 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002186 // The HWC doesn't support present fences, so use the refresh
2187 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002188 const nsecs_t presentTime =
2189 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002190 mAnimFrameTracker.setActualPresentTime(presentTime);
2191 }
2192 mAnimFrameTracker.advanceFrame();
2193 }
Dan Stozab90cf072015-03-05 11:05:59 -08002194
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002195 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002196 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002197 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002198 }
2199
Vishnu Nair9b079a22020-01-21 14:36:08 -08002200 if (mReusedClientComposition) {
2201 mTimeStats->incrementClientCompositionReusedFrames();
2202 }
2203
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002204 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002205
Alec Mouri717bcb62020-02-10 17:07:19 -08002206 const size_t sfConnections = mScheduler->getEventThreadConnectionCount(mSfConnectionHandle);
2207 const size_t appConnections = mScheduler->getEventThreadConnectionCount(mAppConnectionHandle);
2208 mTimeStats->recordDisplayEventConnectionCount(sfConnections + appConnections);
2209
Lloyd Pique32cbe282018-10-19 13:09:22 -07002210 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2211 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002212 return;
2213 }
2214
2215 nsecs_t currentTime = systemTime();
2216 if (mHasPoweredOff) {
2217 mHasPoweredOff = false;
2218 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002219 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002220 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002221 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2222 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002223 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002224 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002225 }
David Sodman4a36e932017-11-07 14:29:47 -08002226 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002227 }
David Sodman4a36e932017-11-07 14:29:47 -08002228 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002229
2230 {
2231 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002232 if (mTexturePool.size() < mTexturePoolSize) {
2233 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002234 const size_t offset = mTexturePool.size();
2235 mTexturePool.resize(mTexturePoolSize);
2236 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2237 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002238 } else if (mTexturePool.size() > mTexturePoolSize) {
2239 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2240 const size_t offset = mTexturePoolSize;
2241 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2242 mTexturePool.resize(mTexturePoolSize);
2243 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002244 }
2245 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002246
Ady Abrahambe0f9482019-04-24 15:41:53 -07002247 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002248 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002249
Kevin DuBois413287f2019-02-25 08:46:47 -08002250 if (mLumaSampling && mRegionSamplingThread) {
2251 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002252 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002253
2254 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2255 // side-effect of getTotalSize(), so we check that again here
2256 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002257 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002258 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2259 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002260}
2261
Vishnu Nair4351ad52019-02-11 14:13:02 -08002262void SurfaceFlinger::computeLayerBounds() {
2263 for (const auto& pair : mDisplays) {
2264 const auto& displayDevice = pair.second;
2265 const auto display = displayDevice->getCompositionDisplay();
2266 for (const auto& layer : mDrawingState.layersSortedByZ) {
2267 // only consider the layers on the given layer stack
2268 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002269 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002270 }
2271
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002272 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2273 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002274 }
2275 }
2276}
2277
David Sodmanfa9b2af2017-12-24 13:28:59 -08002278void SurfaceFlinger::postFrame()
2279{
2280 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002281 const auto display = getDefaultDisplayDeviceLocked();
2282 if (display && getHwComposer().isConnected(*display->getId())) {
2283 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002284 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2285 logFrameStats();
2286 }
2287 }
2288}
2289
Mathias Agopian87baae12012-07-31 12:38:26 -07002290void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002291{
Mathias Agopian841cde52012-03-01 15:44:37 -08002292 ATRACE_CALL();
2293
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002294 // here we keep a copy of the drawing state (that is the state that's
2295 // going to be overwritten by handleTransactionLocked()) outside of
2296 // mStateLock so that the side-effects of the State assignment
2297 // don't happen with mStateLock held (which can cause deadlocks).
2298 State drawingState(mDrawingState);
2299
Mathias Agopianca4d3602011-05-19 15:38:14 -07002300 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002301 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002302
Mathias Agopianca4d3602011-05-19 15:38:14 -07002303 // Here we're guaranteed that some transaction flags are set
2304 // so we can call handleTransactionLocked() unconditionally.
2305 // We call getTransactionFlags(), which will also clear the flags,
2306 // with mStateLock held to guarantee that mCurrentState won't change
2307 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002308
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002309 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002310 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002311 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002312
Mathias Agopianca4d3602011-05-19 15:38:14 -07002313 mDebugInTransaction = 0;
2314 invalidateHwcGeometry();
2315 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002316}
2317
Lloyd Piqueba04e622017-12-14 17:11:26 -08002318void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2319 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002320 const std::optional<DisplayIdentificationInfo> info =
2321 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002322
Dominik Laskowski075d3172018-05-24 15:50:06 -07002323 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002324 continue;
2325 }
2326
Dominik Laskowski55c85402020-01-21 16:25:47 -08002327 const DisplayId displayId = info->id;
2328 const auto it = mPhysicalDisplayTokens.find(displayId);
2329
Lloyd Piqueba04e622017-12-14 17:11:26 -08002330 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002331 if (it == mPhysicalDisplayTokens.end()) {
2332 ALOGV("Creating display %s", to_string(displayId).c_str());
2333
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002334 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002335 initScheduler(displayId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002336 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002337
Dominik Laskowski075d3172018-05-24 15:50:06 -07002338 DisplayDeviceState state;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002339 state.physical = {displayId, getHwComposer().getDisplayConnectionType(displayId)};
Dominik Laskowski075d3172018-05-24 15:50:06 -07002340 state.isSecure = true; // All physical displays are currently considered secure.
2341 state.displayName = info->name;
Dominik Laskowski55c85402020-01-21 16:25:47 -08002342
2343 sp<IBinder> token = new BBinder();
2344 mCurrentState.displays.add(token, state);
2345 mPhysicalDisplayTokens.emplace(displayId, std::move(token));
2346
Dominik Laskowski075d3172018-05-24 15:50:06 -07002347 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002348 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002349 } else {
Dominik Laskowski55c85402020-01-21 16:25:47 -08002350 ALOGV("Removing display %s", to_string(displayId).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002351
Dominik Laskowski55c85402020-01-21 16:25:47 -08002352 const ssize_t index = mCurrentState.displays.indexOfKey(it->second);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002353 if (index >= 0) {
2354 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2355 mInterceptor->saveDisplayDeletion(state.sequenceId);
2356 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002357 }
Dominik Laskowski55c85402020-01-21 16:25:47 -08002358 mPhysicalDisplayTokens.erase(it);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002359 }
2360
2361 processDisplayChangesLocked();
2362 }
2363
2364 mPendingHotplugEvents.clear();
2365}
2366
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002367void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002368 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2369 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002370}
2371
Lloyd Pique99d3da52018-01-22 17:48:03 -08002372sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002373 const wp<IBinder>& displayToken,
2374 std::shared_ptr<compositionengine::Display> compositionDisplay,
Lloyd Pique542307f2018-10-19 13:24:08 -07002375 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002376 const sp<IGraphicBufferProducer>& producer) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002377 auto displayId = compositionDisplay->getDisplayId();
2378 DisplayDeviceCreationArgs creationArgs(this, displayToken, compositionDisplay);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002379 creationArgs.sequenceId = state.sequenceId;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002380 creationArgs.isSecure = state.isSecure;
2381 creationArgs.displaySurface = dispSurface;
2382 creationArgs.hasWideColorGamut = false;
2383 creationArgs.supportedPerFrameMetadata = 0;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002384
Dominik Laskowski55c85402020-01-21 16:25:47 -08002385 if (const auto& physical = state.physical) {
2386 creationArgs.connectionType = physical->type;
2387 }
2388
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002389 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002390 creationArgs.isPrimary = isInternalDisplay;
2391
2392 if (useColorManagement && displayId) {
2393 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002394 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002395 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002396 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002397 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002398
Dominik Laskowski7e045462018-05-30 13:02:02 -07002399 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002400 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002401 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002402 }
tangrobin6753a022018-08-10 10:58:54 +08002403 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002404
Dominik Laskowski075d3172018-05-24 15:50:06 -07002405 if (displayId) {
2406 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002407 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002408 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002409 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002410
Lloyd Pique90c115d2018-09-18 21:39:42 -07002411 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002412 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002413 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002414
Lloyd Pique99d3da52018-01-22 17:48:03 -08002415 // Make sure that composition can never be stalled by a virtual display
2416 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002417 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002418 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002419 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2420 }
2421
Dominik Laskowski718f9602019-11-09 20:01:35 -08002422 creationArgs.physicalOrientation =
2423 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002424
Lloyd Pique99d3da52018-01-22 17:48:03 -08002425 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002426 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002427
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002428 sp<DisplayDevice> display = getFactory().createDisplayDevice(creationArgs);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002429
2430 if (maxFrameBufferAcquiredBuffers >= 3) {
2431 nativeWindowSurface->preallocateBuffers();
2432 }
2433
2434 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002435 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002436 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002437 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002438 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002439 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002440 display->getCompositionDisplay()->setColorProfile(
2441 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2442 RenderIntent::COLORIMETRIC,
2443 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002444 if (!state.isVirtual()) {
2445 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002446 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2447 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002448 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002449
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002450 display->setLayerStack(state.layerStack);
2451 display->setProjection(state.orientation, state.viewport, state.frame);
2452 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002453
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002454 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002455}
2456
Lloyd Pique347200f2017-12-14 17:00:15 -08002457void SurfaceFlinger::processDisplayChangesLocked() {
2458 // here we take advantage of Vector's copy-on-write semantics to
2459 // improve performance by skipping the transaction entirely when
2460 // know that the lists are identical
2461 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2462 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2463 if (!curr.isIdenticalTo(draw)) {
2464 mVisibleRegionsDirty = true;
2465 const size_t cc = curr.size();
2466 size_t dc = draw.size();
2467
2468 // find the displays that were removed
2469 // (ie: in drawing state but not in current state)
2470 // also handle displays that changed
2471 // (ie: displays that are in both lists)
2472 for (size_t i = 0; i < dc;) {
2473 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2474 if (j < 0) {
2475 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002476 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002477 // Save display ID before disconnecting.
2478 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002479 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002480
2481 if (!display->isVirtual()) {
2482 LOG_ALWAYS_FATAL_IF(!displayId);
2483 dispatchDisplayHotplugEvent(displayId->value, false);
2484 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002485 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002486
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002487 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002488 } else {
2489 // this display is in both lists. see if something changed.
2490 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002491 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002492 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2493 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2494 if (state_binder != draw_binder) {
2495 // changing the surface is like destroying and
2496 // recreating the DisplayDevice, so we just remove it
2497 // from the drawing state, so that it get re-added
2498 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002499 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002500 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002501 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002502 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002503 mDrawingState.displays.removeItemsAt(i);
2504 dc--;
2505 // at this point we must loop to the next item
2506 continue;
2507 }
2508
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002509 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002510 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002511 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002512 }
2513 if ((state.orientation != draw[i].orientation) ||
2514 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002515 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002516 }
2517 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002518 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002519 if (display->isPrimary()) {
2520 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2521 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002522 }
2523 }
2524 }
2525 ++i;
2526 }
2527
2528 // find displays that were added
2529 // (ie: in current state but not in drawing state)
2530 for (size_t i = 0; i < cc; i++) {
2531 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2532 const DisplayDeviceState& state(curr[i]);
2533
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002534 int width = 0;
2535 int height = 0;
2536 ui::PixelFormat pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_UNKNOWN);
2537 if (state.physical) {
2538 const auto& activeConfig =
2539 getCompositionEngine().getHwComposer().getActiveConfig(
2540 state.physical->id);
2541 width = activeConfig->getWidth();
2542 height = activeConfig->getHeight();
2543 pixelFormat = static_cast<ui::PixelFormat>(PIXEL_FORMAT_RGBA_8888);
2544 } else if (state.surface != nullptr) {
2545 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2546 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2547 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2548 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2549 int intPixelFormat;
2550 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intPixelFormat);
2551 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
2552 pixelFormat = static_cast<ui::PixelFormat>(intPixelFormat);
2553 } else {
2554 // Virtual displays without a surface are dormant:
2555 // they have external state (layer stack, projection,
2556 // etc.) but no internal state (i.e. a DisplayDevice).
2557 continue;
2558 }
2559
2560 compositionengine::DisplayCreationArgsBuilder builder;
2561 if (const auto& physical = state.physical) {
2562 builder.setPhysical({physical->id, physical->type});
2563 }
2564 builder.setPixels(ui::Size(width, height));
2565 builder.setPixelFormat(pixelFormat);
2566 builder.setIsSecure(state.isSecure);
2567 builder.setLayerStackId(state.layerStack);
2568 builder.setPowerAdvisor(&mPowerAdvisor);
2569 builder.setUseHwcVirtualDisplays(mUseHwcVirtualDisplays ||
2570 getHwComposer().isUsingVrComposer());
2571 builder.setName(state.displayName);
2572 auto compositionDisplay = getCompositionEngine().createDisplay(builder.build());
2573
Lloyd Pique542307f2018-10-19 13:24:08 -07002574 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002575 sp<IGraphicBufferProducer> producer;
2576 sp<IGraphicBufferProducer> bqProducer;
2577 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002578 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002579
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002580 std::optional<DisplayId> displayId = compositionDisplay->getId();
2581
Dominik Laskowski663bd282018-04-19 15:26:54 -07002582 if (state.isVirtual()) {
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002583 sp<VirtualDisplaySurface> vds =
2584 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
2585 bqProducer, bqConsumer, state.displayName);
Lloyd Pique347200f2017-12-14 17:00:15 -08002586
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002587 dispSurface = vds;
2588 producer = vds;
Lloyd Pique347200f2017-12-14 17:00:15 -08002589 } else {
2590 ALOGE_IF(state.surface != nullptr,
2591 "adding a supported display, but rendering "
2592 "surface is provided (%p), ignoring it",
2593 state.surface.get());
2594
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002595 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowski075d3172018-05-24 15:50:06 -07002596 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002597 producer = bqProducer;
2598 }
2599
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002600 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002601 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002602 mDisplays.emplace(displayToken,
Lloyd Piqueaad4ebf2019-10-03 17:58:30 -07002603 setupNewDisplayDeviceInternal(displayToken,
2604 compositionDisplay, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002605 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002606 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002607 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002608 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002609 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002610
2611 const auto displayDevice = mDisplays[displayToken];
2612 if (displayDevice->isPrimary()) {
2613 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2614 displayDevice->getHeight());
2615 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002616 }
2617 }
2618 }
2619 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002620
2621 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002622}
2623
Mathias Agopian87baae12012-07-31 12:38:26 -07002624void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002625{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002626 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2627
Dan Stoza7dde5992015-05-22 09:51:44 -07002628 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002629 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002630 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002631 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002632
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002633 /*
2634 * Traversal of the children
2635 * (perform the transaction for each of them if needed)
2636 */
2637
Marissa Wall06255332019-03-27 13:48:27 -07002638 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002639 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002640 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002641 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642
2643 const uint32_t flags = layer->doTransaction(0);
2644 if (flags & Layer::eVisibleRegion)
2645 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002646
2647 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002648 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002649 }
Robert Carr2047fae2016-11-28 14:09:09 -08002650 });
Marissa Wall06255332019-03-27 13:48:27 -07002651 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002652 }
2653
2654 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002655 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002656 */
2657
Mathias Agopiane57f2922012-08-09 16:29:12 -07002658 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002659 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002660 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002661 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002663 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002664 // The transform hint might have changed for some layers
2665 // (either because a display has changed, or because a layer
2666 // as changed).
2667 //
2668 // Walk through all the layers in currentLayers,
2669 // and update their transform hint.
2670 //
2671 // If a layer is visible only on a single display, then that
2672 // display is used to calculate the hint, otherwise we use the
2673 // default display.
2674 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002675 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002676 // the hint is set before we acquire a buffer from the surface texture.
2677 //
2678 // NOTE: layer transactions have taken place already, so we use their
2679 // drawing state. However, SurfaceFlinger's own transaction has not
2680 // happened yet, so we must use the current state layer list
2681 // (soon to become the drawing state list).
2682 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002683 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002684 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002685 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002686 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002687 // NOTE: we rely on the fact that layers are sorted by
2688 // layerStack first (so we don't have to traverse the list
2689 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002690 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002691 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002692 currentlayerStack = layerStack;
2693 // figure out if this layerstack is mirrored
2694 // (more than one display) if so, pick the default display,
2695 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002696 hintDisplay = nullptr;
2697 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002698 if (display->getCompositionDisplay()
2699 ->belongsInOutput(layer->getLayerStack(),
2700 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002701 if (hintDisplay) {
2702 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002703 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002704 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002705 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002706 }
2707 }
2708 }
2709 }
Chet Haase91d25932013-04-11 15:24:55 -07002710
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002711 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002712 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2713 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002714
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002715 // could be null when this layer is using a layerStack
2716 // that is not visible on any display. Also can occur at
2717 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002718 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002719 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002720
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002721 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002722 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002723 if (hintDisplay) {
2724 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002725 }
Robert Carr2047fae2016-11-28 14:09:09 -08002726
2727 first = false;
2728 });
Mathias Agopian84300952012-11-21 16:02:13 -08002729 }
2730
2731
Mathias Agopian3559b072012-08-15 13:46:03 -07002732 /*
2733 * Perform our own transaction if needed
2734 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002735
2736 if (mLayersAdded) {
2737 mLayersAdded = false;
2738 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002739 mVisibleRegionsDirty = true;
2740 }
2741
2742 // some layers might have been removed, so
2743 // we need to update the regions they're exposing.
2744 if (mLayersRemoved) {
2745 mLayersRemoved = false;
2746 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002747 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002748 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002749 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002750 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002751 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002752 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002753 }
Robert Carr2047fae2016-11-28 14:09:09 -08002754 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002755 }
2756
Vishnu Nairec0ab382019-02-13 15:32:56 -08002757 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002758 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002759}
2760
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002761void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002762 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002763 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002764 return;
2765 }
2766
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002767 if (mVisibleRegionsDirty || mInputInfoChanged) {
2768 mInputInfoChanged = false;
2769 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002770 } else if (mInputWindowCommands.syncInputWindows) {
2771 // If the caller requested to sync input windows, but there are no
2772 // changes to input windows, notify immediately.
2773 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002774 }
2775
Arthur Hung6cbb9752019-09-05 16:38:18 +08002776 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002777}
2778
2779void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002780 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002781
Robert Carra1257842020-01-31 13:48:28 -08002782 // We use a simple caching algorithm here. mInputDirty begins as true,
2783 // after we call setInputWindows we set it to false, so
2784 // in the future we wont call it again.. We set input dirty to true again
2785 // when any layer that hasInput() has a transaction performed on it
2786 // or when any parent or relative parent of such a layer has a transaction
2787 // performed on it. Not all of these transactions will really result in
2788 // input changes but all input changes will spring from these transactions
2789 // so the cache is safe but not optimal. It seems like it might be annoyingly
2790 // costly to cache and comapre the actual InputWindowHandle vector though.
2791 if (!mInputDirty) {
2792 return;
2793 }
2794
Robert Carr720e5062018-07-30 17:45:14 -07002795 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2796 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002797 // When calculating the screen bounds we ignore the transparent region since it may
2798 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002799 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002800 }
2801 });
chaviw291d88a2019-02-14 10:33:58 -08002802
2803 mInputFlinger->setInputWindows(inputHandles,
2804 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2805 : nullptr);
Robert Carra1257842020-01-31 13:48:28 -08002806
2807 mInputDirty = false;
Robert Carr720e5062018-07-30 17:45:14 -07002808}
2809
Vishnu Nairec0ab382019-02-13 15:32:56 -08002810void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002811 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002812 mPendingInputWindowCommands.clear();
2813}
2814
Riley Andrews03414a12014-07-01 14:22:59 -07002815void SurfaceFlinger::updateCursorAsync()
2816{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002817 compositionengine::CompositionRefreshArgs refreshArgs;
2818 for (const auto& [_, display] : mDisplays) {
2819 if (display->getId()) {
2820 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002821 }
2822 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002823
2824 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002825}
2826
Ady Abraham2139f732019-11-13 18:56:40 -08002827void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002828 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2829 // If this is called from the main thread mStateLock must be locked before
2830 // Currently the only way to call this function from the main thread is from
2831 // Sheduler::chooseRefreshRateForContent
2832
2833 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002834 changeRefreshRateLocked(refreshRate, event);
2835}
2836
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002837void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2838 if (mScheduler) {
2839 // In practice it's not allowed to hotplug in/out the primary display once it's been
2840 // connected during startup, but some tests do it, so just warn and return.
2841 ALOGW("Can't re-init scheduler");
2842 return;
2843 }
2844
Ady Abraham2139f732019-11-13 18:56:40 -08002845 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002846 mRefreshRateConfigs =
Ana Krulec3f6a2062020-01-23 15:48:01 -08002847 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002848 primaryDisplayId),
2849 currentConfig);
2850 mRefreshRateStats =
2851 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2852 currentConfig, HWC_POWER_MODE_OFF);
2853 mRefreshRateStats->setConfigMode(currentConfig);
2854
Ady Abraham9e16a482019-12-03 17:19:41 -08002855 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2856
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002857 // start the EventThread
2858 mScheduler =
2859 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002860 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002861 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002862 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002863 impl::EventThread::InterceptVSyncsCallback());
2864 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002865 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002866 [this](nsecs_t timestamp) {
2867 mInterceptor->saveVSyncEvent(timestamp);
2868 });
2869
2870 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2871 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002872 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002873
2874 mRegionSamplingThread =
2875 new RegionSamplingThread(*this, *mScheduler,
2876 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002877 // Dispatch a config change request for the primary display on scheduler
2878 // initialization, so that the EventThreads always contain a reference to a
2879 // prior configuration.
2880 //
2881 // This is a bit hacky, but this avoids a back-pointer into the main SF
2882 // classes from EventThread, and there should be no run-time binder cost
2883 // anyway since there are no connected apps at this point.
2884 const nsecs_t vsyncPeriod =
2885 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2886 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2887 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002888}
2889
Mathias Agopian4fec8732012-06-29 14:12:52 -07002890void SurfaceFlinger::commitTransaction()
2891{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002892 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002893
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002894 mTransactionPending = false;
2895 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002896 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002897}
2898
Lloyd Pique58e24a32019-08-01 15:50:14 -07002899void SurfaceFlinger::commitTransactionLocked() {
2900 if (!mLayersPendingRemoval.isEmpty()) {
2901 // Notify removed layers now that they can't be drawn from
2902 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002903 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002904
2905 // Ensure any buffers set to display on any children are released.
2906 if (l->isRemovedFromCurrentState()) {
2907 l->latchAndReleaseBuffer();
2908 }
2909
2910 // If the layer has been removed and has no parent, then it will not be reachable
2911 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2912 // ensure we can copy its current to drawing state.
2913 if (!l->getParent()) {
2914 mOffscreenLayers.emplace(l.get());
2915 }
2916 }
2917 mLayersPendingRemoval.clear();
2918 }
2919
2920 // If this transaction is part of a window animation then the next frame
2921 // we composite should be considered an animation as well.
2922 mAnimCompositionPending = mAnimTransactionPending;
2923
2924 mDrawingState = mCurrentState;
2925 // clear the "changed" flags in current state
2926 mCurrentState.colorMatrixChanged = false;
2927
Edgar Arriaga844fa672020-01-16 14:21:42 -08002928 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002929 layer->commitChildList();
2930
2931 // If the layer can be reached when traversing mDrawingState, then the layer is no
2932 // longer offscreen. Remove the layer from the offscreenLayer set.
2933 if (mOffscreenLayers.count(layer)) {
2934 mOffscreenLayers.erase(layer);
2935 }
2936 });
2937
2938 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002939 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002940}
2941
Nataniel Borges2b796da2019-02-15 13:32:18 -08002942void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2943 if (mTracingEnabledChanged) {
2944 mTracingEnabled = mTracing.isEnabled();
2945 mTracingEnabledChanged = false;
2946 }
2947
2948 // Synchronize with Tracing thread
2949 std::unique_lock<std::mutex> lock;
2950 if (mTracingEnabled) {
2951 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2952 }
2953
2954 lockedOperation();
2955
2956 // Synchronize with Tracing thread
2957 if (mTracingEnabled) {
2958 lock.unlock();
2959 }
2960}
2961
chaviw74d90ad2019-04-26 14:45:26 -07002962void SurfaceFlinger::commitOffscreenLayers() {
2963 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002964 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002965 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2966 if (!trFlags) return;
2967
2968 layer->doTransaction(0);
2969 layer->commitChildList();
2970 });
2971 }
2972}
2973
Chia-I Wuab0c3192017-08-01 11:29:00 -07002974void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002975 for (const auto& [token, displayDevice] : mDisplays) {
2976 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002977 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002978 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002979 }
2980 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002981}
2982
Dan Stoza6b9454d2014-11-07 16:00:59 -08002983bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002984{
Ady Abraham09bd3922019-04-08 10:44:56 -07002985 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002986 ALOGV("handlePageFlip");
2987
Brian Andersond6927fb2016-07-23 23:37:30 -07002988 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989
Mathias Agopian4fec8732012-06-29 14:12:52 -07002990 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002991 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002992 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002993
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002994 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2995
Eric Penner51c59cd2014-07-28 19:51:58 -07002996 // Store the set of layers that need updates. This set must not change as
2997 // buffers are being latched, as this could result in a deadlock.
2998 // Example: Two producers share the same command stream and:
2999 // 1.) Layer 0 is latched
3000 // 2.) Layer 0 gets a new frame
3001 // 2.) Layer 1 gets a new frame
3002 // 3.) Layer 1 is latched.
3003 // Display is now waiting on Layer 1's frame, which is behind layer 0's
3004 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08003005 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07003006 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003007 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07003008 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08003009 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07003010 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07003011 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07003012 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003013 }
Dan Stozaee44edd2015-03-23 15:50:23 -07003014 } else {
3015 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08003016 }
Robert Carr2047fae2016-11-28 14:09:09 -08003017 });
3018
chaviw49a108c2019-08-12 11:23:06 -07003019 // The client can continue submitting buffers for offscreen layers, but they will not
3020 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
3021 // layers to ensure dequeueBuffer doesn't block indefinitely.
3022 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08003023 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07003024 [&](Layer* l) { l->latchAndReleaseBuffer(); });
3025 }
3026
Lloyd Piquef2c79392018-12-20 16:23:33 -08003027 if (!mLayersWithQueuedFrames.empty()) {
3028 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
3029 // writes to Layer current state. See also b/119481871
3030 Mutex::Autolock lock(mStateLock);
3031
3032 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003033 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08003034 mLayersPendingRefresh.push_back(layer);
3035 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08003036 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08003037 if (layer->isBufferLatched()) {
3038 newDataLatched = true;
3039 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06003040 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07003041 }
Mathias Agopian4da75192010-08-10 17:19:56 -07003042
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07003043 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08003044
3045 // If we will need to wake up at some time in the future to deal with a
3046 // queued frame that shouldn't be displayed during this vsync period, wake
3047 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07003048 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08003049 signalLayerUpdate();
3050 }
3051
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08003052 // enter boot animation on first buffer latch
3053 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
3054 ALOGI("Enter boot animation");
3055 mBootStage = BootStage::BOOTANIMATION;
3056 }
3057
Edgar Arriaga844fa672020-01-16 14:21:42 -08003058 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07003059
Dan Stoza6b9454d2014-11-07 16:00:59 -08003060 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06003061 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003062}
3063
Mathias Agopianad456f92011-01-13 17:53:01 -08003064void SurfaceFlinger::invalidateHwcGeometry()
3065{
Dan Stoza9e56aa02015-11-02 13:00:03 -08003066 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08003067}
3068
Robert Carrc0df3122019-04-11 13:18:21 -07003069status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
3070 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
3071 const sp<IBinder>& parentHandle,
3072 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07003073 // add this layer to the current state list
3074 {
3075 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07003076 sp<Layer> parent;
3077 if (parentHandle != nullptr) {
3078 parent = fromHandle(parentHandle);
3079 if (parent == nullptr) {
3080 return NAME_NOT_FOUND;
3081 }
3082 } else {
3083 parent = parentLayer;
3084 }
3085
Ady Abraham0a525092020-03-03 12:51:24 -08003086 if (mNumLayers >= ISurfaceComposer::MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07003087 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Ady Abraham0a525092020-03-03 12:51:24 -08003088 ISurfaceComposer::MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07003089 return NO_MEMORY;
3090 }
Robert Carrc0df3122019-04-11 13:18:21 -07003091
3092 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
3093
Robert Carrb89ea9d2018-12-10 13:01:14 -08003094 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003095 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08003096 } else if (parent == nullptr) {
3097 lbc->onRemovedFromCurrentState();
3098 } else if (parent->isRemovedFromCurrentState()) {
3099 parent->addChild(lbc);
3100 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08003101 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07003102 parent->addChild(lbc);
3103 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07003104
Yiwei Zhang243b3782018-05-15 17:40:04 -07003105 if (gbc != nullptr) {
3106 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
3107 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
3108 mMaxGraphicBufferProducerListSize,
3109 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
3110 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07003111 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07003112 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07003113 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07003114 }
3115
Mathias Agopian96f08192010-06-02 23:28:45 -07003116 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08003117 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07003118
Dan Stoza7d89d062015-04-30 13:29:25 -07003119 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07003120}
3121
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08003122uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003123 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07003124}
3125
Mathias Agopian3f844832013-08-07 21:24:32 -07003126uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003127 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003128}
3129
Mathias Agopian3f844832013-08-07 21:24:32 -07003130uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003131 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003132}
3133
3134uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003135 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003136 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003137 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003138 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003139 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003140 }
3141 return old;
3142}
3143
Marissa Wall713b63f2018-10-17 15:42:43 -07003144bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003145 // to prevent onHandleDestroyed from being called while the lock is held,
3146 // we must keep a copy of the transactions (specifically the composer
3147 // states) around outside the scope of the lock
3148 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003149 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003150 {
3151 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003152
Valerie Haufce31b82019-04-30 16:41:14 -07003153 auto it = mTransactionQueues.begin();
3154 while (it != mTransactionQueues.end()) {
3155 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003156
Valerie Haufce31b82019-04-30 16:41:14 -07003157 while (!transactionQueue.empty()) {
3158 const auto& transaction = transactionQueue.front();
3159 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003160 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003161 transaction.states)) {
3162 setTransactionFlags(eTransactionFlushNeeded);
3163 break;
3164 }
3165 transactions.push_back(transaction);
3166 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3167 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003168 transaction.buffer, transaction.postTime,
3169 transaction.privileged, transaction.hasListenerCallbacks,
3170 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003171 transactionQueue.pop();
3172 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003173 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003174
Valerie Haufce31b82019-04-30 16:41:14 -07003175 if (transactionQueue.empty()) {
3176 it = mTransactionQueues.erase(it);
3177 mTransactionCV.broadcast();
3178 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003179 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003180 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003181 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003182 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003183 return flushedATransaction;
3184}
3185
3186bool SurfaceFlinger::transactionFlushNeeded() {
3187 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003188}
3189
chaviwca27f252018-02-06 16:46:39 -08003190
Marissa Wall17b4e452018-12-26 16:32:34 -08003191bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003192 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003193 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003194 if (!useCachedExpectedPresentTime)
3195 populateExpectedPresentTime();
3196
3197 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003198 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3199 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3200 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3201 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3202 return false;
3203 }
3204
Marissa Wall713b63f2018-10-17 15:42:43 -07003205 for (const ComposerState& state : states) {
3206 const layer_state_t& s = state.state;
3207 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3208 continue;
3209 }
3210 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003211 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003212 }
3213 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003214 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003215}
3216
Valerie Hau9dab9732019-08-20 09:29:25 -07003217void SurfaceFlinger::setTransactionState(
3218 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3219 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3220 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3221 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003222 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003223
Valerie Haubc6ddb12019-03-08 11:10:15 -08003224 const int64_t postTime = systemTime();
3225
Robert Carr14167e02019-02-13 13:50:55 -08003226 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3227
Mathias Agopian698c0872011-06-28 19:09:31 -07003228 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003229
Marissa Wall713b63f2018-10-17 15:42:43 -07003230 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003231 auto itr = mTransactionQueues.find(applyToken);
3232 // if this is an animation frame, wait until prior animation frame has
3233 // been applied by SF
3234 if (flags & eAnimation) {
3235 while (itr != mTransactionQueues.end()) {
3236 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3237 if (CC_UNLIKELY(err != NO_ERROR)) {
3238 ALOGW_IF(err == TIMED_OUT,
3239 "setTransactionState timed out "
3240 "waiting for animation frame to apply");
3241 break;
3242 }
3243 itr = mTransactionQueues.find(applyToken);
3244 }
3245 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003246
3247 // Expected present time is computed and cached on invalidate, so it may be stale.
3248 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3249 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003250 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003251 uncacheBuffer, postTime, privileged,
3252 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003253 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003254 return;
3255 }
3256
Valerie Haubc6ddb12019-03-08 11:10:15 -08003257 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003258 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3259 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003260}
3261
Valerie Hau9dab9732019-08-20 09:29:25 -07003262void SurfaceFlinger::applyTransactionState(
3263 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3264 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3265 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3266 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3267 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003268 uint32_t transactionFlags = 0;
3269
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003270 if (flags & eAnimation) {
3271 // For window updates that are part of an animation we must wait for
3272 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003273 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003274 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003275 if (CC_UNLIKELY(err != NO_ERROR)) {
3276 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003277 // caller after a few seconds.
3278 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3279 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003280 mAnimTransactionPending = false;
3281 break;
3282 }
3283 }
3284 }
3285
chaviwca27f252018-02-06 16:46:39 -08003286 for (const DisplayState& display : displays) {
3287 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003288 }
3289
Valerie Hau9dab9732019-08-20 09:29:25 -07003290 // start and end registration for listeners w/ no surface so they can get their callback. Note
3291 // that listeners with SurfaceControls will start registration during setClientStateLocked
3292 // below.
3293 for (const auto& listener : listenerCallbacks) {
3294 mTransactionCompletedThread.startRegistration(listener);
3295 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003296 }
3297
Valerie Hau9dab9732019-08-20 09:29:25 -07003298 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003299 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003300 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003301 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3302 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003303 }
3304
Valerie Hau9dab9732019-08-20 09:29:25 -07003305 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003306 mTransactionCompletedThread.endRegistration(listenerCallback);
3307 }
3308
Marissa Walle2ffb422018-10-12 11:33:52 -07003309 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003310 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003311 mTransactionCompletedThread.sendCallbacks();
3312 }
3313 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003314
chaviw273171b2018-12-26 11:46:30 -08003315 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3316
Marissa Wall947d34e2019-03-29 14:03:53 -07003317 if (uncacheBuffer.isValid()) {
3318 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003319 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003320 }
3321
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003322 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3323 // anyway. This can be used as a flush mechanism for previous async transactions.
3324 // Empty animation transaction can be used to simulate back-pressure, so also force a
3325 // transaction for empty animation transactions.
3326 if (transactionFlags == 0 &&
3327 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003328 transactionFlags = eTransactionNeeded;
3329 }
3330
Marissa Wall06255332019-03-27 13:48:27 -07003331 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3332 // so we don't have to wake up again next frame to preform an uneeded traversal.
3333 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3334 transactionFlags = transactionFlags & (~eTraversalNeeded);
3335 mTraversalNeededMainThread = true;
3336 }
3337
Mathias Agopian386aa982011-11-07 21:58:03 -08003338 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003339 if (mInterceptor->isEnabled()) {
3340 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003341 }
Irvel468051e2016-06-13 16:44:44 -07003342
Mathias Agopian386aa982011-11-07 21:58:03 -08003343 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003344 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3345 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003346 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003347
3348 // if this is a synchronous transaction, wait for it to take effect
3349 // before returning.
3350 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003351 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003352 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003353 if (flags & eAnimation) {
3354 mAnimTransactionPending = true;
3355 }
chaviw4fe36852019-04-15 16:25:49 -07003356 if (mPendingInputWindowCommands.syncInputWindows) {
3357 mPendingSyncInputWindows = true;
3358 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003359
3360 // applyTransactionState can be called by either the main SF thread or by
3361 // another process through setTransactionState. While a given process may wish
3362 // to wait on synchronous transactions, the main SF thread should never
3363 // be blocked. Therefore, we only wait if isMainThread is false.
3364 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003365 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3366 if (CC_UNLIKELY(err != NO_ERROR)) {
3367 // just in case something goes wrong in SF, return to the
3368 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003369 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3370 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003371 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003372 break;
3373 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003374 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003375 }
3376}
3377
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003378uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3379 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3380 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003381
Mathias Agopiane57f2922012-08-09 16:29:12 -07003382 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003383 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3384
3385 const uint32_t what = s.what;
3386 if (what & DisplayState::eSurfaceChanged) {
3387 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3388 state.surface = s.surface;
3389 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003390 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003391 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003392 if (what & DisplayState::eLayerStackChanged) {
3393 if (state.layerStack != s.layerStack) {
3394 state.layerStack = s.layerStack;
3395 flags |= eDisplayTransactionNeeded;
3396 }
3397 }
3398 if (what & DisplayState::eDisplayProjectionChanged) {
3399 if (state.orientation != s.orientation) {
3400 state.orientation = s.orientation;
3401 flags |= eDisplayTransactionNeeded;
3402 }
3403 if (state.frame != s.frame) {
3404 state.frame = s.frame;
3405 flags |= eDisplayTransactionNeeded;
3406 }
3407 if (state.viewport != s.viewport) {
3408 state.viewport = s.viewport;
3409 flags |= eDisplayTransactionNeeded;
3410 }
3411 }
3412 if (what & DisplayState::eDisplaySizeChanged) {
3413 if (state.width != s.width) {
3414 state.width = s.width;
3415 flags |= eDisplayTransactionNeeded;
3416 }
3417 if (state.height != s.height) {
3418 state.height = s.height;
3419 flags |= eDisplayTransactionNeeded;
3420 }
3421 }
3422
Mathias Agopiane57f2922012-08-09 16:29:12 -07003423 return flags;
3424}
3425
Robert Carr14167e02019-02-13 13:50:55 -08003426bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003427 IPCThreadState* ipc = IPCThreadState::self();
3428 const int pid = ipc->getCallingPid();
3429 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003430 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003431 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003432 return false;
3433 }
3434 return true;
3435}
3436
Marissa Wall3dad52d2019-03-22 14:03:19 -07003437uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003438 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3439 bool privileged,
3440 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003441 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003442
Valerie Hau9dab9732019-08-20 09:29:25 -07003443 for (auto& listener : s.listeners) {
3444 // note that startRegistration will not re-register if the listener has
3445 // already be registered for a prior surface control
3446 mTransactionCompletedThread.startRegistration(listener);
3447 listenerCallbacks.insert(listener);
3448 }
3449
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003450 sp<Layer> layer = nullptr;
3451 if (s.surface) {
3452 layer = fromHandle(s.surface);
3453 } else {
3454 // The client may provide us a null handle. Treat it as if the layer was removed.
3455 ALOGW("Attempt to set client state with a null layer handle");
3456 }
chaviw8b3871a2017-11-01 17:41:01 -07003457 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003458 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003459 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003460 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003461 }
chaviw8b3871a2017-11-01 17:41:01 -07003462 return 0;
3463 }
3464
chaviw8b3871a2017-11-01 17:41:01 -07003465 uint32_t flags = 0;
3466
Garfield Tan8a3083e2018-12-03 13:21:07 -08003467 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003468
3469 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3470 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003471 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003472 layer->pushPendingState();
3473 }
3474
Valerie Hau871d6352020-01-29 08:44:02 -08003475 // Only set by BLAST adapter layers
3476 if (what & layer_state_t::eProducerDisconnect) {
3477 layer->onDisconnect();
3478 }
3479
chaviw8b3871a2017-11-01 17:41:01 -07003480 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003481 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003482 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003483 }
chaviw8b3871a2017-11-01 17:41:01 -07003484 }
3485 if (what & layer_state_t::eLayerChanged) {
3486 // NOTE: index needs to be calculated before we update the state
3487 const auto& p = layer->getParent();
3488 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003489 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003490 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003491 mCurrentState.layersSortedByZ.removeAt(idx);
3492 mCurrentState.layersSortedByZ.add(layer);
3493 // we need traversal (state changed)
3494 // AND transaction (list changed)
3495 flags |= eTransactionNeeded|eTraversalNeeded;
3496 }
chaviw8b3871a2017-11-01 17:41:01 -07003497 } else {
3498 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003499 flags |= eTransactionNeeded|eTraversalNeeded;
3500 }
3501 }
chaviw8b3871a2017-11-01 17:41:01 -07003502 }
3503 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003504 // NOTE: index needs to be calculated before we update the state
3505 const auto& p = layer->getParent();
3506 if (p == nullptr) {
3507 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3508 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3509 mCurrentState.layersSortedByZ.removeAt(idx);
3510 mCurrentState.layersSortedByZ.add(layer);
3511 // we need traversal (state changed)
3512 // AND transaction (list changed)
3513 flags |= eTransactionNeeded|eTraversalNeeded;
3514 }
3515 } else {
3516 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3517 flags |= eTransactionNeeded|eTraversalNeeded;
3518 }
chaviw8b3871a2017-11-01 17:41:01 -07003519 }
3520 }
3521 if (what & layer_state_t::eSizeChanged) {
3522 if (layer->setSize(s.w, s.h)) {
3523 flags |= eTraversalNeeded;
3524 }
3525 }
3526 if (what & layer_state_t::eAlphaChanged) {
3527 if (layer->setAlpha(s.alpha))
3528 flags |= eTraversalNeeded;
3529 }
3530 if (what & layer_state_t::eColorChanged) {
3531 if (layer->setColor(s.color))
3532 flags |= eTraversalNeeded;
3533 }
Peiyong Lind3788632018-09-18 16:01:31 -07003534 if (what & layer_state_t::eColorTransformChanged) {
3535 if (layer->setColorTransform(s.colorTransform)) {
3536 flags |= eTraversalNeeded;
3537 }
3538 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003539 if (what & layer_state_t::eBackgroundColorChanged) {
3540 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3541 flags |= eTraversalNeeded;
3542 }
3543 }
chaviw8b3871a2017-11-01 17:41:01 -07003544 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003545 // TODO: b/109894387
3546 //
3547 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3548 // rotation. To see the problem observe that if we have a square parent, and a child
3549 // of the same size, then we rotate the child 45 degrees around it's center, the child
3550 // must now be cropped to a non rectangular 8 sided region.
3551 //
3552 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3553 // private API, and the WindowManager only uses rotation in one case, which is on a top
3554 // level layer in which cropping is not an issue.
3555 //
3556 // However given that abuse of rotation matrices could lead to surfaces extending outside
3557 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3558 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3559 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003560 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003561 flags |= eTraversalNeeded;
3562 }
3563 if (what & layer_state_t::eTransparentRegionChanged) {
3564 if (layer->setTransparentRegionHint(s.transparentRegion))
3565 flags |= eTraversalNeeded;
3566 }
3567 if (what & layer_state_t::eFlagsChanged) {
3568 if (layer->setFlags(s.flags, s.mask))
3569 flags |= eTraversalNeeded;
3570 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003571 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003572 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003573 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003574 if (what & layer_state_t::eCornerRadiusChanged) {
3575 if (layer->setCornerRadius(s.cornerRadius))
3576 flags |= eTraversalNeeded;
3577 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003578 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3579 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3580 }
chaviw8b3871a2017-11-01 17:41:01 -07003581 if (what & layer_state_t::eLayerStackChanged) {
3582 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3583 // We only allow setting layer stacks for top level layers,
3584 // everything else inherits layer stack from its parent.
3585 if (layer->hasParent()) {
3586 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003587 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003588 } else if (idx < 0) {
3589 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003590 "that also does not appear in the top level layer list. Something"
3591 " has gone wrong.",
3592 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003593 } else if (layer->setLayerStack(s.layerStack)) {
3594 mCurrentState.layersSortedByZ.removeAt(idx);
3595 mCurrentState.layersSortedByZ.add(layer);
3596 // we need traversal (state changed)
3597 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003598 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003599 }
3600 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003601 if (what & layer_state_t::eDeferTransaction_legacy) {
3602 if (s.barrierHandle_legacy != nullptr) {
3603 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3604 } else if (s.barrierGbp_legacy != nullptr) {
3605 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003606 if (authenticateSurfaceTextureLocked(gbp)) {
3607 const auto& otherLayer =
3608 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003609 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003610 } else {
3611 ALOGE("Attempt to defer transaction to to an"
3612 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003613 }
3614 }
chaviw8b3871a2017-11-01 17:41:01 -07003615 // We don't trigger a traversal here because if no other state is
3616 // changed, we don't want this to cause any more work
3617 }
chaviw8b3871a2017-11-01 17:41:01 -07003618 if (what & layer_state_t::eReparentChildren) {
3619 if (layer->reparentChildren(s.reparentHandle)) {
3620 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003621 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003622 }
chaviw8b3871a2017-11-01 17:41:01 -07003623 if (what & layer_state_t::eDetachChildren) {
3624 layer->detachChildren();
3625 }
3626 if (what & layer_state_t::eOverrideScalingModeChanged) {
3627 layer->setOverrideScalingMode(s.overrideScalingMode);
3628 // We don't trigger a traversal here because if no other state is
3629 // changed, we don't want this to cause any more work
3630 }
Marissa Wall61c58622018-07-18 10:12:20 -07003631 if (what & layer_state_t::eTransformChanged) {
3632 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3633 }
3634 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3635 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3636 flags |= eTraversalNeeded;
3637 }
3638 if (what & layer_state_t::eCropChanged) {
3639 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3640 }
Marissa Wall861616d2018-10-22 12:52:23 -07003641 if (what & layer_state_t::eFrameChanged) {
3642 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3643 }
Marissa Wall61c58622018-07-18 10:12:20 -07003644 if (what & layer_state_t::eAcquireFenceChanged) {
3645 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3646 }
3647 if (what & layer_state_t::eDataspaceChanged) {
3648 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3649 }
3650 if (what & layer_state_t::eHdrMetadataChanged) {
3651 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3652 }
3653 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3654 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3655 }
3656 if (what & layer_state_t::eApiChanged) {
3657 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3658 }
3659 if (what & layer_state_t::eSidebandStreamChanged) {
3660 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3661 }
Robert Carr720e5062018-07-30 17:45:14 -07003662 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003663 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003664 layer->setInputInfo(s.inputInfo);
3665 flags |= eTraversalNeeded;
3666 } else {
3667 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3668 }
Robert Carr720e5062018-07-30 17:45:14 -07003669 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003670 if (what & layer_state_t::eMetadataChanged) {
3671 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3672 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003673 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3674 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3675 flags |= eTraversalNeeded;
3676 }
3677 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003678 if (what & layer_state_t::eShadowRadiusChanged) {
3679 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3680 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003681 if (what & layer_state_t::eFrameRateSelectionPriority) {
3682 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3683 flags |= eTraversalNeeded;
3684 }
3685 }
Steven Thomas3172e202020-01-06 19:25:30 -08003686 if (what & layer_state_t::eFrameRateChanged) {
Steven Thomas62a4cf82020-01-31 12:04:03 -08003687 if (ValidateFrameRate(s.frameRate, s.frameRateCompatibility,
3688 "SurfaceFlinger::setClientStateLocked") &&
3689 layer->setFrameRate(Layer::FrameRate(s.frameRate,
3690 Layer::FrameRate::convertCompatibility(
3691 s.frameRateCompatibility)))) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003692 flags |= eTraversalNeeded;
Steven Thomas62a4cf82020-01-31 12:04:03 -08003693 }
Steven Thomas3172e202020-01-06 19:25:30 -08003694 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003695 // This has to happen after we reparent children because when we reparent to null we remove
3696 // child layers from current state and remove its relative z. If the children are reparented in
3697 // the same transaction, then we have to make sure we reparent the children first so we do not
3698 // lose its relative z order.
3699 if (what & layer_state_t::eReparent) {
3700 bool hadParent = layer->hasParent();
3701 if (layer->reparent(s.parentHandleForChild)) {
3702 if (!hadParent) {
3703 mCurrentState.layersSortedByZ.remove(layer);
3704 }
3705 flags |= eTransactionNeeded | eTraversalNeeded;
3706 }
3707 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003708 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003709 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3710 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003711 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3712 }
3713 }
Marissa Wall78b72202019-03-15 14:58:34 -07003714 bool bufferChanged = what & layer_state_t::eBufferChanged;
3715 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3716 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003717 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003718 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003719 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3720 if (success) {
3721 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3722 success = ClientCache::getInstance()
3723 .registerErasedRecipient(s.cachedBuffer,
3724 wp<ClientCache::ErasedRecipient>(this));
3725 if (!success) {
3726 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3727 }
3728 }
Marissa Wall78b72202019-03-15 14:58:34 -07003729 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003730 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003731 } else if (bufferChanged) {
3732 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003733 }
Marissa Wall78b72202019-03-15 14:58:34 -07003734 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003735 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3736 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003737 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003738 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003739 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003740 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3741 // Do not put anything that updates layer state or modifies flags after
3742 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003743 return flags;
3744}
3745
chaviw273171b2018-12-26 11:46:30 -08003746uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3747 uint32_t flags = 0;
3748 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3749 flags |= eTraversalNeeded;
3750 }
3751
chaviwa911b102019-02-14 10:18:33 -08003752 if (inputWindowCommands.syncInputWindows) {
3753 flags |= eTraversalNeeded;
3754 }
3755
Vishnu Nairec0ab382019-02-13 15:32:56 -08003756 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003757 return flags;
3758}
3759
chaviwfe94a222019-08-21 13:52:59 -07003760status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3761 sp<IBinder>* outHandle) {
3762 if (!mirrorFromHandle) {
3763 return NAME_NOT_FOUND;
3764 }
3765
3766 sp<Layer> mirrorLayer;
3767 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003768 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003769
3770 {
3771 Mutex::Autolock _l(mStateLock);
3772 mirrorFrom = fromHandle(mirrorFromHandle);
3773 if (!mirrorFrom) {
3774 return NAME_NOT_FOUND;
3775 }
3776
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003777 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3778 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003779 if (result != NO_ERROR) {
3780 return result;
3781 }
3782
3783 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3784 }
3785
3786 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3787}
3788
Marissa Wall2d814fb2019-04-09 18:52:57 +00003789status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3790 uint32_t h, PixelFormat format, uint32_t flags,
3791 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003792 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003793 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3794 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003795 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003796 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003797 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003798 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003799 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003800
Robert Carrc0df3122019-04-11 13:18:21 -07003801 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3802 "Expected only one of parentLayer or parentHandle to be non-null. "
3803 "Programmer error?");
3804
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003805 status_t result = NO_ERROR;
3806
3807 sp<Layer> layer;
3808
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003809 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003810
Evan Roskya1f1e152019-01-24 16:17:46 -08003811 bool primaryDisplayOnly = false;
3812
3813 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3814 // TODO b/64227542
3815 if (metadata.has(METADATA_WINDOW_TYPE)) {
3816 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3817 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003818 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003819 primaryDisplayOnly = true;
3820 }
3821 }
3822
Mathias Agopian3165cc22012-08-08 19:42:09 -07003823 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003824 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003825 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3826 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003827
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003828 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003829 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003830 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003831 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003832 break;
Vishnu Nairfa247b12020-02-11 08:58:26 -08003833 case ISurfaceComposerClient::eFXSurfaceEffect:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003834 // check if buffer size is set for color layer.
3835 if (w > 0 || h > 0) {
3836 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3837 int(w), int(h));
3838 return BAD_VALUE;
3839 }
3840
Vishnu Nairfa247b12020-02-11 08:58:26 -08003841 result = createEffectLayer(client, std::move(uniqueName), w, h, flags,
3842 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003843 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003844 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003845 // check if buffer size is set for container layer.
3846 if (w > 0 || h > 0) {
3847 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3848 int(w), int(h));
3849 return BAD_VALUE;
3850 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003851 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3852 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003853 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003854 default:
3855 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003856 break;
3857 }
3858
Dan Stoza7d89d062015-04-30 13:29:25 -07003859 if (result != NO_ERROR) {
3860 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003861 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003862
Evan Roskya1f1e152019-01-24 16:17:46 -08003863 if (primaryDisplayOnly) {
3864 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003865 }
3866
Robert Carrb89ea9d2018-12-10 13:01:14 -08003867 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003868 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3869 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003870 if (result != NO_ERROR) {
3871 return result;
3872 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003873 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003874
3875 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003876 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003877}
3878
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003879std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3880 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003881
3882 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003883 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003884
Dan Stoza436ccf32018-06-21 12:10:12 -07003885 // Grab the state lock since we're accessing mCurrentState
3886 Mutex::Autolock lock(mStateLock);
3887
Cody Northropbc755282017-03-31 12:00:08 -06003888 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003889 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003890 while (matchFound) {
3891 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003892 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003893 if (layer->getName() == uniqueName) {
3894 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003895 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003896 }
3897 });
3898 }
3899
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003900 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003901 return uniqueName;
3902}
3903
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003904status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003905 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003906 LayerMetadata metadata, PixelFormat& format,
3907 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003908 sp<IGraphicBufferProducer>* gbp,
3909 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003910 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003911 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003912 case PIXEL_FORMAT_TRANSPARENT:
3913 case PIXEL_FORMAT_TRANSLUCENT:
3914 format = PIXEL_FORMAT_RGBA_8888;
3915 break;
3916 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003917 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003918 break;
3919 }
3920
chaviwb4c6e582019-08-16 14:35:07 -07003921 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003922 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003923 args.textureName = getNewTexture();
3924 {
3925 // Grab the SF state lock during this since it's the only safe way to access
3926 // RenderEngine when creating a BufferLayerConsumer
3927 // TODO: Check if this lock is still needed here
3928 Mutex::Autolock lock(mStateLock);
3929 layer = getFactory().createBufferQueueLayer(args);
3930 }
3931
Marissa Wallfd668622018-05-10 10:21:13 -07003932 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003933 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003934 *handle = layer->getHandle();
3935 *gbp = layer->getProducer();
3936 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003937 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003938
Marissa Wallfd668622018-05-10 10:21:13 -07003939 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003940 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003941}
3942
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003943status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003944 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003945 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003946 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003947 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003948 args.displayDevice = getDefaultDisplayDevice();
3949 args.textureName = getNewTexture();
3950 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003951 if (outTransformHint) {
3952 *outTransformHint = layer->getTransformHint();
3953 }
Marissa Wall61c58622018-07-18 10:12:20 -07003954 *handle = layer->getHandle();
3955 *outLayer = layer;
3956
3957 return NO_ERROR;
3958}
3959
Vishnu Nairfa247b12020-02-11 08:58:26 -08003960status_t SurfaceFlinger::createEffectLayer(const sp<Client>& client, std::string name, uint32_t w,
3961 uint32_t h, uint32_t flags, LayerMetadata metadata,
3962 sp<IBinder>* handle, sp<Layer>* outLayer) {
3963 *outLayer = getFactory().createEffectLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003964 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003965 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003966 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003967}
3968
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003969status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003970 uint32_t w, uint32_t h, uint32_t flags,
3971 LayerMetadata metadata, sp<IBinder>* handle,
3972 sp<Layer>* outLayer) {
3973 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003974 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003975 *handle = (*outLayer)->getHandle();
3976 return NO_ERROR;
3977}
3978
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003979void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003980 mLayersPendingRemoval.add(layer);
3981 mLayersRemoved = true;
3982 setTransactionFlags(eTransactionNeeded);
3983}
3984
Robert Carr695d5282018-12-18 15:27:58 -08003985void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003986{
Robert Carr2e102c92018-10-23 12:11:15 -07003987 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003988 // If a layer has a parent, we allow it to out-live it's handle
3989 // with the idea that the parent holds a reference and will eventually
3990 // be cleaned up. However no one cleans up the top-level so we do so
3991 // here.
3992 if (layer->getParent() == nullptr) {
3993 mCurrentState.layersSortedByZ.remove(layer);
3994 }
3995 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003996
3997 auto it = mLayersByLocalBinderToken.begin();
3998 while (it != mLayersByLocalBinderToken.end()) {
3999 if (it->second == layer) {
4000 it = mLayersByLocalBinderToken.erase(it);
4001 } else {
4002 it++;
4003 }
4004 }
4005
Robert Carr695d5282018-12-18 15:27:58 -08004006 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00004007}
4008
Mathias Agopianb60314a2012-04-10 22:09:54 -07004009// ---------------------------------------------------------------------------
4010
Andy McFadden13a082e2012-08-24 10:16:42 -07004011void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004012 const auto display = getDefaultDisplayDeviceLocked();
4013 if (!display) return;
4014
4015 const sp<IBinder> token = display->getDisplayToken().promote();
4016 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004017
Jesse Hall01e29052013-02-19 16:13:35 -08004018 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07004019 Vector<ComposerState> state;
4020 Vector<DisplayState> displays;
4021 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08004022 d.what = DisplayState::eDisplayProjectionChanged |
4023 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08004024 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08004025 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08004026 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07004027 d.frame.makeInvalid();
4028 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07004029 d.width = 0;
4030 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07004031 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07004032 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
4033 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07004034
Dominik Laskowskie9774092018-12-11 10:04:24 -08004035 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004036
Dominik Laskowski83b88212018-12-11 13:34:06 -08004037 const nsecs_t vsyncPeriod = getVsyncPeriod();
4038 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08004039
Brian Andersond0010582017-03-07 13:20:31 -08004040 // Use phase of 0 since phase is not known.
4041 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004042 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07004043 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07004044}
4045
4046void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07004047 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08004048 postMessageAsync(
4049 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07004050}
4051
Ady Abraham27c70212019-06-11 10:52:26 -07004052void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
4053 if (mHWCVsyncState != enabled) {
4054 getHwComposer().setVsyncEnabled(displayId, enabled);
4055 mHWCVsyncState = enabled;
4056 }
4057}
4058
Dominik Laskowskie9774092018-12-11 10:04:24 -08004059void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004060 if (display->isVirtual()) {
4061 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004062 return;
4063 }
4064
Dominik Laskowski075d3172018-05-24 15:50:06 -07004065 const auto displayId = display->getId();
4066 LOG_ALWAYS_FATAL_IF(!displayId);
4067
Dominik Laskowski34157762018-10-31 13:07:19 -07004068 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004069
4070 int currentMode = display->getPowerMode();
4071 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004072 return;
4073 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004074
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004075 display->setPowerMode(mode);
4076
Lloyd Pique4dccc412018-01-22 17:21:36 -08004077 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004078 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07004079 }
4080
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004081 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004082 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004083 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07004084 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08004085 mScheduler->onScreenAcquired(mAppConnectionHandle);
4086 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004087 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004088
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004089 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08004090 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004091 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07004092
4093 struct sched_param param = {0};
4094 param.sched_priority = 1;
4095 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
4096 ALOGW("Couldn't set SCHED_FIFO on display on");
4097 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004098 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07004099 // Turn off the display
4100 struct sched_param param = {0};
4101 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
4102 ALOGW("Couldn't set SCHED_OTHER on display off");
4103 }
4104
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004105 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004106 mScheduler->disableHardwareVsync(true);
4107 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07004108 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004109
Ady Abraham27c70212019-06-11 10:52:26 -07004110 // Make sure HWVsync is disabled before turning off the display
4111 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
4112
Dominik Laskowski075d3172018-05-24 15:50:06 -07004113 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004114 mVisibleRegionsDirty = true;
4115 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07004116 } else if (mode == HWC_POWER_MODE_DOZE ||
4117 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004118 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07004119 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004120 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08004121 mScheduler->onScreenAcquired(mAppConnectionHandle);
4122 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004123 }
4124 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
4125 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004126 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08004127 mScheduler->disableHardwareVsync(true);
4128 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01004129 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07004130 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07004131 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07004132 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07004133 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004134 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004135
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004136 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08004137 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004138 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07004139 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07004140 }
4141
Dominik Laskowski34157762018-10-31 13:07:19 -07004142 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004143}
4144
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004145void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004146 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004147 const auto display = getDisplayDevice(displayToken);
4148 if (!display) {
4149 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4150 displayToken.get());
4151 } else if (display->isVirtual()) {
4152 ALOGW("Attempt to set power mode %d for virtual display", mode);
4153 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004154 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004155 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004156 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004157}
4158
4159// ---------------------------------------------------------------------------
4160
Dominik Laskowskic2867142019-01-21 11:33:38 -08004161status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4162 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004163 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004164
Mathias Agopianbd115332013-04-18 16:41:04 -07004165 IPCThreadState* ipc = IPCThreadState::self();
4166 const int pid = ipc->getCallingPid();
4167 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004168
Mathias Agopianbd115332013-04-18 16:41:04 -07004169 if ((uid != AID_SHELL) &&
4170 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004171 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4172 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004173 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004174 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004175 // (this would indicate SF is stuck, but we want to be able to
4176 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004177 status_t err = mStateLock.timedLock(s2ns(1));
4178 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004179 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004180 StringAppendF(&result,
4181 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4182 "(no locks held)\n",
4183 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004184 }
4185
Dominik Laskowskic2867142019-01-21 11:33:38 -08004186 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004187 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004188 {"--dispsync"s,
4189 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004190 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004191 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4192 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4193 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4194 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4195 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4196 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004197 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004198 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4199 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004200
Dominik Laskowskic2867142019-01-21 11:33:38 -08004201 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004202
Dominik Laskowski46470112019-08-02 13:13:11 -07004203 const auto it = dumpers.find(flag);
4204 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004205 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004206 } else if (!asProto) {
4207 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004208 }
4209
Mathias Agopian9795c422009-08-26 16:36:26 -07004210 if (locked) {
4211 mStateLock.unlock();
4212 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004213
Dominik Laskowski46470112019-08-02 13:13:11 -07004214 if (it == dumpers.end()) {
4215 const LayersProto layersProto = dumpProtoFromMainThread();
4216 if (asProto) {
4217 result.append(layersProto.SerializeAsString());
4218 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004219 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004220 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4221 result.append(LayerProtoParser::layerTreeToString(layerTree));
4222 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004223 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004224 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004225 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004226 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004227 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004228 return NO_ERROR;
4229}
4230
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004231status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4232 if (asProto && mTracing.isEnabled()) {
4233 mTracing.writeToFileAsync();
4234 }
4235
4236 return doDump(fd, DumpArgs(), asProto);
4237}
4238
Dominik Laskowskic2867142019-01-21 11:33:38 -08004239void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004240 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004241 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004242}
4243
Dominik Laskowskic2867142019-01-21 11:33:38 -08004244void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004245 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004246
Dominik Laskowskic2867142019-01-21 11:33:38 -08004247 if (args.size() > 1) {
4248 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004249 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004250 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004251 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004252 }
Robert Carr2047fae2016-11-28 14:09:09 -08004253 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004254 } else {
4255 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004256 }
4257}
4258
Dominik Laskowskic2867142019-01-21 11:33:38 -08004259void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004260 const bool clearAll = args.size() < 2;
4261 const auto name = clearAll ? String8() : String8(args[1]);
4262
Edgar Arriaga844fa672020-01-16 14:21:42 -08004263 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004264 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004265 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004266 }
Robert Carr2047fae2016-11-28 14:09:09 -08004267 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004268
Svetoslavd85084b2014-03-20 10:28:31 -07004269 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004270}
4271
Dominik Laskowskic2867142019-01-21 11:33:38 -08004272void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4273 mTimeStats->parseArgs(asProto, args, result);
4274}
4275
Jamie Gennis6547ff42013-07-16 20:12:42 -07004276// This should only be called from the main thread. Otherwise it would need
4277// the lock and should use mCurrentState rather than mDrawingState.
4278void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004279 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004280 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004281 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004282
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004283 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004284}
4285
Yiwei Zhang5434a782018-12-05 18:06:32 -08004286void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004287 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004288
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004289 if (isLayerTripleBufferingDisabled())
4290 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004291
Yiwei Zhang5434a782018-12-05 18:06:32 -08004292 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4293 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4294 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4295 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4296 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4297 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004298 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004299}
4300
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004301void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004302 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004303
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004304 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004305 result.append("\n");
4306
Ady Abraham9e16a482019-12-03 17:19:41 -08004307 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004308 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004309 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004310 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004311
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004312 HwcConfigIndexType defaultConfig;
4313 float minFps, maxFps;
4314 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004315 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004316 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004317 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004318 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004319 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4320 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004321
Ana Krulecc2870422019-01-29 19:00:58 -08004322 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004323}
4324
Yiwei Zhang5434a782018-12-05 18:06:32 -08004325void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4326 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004327 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4328 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004329 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004330 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004331 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004332 }
David Sodman4a36e932017-11-07 14:29:47 -08004333 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004334 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004335 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004336 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4337 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004338}
4339
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004340void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4341 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004342 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4343 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004344 for (const auto& segment : history) {
4345 if (!segment.usedThirdBuffer) {
4346 stats.twoBufferTime += segment.totalTime;
4347 }
4348 if (segment.occupancyAverage < 1.0f) {
4349 stats.doubleBufferedTime += segment.totalTime;
4350 } else if (segment.occupancyAverage < 2.0f) {
4351 stats.tripleBufferedTime += segment.totalTime;
4352 }
4353 ++stats.numSegments;
4354 stats.totalTime += segment.totalTime;
4355 }
4356}
4357
Yiwei Zhang5434a782018-12-05 18:06:32 -08004358void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4359 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004360
4361 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4362 const size_t count = currentLayers.size();
4363 for (size_t i=0 ; i<count ; i++) {
4364 currentLayers[i]->dumpFrameEvents(result);
4365 }
4366}
4367
Yiwei Zhang5434a782018-12-05 18:06:32 -08004368void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004369 result.append("Buffering stats:\n");
4370 result.append(" [Layer name] <Active time> <Two buffer> "
4371 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004372 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004373 typedef std::tuple<std::string, float, float, float> BufferTuple;
4374 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004375 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004376 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004377 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004378 if (stats.numSegments == 0) {
4379 continue;
4380 }
4381 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4382 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4383 stats.totalTime;
4384 float doubleBufferRatio = static_cast<float>(
4385 stats.doubleBufferedTime) / stats.totalTime;
4386 float tripleBufferRatio = static_cast<float>(
4387 stats.tripleBufferedTime) / stats.totalTime;
4388 sorted.insert({activeTime, {name, twoBufferRatio,
4389 doubleBufferRatio, tripleBufferRatio}});
4390 }
4391 for (const auto& sortedPair : sorted) {
4392 float activeTime = sortedPair.first;
4393 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004394 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4395 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004396 }
4397 result.append("\n");
4398}
4399
Yiwei Zhang5434a782018-12-05 18:06:32 -08004400void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004401 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004402 const auto displayId = display->getId();
4403 if (!displayId) {
4404 continue;
4405 }
4406 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004407 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004408 continue;
4409 }
4410
Yiwei Zhang5434a782018-12-05 18:06:32 -08004411 StringAppendF(&result,
4412 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4413 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004414 uint8_t port;
4415 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004416 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004417 result.append("no identification data\n");
4418 continue;
4419 }
4420
4421 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004422 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004423 continue;
4424 }
4425
4426 const auto edid = parseEdid(data);
4427 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004428 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004429 continue;
4430 }
4431
Yiwei Zhang5434a782018-12-05 18:06:32 -08004432 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004433 result.append(edid->displayName.data(), edid->displayName.length());
4434 result.append("\"\n");
4435 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004436}
4437
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004438void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4439 std::string& result) const {
4440 hwc2_display_t hwcDisplayId;
4441 uint8_t port;
4442 DisplayIdentificationData data;
4443
4444 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4445 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4446 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4447 }
4448}
4449
Yiwei Zhang5434a782018-12-05 18:06:32 -08004450void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004451 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004452 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4453 StringAppendF(&result, "DisplayColorSetting: %s\n",
4454 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004455
4456 // TODO: print out if wide-color mode is active or not
4457
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004458 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004459 const auto displayId = display->getId();
4460 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004461 continue;
4462 }
4463
Yiwei Zhang5434a782018-12-05 18:06:32 -08004464 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004465 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004466 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004467 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004468 }
4469
Lloyd Pique32cbe282018-10-19 13:09:22 -07004470 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004471 StringAppendF(&result, " Current color mode: %s (%d)\n",
4472 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004473 }
4474 result.append("\n");
4475}
4476
Vishnu Nair8406fd72019-07-30 11:29:31 -07004477LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
Alec Mouri6b9e9912020-01-21 10:50:24 -08004478 Mutex::Autolock _l(mStateLock);
4479 const auto device = getDefaultDisplayDeviceLocked();
chaviw1d044282017-09-27 12:19:28 -07004480 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004481 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
Alec Mouri6b9e9912020-01-21 10:50:24 -08004482 layer->writeToProto(layersProto, traceFlags, device);
chaviw08f3cb22020-01-13 13:17:21 -08004483 }
Alec Mouri6b9e9912020-01-21 10:50:24 -08004484
chaviw1d044282017-09-27 12:19:28 -07004485 return layersProto;
4486}
4487
Alec Mouri6b9e9912020-01-21 10:50:24 -08004488void SurfaceFlinger::dumpHwc(std::string& result) const {
4489 getHwComposer().dump(result);
4490}
4491
Vishnu Nair0f085c62019-08-30 08:49:12 -07004492void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4493 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4494 // it.
4495 LayerProto* rootProto = layersProto.add_layers();
4496 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4497 rootProto->set_id(offscreenRootLayerId);
4498 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004499 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004500
4501 for (Layer* offscreenLayer : mOffscreenLayers) {
4502 // Add layer as child of the fake root
4503 rootProto->add_children(offscreenLayer->sequence);
4504
4505 // Add layer
Alec Mouri6b9e9912020-01-21 10:50:24 -08004506 LayerProto* layerProto =
4507 offscreenLayer->writeToProto(layersProto, traceFlags, nullptr /*device*/);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004508 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004509 }
4510}
4511
Vishnu Nair8406fd72019-07-30 11:29:31 -07004512LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4513 LayersProto layersProto;
4514 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4515 return layersProto;
4516}
4517
Vishnu Nair0f085c62019-08-30 08:49:12 -07004518void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4519 result.append("Offscreen Layers:\n");
4520 postMessageSync(new LambdaMessage([&]() {
4521 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004522 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004523 layer->dumpCallingUidPid(result);
4524 });
4525 }
4526 }));
4527}
4528
Dominik Laskowskic2867142019-01-21 11:33:38 -08004529void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4530 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004531 Colorizer colorizer(colorize);
4532
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004533 // figure out if we're stuck somewhere
4534 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004535 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004536 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4537
4538 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004539 * Dump library configuration.
4540 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004541
4542 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004543 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004544 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004545 appendSfConfigString(result);
4546 appendUiConfigString(result);
4547 appendGuiConfigString(result);
4548 result.append("\n");
4549
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004550 result.append("\nDisplay identification data:\n");
4551 dumpDisplayIdentificationData(result);
4552
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004553 result.append("\nWide-Color information:\n");
4554 dumpWideColorInfo(result);
4555
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004556 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004557 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004558 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004559 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004560 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004561
Andy McFadden41d67d72014-04-25 16:58:34 -07004562 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004563 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004564 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004565 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004566 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004567
Dan Stozab90cf072015-03-05 11:05:59 -08004568 dumpStaticScreenStats(result);
4569 result.append("\n");
4570
Alec Mouri40189b02019-03-05 15:07:54 -08004571 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4572 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4573 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004574
Dan Stozae77c7662016-05-13 11:37:28 -07004575 dumpBufferingStats(result);
4576
Andy McFadden4803b742012-09-24 19:07:20 -07004577 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004578 * Dump the visible layer list
4579 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004580 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004581 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004582 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4583 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004584 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004585
Chia-I Wu2f884132018-09-13 15:17:58 -07004586 {
Lloyd Pique207def92019-02-28 16:09:52 -08004587 StringAppendF(&result, "Composition layers\n");
4588 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Piquede196652020-01-22 17:29:58 -08004589 auto* compositionState = layer->getCompositionState();
4590 if (!compositionState) return;
4591
4592 android::base::StringAppendF(&result, "* Layer %p (%s)\n", layer,
4593 layer->getDebugName() ? layer->getDebugName()
4594 : "<unknown>");
4595 compositionState->dump(result);
Lloyd Pique207def92019-02-28 16:09:52 -08004596 });
4597 }
4598
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004599 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004600 * Dump Display state
4601 */
4602
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004603 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004604 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004605 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004606 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004607 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004608 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004609 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004610
4611 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004612 * Dump CompositionEngine state
4613 */
4614
4615 mCompositionEngine->dump(result);
4616
4617 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004618 * Dump SurfaceFlinger global state
4619 */
4620
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004621 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004622 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004623 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004624
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004625 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004626
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004627 DebugEGLImageTracker::getInstance()->dump(result);
4628
Dominik Laskowski075d3172018-05-24 15:50:06 -07004629 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004630 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4631 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004632 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4633 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004634 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004635 StringAppendF(&result,
4636 " transaction-flags : %08x\n"
4637 " gpu_to_cpu_unsupported : %d\n",
4638 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004639
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004640 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004641 displayId && getHwComposer().isConnected(*displayId)) {
4642 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004643 StringAppendF(&result,
4644 " refresh-rate : %f fps\n"
4645 " x-dpi : %f\n"
4646 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004647 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4648 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004649 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004650
Yiwei Zhang5434a782018-12-05 18:06:32 -08004651 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004652
Dan Stozae22aec72016-08-01 13:20:59 -07004653 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004654 * Tracing state
4655 */
4656 mTracing.dump(result);
4657 result.append("\n");
4658
4659 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004660 * HWC layer minidump
4661 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004662 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004663 const auto displayId = display->getId();
4664 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004665 continue;
4666 }
4667
Yiwei Zhang5434a782018-12-05 18:06:32 -08004668 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004669 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004670 const sp<DisplayDevice> displayDevice = display;
4671 mCurrentState.traverseInZOrder(
4672 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004673 result.append("\n");
4674 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004675
4676 /*
4677 * Dump HWComposer state
4678 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004679 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004680 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004681 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004682 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004683 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004684 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004685
4686 /*
4687 * Dump gralloc state
4688 */
4689 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4690 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004691
4692 /*
4693 * Dump VrFlinger state if in use.
4694 */
4695 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4696 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004697 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004698 result.append("\n");
4699 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004700
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004701 result.append(mTimeStats->miniDump());
4702 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004703}
4704
Chia-I Wu28f320b2018-05-03 11:02:56 -07004705void SurfaceFlinger::updateColorMatrixLocked() {
4706 mat4 colorMatrix;
4707 if (mGlobalSaturationFactor != 1.0f) {
4708 // Rec.709 luma coefficients
4709 float3 luminance{0.213f, 0.715f, 0.072f};
4710 luminance *= 1.0f - mGlobalSaturationFactor;
4711 mat4 saturationMatrix = mat4(
4712 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4713 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4714 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4715 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4716 );
4717 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4718 } else {
4719 colorMatrix = mClientColorMatrix * mDaltonizer();
4720 }
4721
4722 if (mCurrentState.colorMatrix != colorMatrix) {
4723 mCurrentState.colorMatrix = colorMatrix;
4724 mCurrentState.colorMatrixChanged = true;
4725 setTransactionFlags(eTransactionNeeded);
4726 }
4727}
4728
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004729status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004730#pragma clang diagnostic push
4731#pragma clang diagnostic error "-Wswitch-enum"
4732 switch (static_cast<ISurfaceComposerTag>(code)) {
4733 // These methods should at minimum make sure that the client requested
4734 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004735 case BOOT_FINISHED:
4736 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004737 case CREATE_DISPLAY:
4738 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004739 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004740 case GET_ANIMATION_FRAME_STATS:
4741 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004742 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004743 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004744 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004745 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4746 case SET_AUTO_LOW_LATENCY_MODE:
4747 case GET_GAME_CONTENT_TYPE_SUPPORT:
4748 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004749 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004750 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004751 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004752 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004753 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004754 case NOTIFY_POWER_HINT:
4755 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004756 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4757 IPCThreadState* ipc = IPCThreadState::self();
4758 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4759 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004760 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004761 }
Robert Carr1db73f62016-12-21 12:58:51 -08004762 return OK;
4763 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004764 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004765 IPCThreadState* ipc = IPCThreadState::self();
4766 const int pid = ipc->getCallingPid();
4767 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004768 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4769 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004770 return PERMISSION_DENIED;
4771 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004772 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004773 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004774 // Used by apps to hook Choreographer to SurfaceFlinger.
4775 case CREATE_DISPLAY_EVENT_CONNECTION:
4776 // The following calls are currently used by clients that do not
4777 // request necessary permissions. However, they do not expose any secret
4778 // information, so it is OK to pass them.
4779 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004780 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004781 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004782 case GET_PHYSICAL_DISPLAY_IDS:
4783 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004784 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004785 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004786 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004787 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004788 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004789 case GET_DISPLAY_STATS:
4790 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4791 // Calling setTransactionState is safe, because you need to have been
4792 // granted a reference to Client* and Handle* to do anything with it.
4793 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004794 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004795 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004796 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004797 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004798 case IS_WIDE_COLOR_DISPLAY:
Steven Thomas62a4cf82020-01-31 12:04:03 -08004799 // setFrameRate() is deliberately available for apps to call without any
4800 // special permissions.
4801 case SET_FRAME_RATE:
Dan Gittik57e63c52019-01-18 16:37:54 +00004802 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4803 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004804 return OK;
4805 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004806 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004807 case CAPTURE_SCREEN:
4808 case ADD_REGION_SAMPLING_LISTENER:
4809 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004810 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004811 IPCThreadState* ipc = IPCThreadState::self();
4812 const int pid = ipc->getCallingPid();
4813 const int uid = ipc->getCallingUid();
4814 if ((uid != AID_GRAPHICS) &&
4815 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4816 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4817 return PERMISSION_DENIED;
4818 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004819 return OK;
4820 }
chaviw93df2ea2019-04-30 16:45:12 -07004821 case CAPTURE_SCREEN_BY_ID: {
4822 IPCThreadState* ipc = IPCThreadState::self();
4823 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004824 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004825 return OK;
4826 }
4827 return PERMISSION_DENIED;
4828 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004829 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004830
4831 // These codes are used for the IBinder protocol to either interrogate the recipient
4832 // side of the transaction for its canonical interface descriptor or to dump its state.
4833 // We let them pass by default.
4834 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4835 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4836 code == IBinder::SYSPROPS_TRANSACTION) {
4837 return OK;
4838 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004839 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004840 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004841 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004842 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4843 return OK;
4844 }
4845 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4846 return PERMISSION_DENIED;
4847#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004848}
4849
Ana Krulec13be8ad2018-08-21 02:43:56 +00004850status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4851 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004852 status_t credentialCheck = CheckTransactCodeCredentials(code);
4853 if (credentialCheck != OK) {
4854 return credentialCheck;
4855 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004856
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004857 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4858 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004859 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004860 IPCThreadState* ipc = IPCThreadState::self();
4861 const int uid = ipc->getCallingUid();
4862 if (CC_UNLIKELY(uid != AID_SYSTEM
4863 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004864 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004865 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004866 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004867 return PERMISSION_DENIED;
4868 }
4869 int n;
4870 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004871 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004872 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004873 return NO_ERROR;
4874 case 1002: // SHOW_UPDATES
4875 n = data.readInt32();
4876 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004877 invalidateHwcGeometry();
4878 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004879 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004880 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004881 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004882 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004883 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004884 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004885 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004886 setTransactionFlags(
4887 eTransactionNeeded|
4888 eDisplayTransactionNeeded|
4889 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004890 return NO_ERROR;
4891 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004892 case 1006:{ // send empty update
4893 signalRefresh();
4894 return NO_ERROR;
4895 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004896 case 1008: // toggle use of hw composer
4897 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004898 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004899 invalidateHwcGeometry();
4900 repaintEverything();
4901 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004902 case 1009: // toggle use of transform hint
4903 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004904 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004905 invalidateHwcGeometry();
4906 repaintEverything();
4907 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004908 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004909 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004910 reply->writeInt32(0);
4911 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004912 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004913 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004914 return NO_ERROR;
4915 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004916 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004917 if (!display) {
4918 return NAME_NOT_FOUND;
4919 }
4920
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004921 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004922 return NO_ERROR;
4923 }
4924 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004925 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004926 // daltonize
4927 n = data.readInt32();
4928 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004929 case 1:
4930 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4931 break;
4932 case 2:
4933 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4934 break;
4935 case 3:
4936 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4937 break;
4938 default:
4939 mDaltonizer.setType(ColorBlindnessType::None);
4940 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004941 }
4942 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004943 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004944 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004945 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004946 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004947
4948 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004949 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004950 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004951 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004952 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004953 // apply a color matrix
4954 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004955 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004956 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004957 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004958 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004959 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004960 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004961 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004962 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004963 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004964 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004965
4966 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4967 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004968 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004969 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4970 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4971 }
4972
Chia-I Wu28f320b2018-05-03 11:02:56 -07004973 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004974 return NO_ERROR;
4975 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004976 case 1016: { // Unused.
4977 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004978 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004979 case 1017: {
4980 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004981 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004982 return NO_ERROR;
4983 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004984 case 1018: { // Modify Choreographer's phase offset
4985 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004986 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004987 return NO_ERROR;
4988 }
4989 case 1019: { // Modify SurfaceFlinger's phase offset
4990 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004991 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004992 return NO_ERROR;
4993 }
Irvel468051e2016-06-13 16:44:44 -07004994 case 1020: { // Layer updates interceptor
4995 n = data.readInt32();
4996 if (n) {
4997 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004998 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004999 }
5000 else{
5001 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08005002 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07005003 }
5004 return NO_ERROR;
5005 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07005006 case 1021: { // Disable HWC virtual displays
5007 n = data.readInt32();
5008 mUseHwcVirtualDisplays = !n;
5009 return NO_ERROR;
5010 }
Romain Guy0147a172017-06-01 13:53:56 -07005011 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07005012 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005013 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07005014
Chia-I Wu28f320b2018-05-03 11:02:56 -07005015 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07005016 return NO_ERROR;
5017 }
Romain Guy54f154a2017-10-24 21:40:32 +01005018 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005019 int32_t colorMode;
5020
Chia-I Wu0d711262018-05-21 15:19:35 -07005021 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07005022 if (data.readInt32(&colorMode) == NO_ERROR) {
5023 mForceColorMode = static_cast<ColorMode>(colorMode);
5024 }
Romain Guy54f154a2017-10-24 21:40:32 +01005025 invalidateHwcGeometry();
5026 repaintEverything();
5027 return NO_ERROR;
5028 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07005029 // Deprecate, use 1030 to check whether the device is color managed.
5030 case 1024: {
5031 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01005032 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005033 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01005034 n = data.readInt32();
5035 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08005036 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005037 Mutex::Autolock lock(mStateLock);
5038 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01005039 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01005040 reply->writeInt32(NO_ERROR);
5041 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08005042 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08005043 bool writeFile = false;
5044 {
5045 Mutex::Autolock lock(mStateLock);
5046 mTracingEnabledChanged = true;
5047 writeFile = mTracing.disable();
5048 }
5049
5050 if (writeFile) {
5051 reply->writeInt32(mTracing.writeToFile());
5052 } else {
5053 reply->writeInt32(NO_ERROR);
5054 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01005055 }
5056 return NO_ERROR;
5057 }
Vishnu Nair87704c92018-01-08 15:32:57 -08005058 case 1026: { // Get layer tracing status
5059 reply->writeBool(mTracing.isEnabled());
5060 return NO_ERROR;
5061 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005062 // Is a DisplayColorSetting supported?
5063 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005064 const auto display = getDefaultDisplayDevice();
5065 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07005066 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005067 }
Chia-I Wu0d711262018-05-21 15:19:35 -07005068
5069 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
5070 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005071 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07005072 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07005073 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005074 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07005075 reply->writeBool(true);
5076 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08005077 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005078 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07005079 break;
5080 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005081 reply->writeBool(
5082 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07005083 break;
5084 }
5085 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005086 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005087 // Is VrFlinger active?
5088 case 1028: {
5089 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07005090 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07005091 return NO_ERROR;
5092 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08005093 // Set buffer size for SF tracing (value in KB)
5094 case 1029: {
5095 n = data.readInt32();
5096 if (n <= 0 || n > MAX_TRACING_MEMORY) {
5097 ALOGW("Invalid buffer size: %d KB", n);
5098 reply->writeInt32(BAD_VALUE);
5099 return BAD_VALUE;
5100 }
5101
5102 ALOGD("Updating trace buffer to %d KB", n);
5103 mTracing.setBufferSize(n * 1024);
5104 reply->writeInt32(NO_ERROR);
5105 return NO_ERROR;
5106 }
Peiyong Lin13effd12018-07-24 17:01:47 -07005107 // Is device color managed?
5108 case 1030: {
5109 reply->writeBool(useColorManagement);
5110 return NO_ERROR;
5111 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08005112 // Override default composition data space
5113 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
5114 // && adb shell stop zygote && adb shell start zygote
5115 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
5116 // adb shell stop zygote && adb shell start zygote
5117 case 1031: {
5118 Mutex::Autolock _l(mStateLock);
5119 n = data.readInt32();
5120 if (n) {
5121 n = data.readInt32();
5122 if (n) {
5123 Dataspace dataspace = static_cast<Dataspace>(n);
5124 if (!validateCompositionDataspace(dataspace)) {
5125 return BAD_VALUE;
5126 }
5127 mDefaultCompositionDataspace = dataspace;
5128 }
5129 n = data.readInt32();
5130 if (n) {
5131 Dataspace dataspace = static_cast<Dataspace>(n);
5132 if (!validateCompositionDataspace(dataspace)) {
5133 return BAD_VALUE;
5134 }
5135 mWideColorGamutCompositionDataspace = dataspace;
5136 }
5137 } else {
5138 // restore composition data space.
5139 mDefaultCompositionDataspace = defaultCompositionDataspace;
5140 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
5141 }
5142 return NO_ERROR;
5143 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07005144 // Set trace flags
5145 case 1033: {
5146 n = data.readUint32();
5147 ALOGD("Updating trace flags to 0x%x", n);
5148 mTracing.setTraceFlags(n);
5149 reply->writeInt32(NO_ERROR);
5150 return NO_ERROR;
5151 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07005152 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005153 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005154 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005155 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2e1dd892020-03-05 13:48:36 -08005156 auto& current = mRefreshRateConfigs->getCurrentRefreshRate();
Ady Abraham2139f732019-11-13 18:56:40 -08005157 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005158 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005159 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005160 } else {
5161 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005162 }
5163 return NO_ERROR;
5164 }
Ady Abraham34392f72019-04-10 11:29:27 -07005165 case 1035: {
5166 n = data.readInt32();
5167 mDebugDisplayConfigSetByBackdoor = false;
5168 if (n >= 0) {
5169 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005170 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005171 if (result != NO_ERROR) {
5172 return result;
5173 }
5174 mDebugDisplayConfigSetByBackdoor = true;
5175 }
5176 return NO_ERROR;
5177 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005178 }
5179 }
5180 return err;
5181}
5182
Steven Thomas6d8110b2017-08-31 18:24:21 -07005183void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005184 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005185 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005186}
5187
Ana Krulec7d1d6832018-12-27 11:10:09 -08005188void SurfaceFlinger::repaintEverythingForHWC() {
5189 mRepaintEverything = true;
Dan Stoza030fbc12020-02-19 15:32:01 -08005190 mPowerAdvisor.notifyDisplayUpdateImminent();
Ady Abraham8532d012019-05-08 14:50:56 -07005191 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005192}
5193
Ady Abrahama09852a2020-02-20 14:23:42 -08005194void SurfaceFlinger::kernelTimerChanged(bool expired) {
5195 static bool updateOverlay =
5196 property_get_bool("debug.sf.kernel_idle_timer_update_overlay", true);
5197 if (!updateOverlay || !mRefreshRateOverlay) return;
5198
5199 // Update the overlay on the main thread to avoid race conditions with
5200 // mRefreshRateConfigs->getCurrentRefreshRate()
5201 postMessageAsync(new LambdaMessage([this, expired]() NO_THREAD_SAFETY_ANALYSIS {
5202 if (mRefreshRateOverlay) {
5203 const auto kernelTimerEnabled = property_get_bool(KERNEL_IDLE_TIMER_PROP, false);
5204 const bool timerExpired = kernelTimerEnabled && expired;
Ady Abraham2e1dd892020-03-05 13:48:36 -08005205 const auto& current = [this]() -> const RefreshRate& {
Ady Abrahama09852a2020-02-20 14:23:42 -08005206 std::lock_guard<std::mutex> lock(mActiveConfigLock);
5207 if (mDesiredActiveConfigChanged) {
5208 return mRefreshRateConfigs->getRefreshRateFromConfigId(
5209 mDesiredActiveConfig.configId);
5210 }
5211
5212 return mRefreshRateConfigs->getCurrentRefreshRate();
5213 }();
5214 const auto& min = mRefreshRateConfigs->getMinRefreshRate();
5215
5216 if (current != min) {
5217 mRefreshRateOverlay->changeRefreshRate(timerExpired ? min : current);
5218 mEventQueue->invalidate();
5219 }
5220 }
5221 }));
5222}
5223
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005224// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5225class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005226public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005227 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5228 ~WindowDisconnector() {
5229 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005230 }
5231
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005232private:
5233 ANativeWindow* mWindow;
5234 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005235};
5236
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005237status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005238 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005239 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5240 const Rect& sourceCrop, uint32_t reqWidth,
5241 uint32_t reqHeight, bool useIdentityTransform,
5242 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005243 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005244
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005245 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005246
Dominik Laskowski718f9602019-11-09 20:01:35 -08005247 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5248 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5249 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5250 renderAreaRotation = ui::Transform::ROT_0;
5251 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005252
Chia-I Wu20261cb2018-08-23 12:55:44 -07005253 sp<DisplayDevice> display;
5254 {
5255 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005256
Chia-I Wu20261cb2018-08-23 12:55:44 -07005257 display = getDisplayDeviceLocked(displayToken);
5258 if (!display) return BAD_VALUE;
5259
Chia-I Wucb023152018-08-28 12:57:23 -07005260 // set the requested width/height to the logical display viewport size
5261 // by default
5262 if (reqWidth == 0 || reqHeight == 0) {
5263 reqWidth = uint32_t(display->getViewport().width());
5264 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005265 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005266 }
5267
Peiyong Lin0e003c92018-09-17 11:09:51 -07005268 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005269 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005270
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005271 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5272 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005273 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005274 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005275}
5276
chaviw93df2ea2019-04-30 16:45:12 -07005277static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5278 switch (colorMode) {
5279 case ColorMode::DISPLAY_P3:
5280 case ColorMode::BT2100_PQ:
5281 case ColorMode::BT2100_HLG:
5282 case ColorMode::DISPLAY_BT2020:
5283 return Dataspace::DISPLAY_P3;
5284 default:
5285 return Dataspace::V0_SRGB;
5286 }
5287}
5288
5289const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5290 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5291 if (displayToken) {
5292 return getDisplayDeviceLocked(displayToken);
5293 }
5294 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5295 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005296 return getDisplayByLayerStack(displayOrLayerStack);
5297}
5298
5299const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005300 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005301 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005302 return display;
5303 }
5304 }
5305 return nullptr;
5306}
5307
5308status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5309 sp<GraphicBuffer>* outBuffer) {
5310 sp<DisplayDevice> display;
5311 uint32_t width;
5312 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005313 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005314 {
5315 Mutex::Autolock _l(mStateLock);
5316 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5317 if (!display) {
5318 return BAD_VALUE;
5319 }
5320
5321 width = uint32_t(display->getViewport().width());
5322 height = uint32_t(display->getViewport().height());
5323
Dominik Laskowski718f9602019-11-09 20:01:35 -08005324 const auto orientation = display->getOrientation();
5325 captureOrientation = ui::Transform::toRotationFlags(orientation);
5326
5327 switch (captureOrientation) {
5328 case ui::Transform::ROT_90:
5329 captureOrientation = ui::Transform::ROT_270;
5330 break;
5331
5332 case ui::Transform::ROT_270:
5333 captureOrientation = ui::Transform::ROT_90;
5334 break;
5335
5336 case ui::Transform::ROT_INVALID:
5337 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5338 captureOrientation = ui::Transform::ROT_0;
5339 break;
5340
5341 default:
5342 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005343 }
chaviw93df2ea2019-04-30 16:45:12 -07005344 *outDataspace =
5345 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5346 }
5347
5348 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5349 false /* captureSecureLayers */);
5350
5351 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5352 std::placeholders::_1);
5353 bool ignored = false;
5354 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5355 false /* useIdentityTransform */,
5356 ignored /* outCapturedSecureLayers */);
5357}
5358
Robert Carr866455f2019-04-02 16:28:26 -07005359status_t SurfaceFlinger::captureLayers(
5360 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5361 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5362 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5363 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005364 ATRACE_CALL();
5365
5366 class LayerRenderArea : public RenderArea {
5367 public:
Robert Carr578038f2018-03-09 12:25:24 -08005368 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005369 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005370 bool childrenOnly, const Rect& displayViewport)
5371 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005372 mLayer(layer),
5373 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005374 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005375 mFlinger(flinger),
5376 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005377 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005378 Rect getBounds() const override {
5379 const Layer::State& layerState(mLayer->getDrawingState());
5380 return mLayer->getBufferSize(layerState);
5381 }
Marissa Wall61c58622018-07-18 10:12:20 -07005382 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005383 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005384 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005385 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005386 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005387 }
chaviwa76b2712017-09-20 12:02:26 -07005388 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005389 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005390 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005391 Rect getSourceCrop() const override {
5392 if (mCrop.isEmpty()) {
5393 return getBounds();
5394 } else {
5395 return mCrop;
5396 }
5397 }
Robert Carr578038f2018-03-09 12:25:24 -08005398 class ReparentForDrawing {
5399 public:
5400 const sp<Layer>& oldParent;
5401 const sp<Layer>& newParent;
5402
Vishnu Nair4351ad52019-02-11 14:13:02 -08005403 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5404 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005405 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005406 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005407 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5408 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005409 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005410 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005411 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005412 };
5413
5414 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005415 const Rect sourceCrop = getSourceCrop();
5416 // no need to check rotation because there is none
5417 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5418 sourceCrop.height() != getReqHeight();
5419
Robert Carr578038f2018-03-09 12:25:24 -08005420 if (!mChildrenOnly) {
5421 mTransform = mLayer->getTransform().inverse();
5422 drawLayers();
5423 } else {
5424 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005425 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5426 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005427 // In the "childrenOnly" case we reparent the children to a screenshot
5428 // layer which has no properties set and which does not draw.
5429 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005430 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5431 "Screenshot Parent"s, w, h, 0,
5432 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005433
Vishnu Nair4351ad52019-02-11 14:13:02 -08005434 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005435 drawLayers();
5436 }
5437 }
chaviwa76b2712017-09-20 12:02:26 -07005438
chaviwa76b2712017-09-20 12:02:26 -07005439 private:
chaviw7206d492017-11-10 16:16:12 -08005440 const sp<Layer> mLayer;
5441 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005442
Peiyong Linefefaac2018-08-17 12:27:51 -07005443 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005444 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005445
5446 SurfaceFlinger* mFlinger;
5447 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005448 };
5449
Robert Carrc0df3122019-04-11 13:18:21 -07005450 int reqWidth = 0;
5451 int reqHeight = 0;
5452 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005453 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005454 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005455 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005456 {
5457 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005458
Robert Carrc0df3122019-04-11 13:18:21 -07005459 parent = fromHandle(layerHandleBinder);
5460 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5461 ALOGE("captureLayers called with an invalid or removed parent");
5462 return NAME_NOT_FOUND;
5463 }
5464
5465 const int uid = IPCThreadState::self()->getCallingUid();
5466 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5467 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5468 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5469 return PERMISSION_DENIED;
5470 }
5471
Vishnu Nairefc42e22019-12-03 17:36:12 -08005472 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005473 if (sourceCrop.width() <= 0) {
5474 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005475 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005476 }
5477
5478 if (sourceCrop.height() <= 0) {
5479 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005480 crop.bottom = parentSourceBounds.getHeight();
5481 }
5482
5483 if (crop.isEmpty() || frameScale <= 0.0f) {
5484 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5485 // crop was not specified, or an invalid frame scale was provided.
5486 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005487 }
5488 reqWidth = crop.width() * frameScale;
5489 reqHeight = crop.height() * frameScale;
5490
5491 for (const auto& handle : excludeHandles) {
5492 sp<Layer> excludeLayer = fromHandle(handle);
5493 if (excludeLayer != nullptr) {
5494 excludeLayers.emplace(excludeLayer);
5495 } else {
5496 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5497 return NAME_NOT_FOUND;
5498 }
5499 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005500
5501 auto display = getDisplayByLayerStack(parent->getLayerStack());
5502 if (!display) {
5503 return BAD_VALUE;
5504 }
5505
5506 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005507 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005508
Chia-I Wu20261cb2018-08-23 12:55:44 -07005509 // really small crop or frameScale
5510 if (reqWidth <= 0) {
5511 reqWidth = 1;
5512 }
5513 if (reqHeight <= 0) {
5514 reqHeight = 1;
5515 }
5516
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005517 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5518 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005519 auto traverseLayers = [parent, childrenOnly,
5520 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005521 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5522 if (!layer->isVisible()) {
5523 return;
Robert Carr578038f2018-03-09 12:25:24 -08005524 } else if (childrenOnly && layer == parent.get()) {
5525 return;
chaviwa76b2712017-09-20 12:02:26 -07005526 }
Robert Carr866455f2019-04-02 16:28:26 -07005527
5528 sp<Layer> p = layer;
5529 while (p != nullptr) {
5530 if (excludeLayers.count(p) != 0) {
5531 return;
5532 }
5533 p = p->getParent();
5534 }
5535
chaviwa76b2712017-09-20 12:02:26 -07005536 visitor(layer);
5537 });
5538 };
Robert Carr108b2c72019-04-02 16:32:58 -07005539
5540 bool outCapturedSecureLayers = false;
5541 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5542 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005543}
5544
5545status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5546 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005547 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005548 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005549 bool useIdentityTransform,
5550 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005551 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005552
Peiyong Lin0e003c92018-09-17 11:09:51 -07005553 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005554 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5555 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005556 *outBuffer =
5557 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5558 static_cast<android_pixel_format>(reqPixelFormat), 1,
5559 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005560
Robert Carr108b2c72019-04-02 16:32:58 -07005561 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5562 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005563}
5564
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005565status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5566 TraverseLayersFunction traverseLayers,
5567 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005568 bool useIdentityTransform,
5569 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005570 // This mutex protects syncFd and captureResult for communication of the return values from the
5571 // main thread back to this Binder thread
5572 std::mutex captureMutex;
5573 std::condition_variable captureCondition;
5574 std::unique_lock<std::mutex> captureLock(captureMutex);
5575 int syncFd = -1;
5576 std::optional<status_t> captureResult;
5577
Robert Carr03480e22018-01-04 16:02:06 -08005578 const int uid = IPCThreadState::self()->getCallingUid();
5579 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5580
Dominik Laskowski8c001672018-05-30 16:52:06 -07005581 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005582 // If there is a refresh pending, bug out early and tell the binder thread to try again
5583 // after the refresh.
5584 if (mRefreshPending) {
5585 ATRACE_NAME("Skipping screenshot for now");
5586 std::unique_lock<std::mutex> captureLock(captureMutex);
5587 captureResult = std::make_optional<status_t>(EAGAIN);
5588 captureCondition.notify_one();
5589 return;
5590 }
5591
5592 status_t result = NO_ERROR;
5593 int fd = -1;
5594 {
5595 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005596 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005597 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005598 useIdentityTransform, forSystem, &fd,
5599 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005600 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005601 }
5602
5603 {
5604 std::unique_lock<std::mutex> captureLock(captureMutex);
5605 syncFd = fd;
5606 captureResult = std::make_optional<status_t>(result);
5607 captureCondition.notify_one();
5608 }
5609 });
5610
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005611 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005612 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005613 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005614 while (*captureResult == EAGAIN) {
5615 captureResult.reset();
5616 result = postMessageAsync(message);
5617 if (result != NO_ERROR) {
5618 return result;
5619 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005620 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005621 }
5622 result = *captureResult;
5623 }
5624
5625 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005626 sync_wait(syncFd, -1);
5627 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005628 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005629
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005630 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005631}
5632
chaviwa76b2712017-09-20 12:02:26 -07005633void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005634 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005635 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5636 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005637 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005638
chaviwa76b2712017-09-20 12:02:26 -07005639 const auto reqWidth = renderArea.getReqWidth();
5640 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005641 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005642 const auto transform = renderArea.getTransform();
5643 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005644 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005645
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005646 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005647 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005648
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005649 // assume that bounds are never offset, and that they are the same as the
5650 // buffer bounds.
5651 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005652 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005653 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005654
5655 // Now take into account the rotation flag. We append a transform that
5656 // rotates the layer stack about the origin, then translate by buffer
5657 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005658 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005659 int displacementX = 0;
5660 int displacementY = 0;
5661 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5662 switch (rotation) {
5663 case ui::Transform::ROT_90:
5664 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005665 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005666 break;
5667 case ui::Transform::ROT_180:
5668 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005669 displacementY = renderArea.getBounds().getWidth();
5670 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005671 break;
5672 case ui::Transform::ROT_270:
5673 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005674 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005675 break;
5676 default:
5677 break;
5678 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005679
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005680 // We need to transform the clipping window into the right spot.
5681 // First, rotate the clipping rectangle by the rotation hint to get the
5682 // right orientation
5683 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5684 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5685 const vec4 rotClipTL = rotMatrix * clipTL;
5686 const vec4 rotClipBR = rotMatrix * clipBR;
5687 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5688 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5689 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5690 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5691
5692 // Now reposition the clipping rectangle with the displacement vector
5693 // computed above.
5694 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005695 clientCompositionDisplay.clip =
5696 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5697 newClipRight + displacementX, newClipBottom + displacementY);
5698
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005699 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005700 clientCompositionDisplay.globalTransform =
5701 clipTransform * clientCompositionDisplay.globalTransform;
5702
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005703 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5704 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005705
chaviw50da5042018-04-09 13:49:37 -07005706 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005707
Vishnu Nair9b079a22020-01-21 14:36:08 -08005708 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005709 fillLayer.source.buffer.buffer = nullptr;
5710 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5711 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5712 fillLayer.alpha = half(alpha);
5713 clientCompositionLayers.push_back(fillLayer);
5714
5715 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005716 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005717 const bool supportProtectedContent = false;
5718 Region clip(renderArea.getBounds());
5719 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5720 clip,
5721 useIdentityTransform,
5722 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5723 renderArea.isSecure(),
5724 supportProtectedContent,
5725 clearRegion,
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005726 displayViewport,
5727 clientCompositionDisplay.outputDataspace,
5728 true, /* realContentIsVisible */
5729 false, /* clearContent */
Lloyd Piquef16688f2019-02-19 17:47:57 -08005730 };
Vishnu Nairb87d94f2020-02-13 09:17:36 -08005731 std::vector<compositionengine::LayerFE::LayerSettings> results =
5732 layer->prepareClientCompositionList(targetSettings);
5733 clientCompositionLayers.insert(clientCompositionLayers.end(),
5734 std::make_move_iterator(results.begin()),
5735 std::make_move_iterator(results.end()));
5736 results.clear();
5737
chaviwa76b2712017-09-20 12:02:26 -07005738 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005739
Vishnu Nair9b079a22020-01-21 14:36:08 -08005740 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5741 clientCompositionLayers.reserve(clientCompositionLayers.size());
5742 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5743 std::back_inserter(clientCompositionLayerPointers),
5744 [](compositionengine::LayerFE::LayerSettings& settings)
5745 -> renderengine::LayerSettings* { return &settings; });
5746
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005747 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005748 // Use an empty fence for the buffer fence, since we just created the buffer so
5749 // there is no need for synchronization with the GPU.
5750 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005751 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005752 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005753 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005754 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005755
5756 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005757}
5758
chaviwa76b2712017-09-20 12:02:26 -07005759status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5760 TraverseLayersFunction traverseLayers,
5761 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005762 bool useIdentityTransform, bool forSystem,
5763 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005764 ATRACE_CALL();
5765
chaviwa76b2712017-09-20 12:02:26 -07005766 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005767 outCapturedSecureLayers =
5768 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005769 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005770
Robert Carr03480e22018-01-04 16:02:06 -08005771 // We allow the system server to take screenshots of secure layers for
5772 // use in situations like the Screen-rotation animation and place
5773 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005774 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005775 ALOGW("FB is protected: PERMISSION_DENIED");
5776 return PERMISSION_DENIED;
5777 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005778 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005779 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005780}
5781
chaviw95ef3c42019-02-14 10:55:09 -08005782void SurfaceFlinger::setInputWindowsFinished() {
5783 Mutex::Autolock _l(mStateLock);
5784
5785 mPendingSyncInputWindows = false;
5786 mTransactionCV.broadcast();
5787}
chaviw5f21a5e2019-02-14 10:00:34 -08005788
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005789// ---------------------------------------------------------------------------
5790
Edgar Arriaga844fa672020-01-16 14:21:42 -08005791void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5792 layersSortedByZ.traverse(visitor);
5793}
5794
Dan Stoza412903f2017-04-27 13:42:17 -07005795void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5796 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005797}
5798
Dan Stoza412903f2017-04-27 13:42:17 -07005799void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5800 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005801}
5802
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005803void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005804 const LayerVector::Visitor& visitor) {
5805 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005806 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005807 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005808 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005809 continue;
5810 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005811 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005812 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005813 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005814 return;
5815 }
chaviwa76b2712017-09-20 12:02:26 -07005816 if (!layer->isVisible()) {
5817 return;
5818 }
5819 visitor(layer);
5820 });
5821 }
5822}
5823
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005824status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5825 HwcConfigIndexType defaultConfig,
5826 float minRefreshRate,
5827 float maxRefreshRate) {
5828 Mutex::Autolock lock(mStateLock);
5829
Dominik Laskowski22488f62019-03-28 09:53:04 -07005830 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005831 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5832 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5833 // it should go thru setDesiredActiveConfig, similar to primary display.
5834 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5835 const auto displayId = display->getId();
5836 LOG_ALWAYS_FATAL_IF(!displayId);
5837
5838 HWC2::VsyncPeriodChangeConstraints constraints;
5839 constraints.desiredTimeNanos = systemTime();
5840 constraints.seamlessRequired = false;
5841
5842 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005843 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5844 constraints, &timeline) < 0) {
5845 return BAD_VALUE;
5846 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005847 if (timeline.refreshRequired) {
5848 repaintEverythingForHWC();
5849 }
5850
Ady Abrahamdfa37362020-01-21 18:02:39 -08005851 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005852 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005853 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5854 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005855 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005856 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005857 }
5858
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005859 if (mDebugDisplayConfigSetByBackdoor) {
5860 // ignore this request as config is overridden by backdoor
5861 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005862 }
5863
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005864 bool policyChanged;
5865 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5866 &policyChanged) < 0) {
5867 return BAD_VALUE;
5868 }
5869 if (!policyChanged) {
5870 return NO_ERROR;
5871 }
5872
5873 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5874 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005875
5876 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5877 // that listeners that care about a change in allowed configs can get the notification.
5878 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005879 const nsecs_t vsyncPeriod =
5880 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005881 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005882 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005883
Ana Krulec3f6a2062020-01-23 15:48:01 -08005884 auto configId = mScheduler->getPreferredConfigId();
Ady Abraham2e1dd892020-03-05 13:48:36 -08005885 auto& preferredRefreshRate = configId
Ana Krulec3f6a2062020-01-23 15:48:01 -08005886 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5887 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5888 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5889 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5890 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5891
5892 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5893 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5894 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005895 } else {
Ana Krulec3f6a2062020-01-23 15:48:01 -08005896 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005897 }
5898
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005899 return NO_ERROR;
5900}
5901
Ana Krulec0782b882019-10-15 17:34:54 -07005902status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005903 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005904 float maxRefreshRate) {
5905 ATRACE_CALL();
5906
5907 if (!displayToken) {
5908 return BAD_VALUE;
5909 }
5910
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005911 status_t result = NO_ERROR;
5912
Ana Krulec234bb162019-11-10 22:55:55 +01005913 postMessageSync(new LambdaMessage([&]() {
5914 const auto display = getDisplayDeviceLocked(displayToken);
5915 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005916 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005917 ALOGE("Attempt to set desired display configs for invalid display token %p",
5918 displayToken.get());
5919 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005920 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005921 ALOGW("Attempt to set desired display configs for virtual display");
5922 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005923 result =
5924 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5925 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005926 }
5927 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005928
5929 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005930}
5931
5932status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005933 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005934 float* outMinRefreshRate,
5935 float* outMaxRefreshRate) {
5936 ATRACE_CALL();
5937
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005938 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005939 return BAD_VALUE;
5940 }
5941
5942 Mutex::Autolock lock(mStateLock);
5943 const auto display = getDisplayDeviceLocked(displayToken);
5944 if (!display) {
5945 return NAME_NOT_FOUND;
5946 }
5947
5948 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005949 HwcConfigIndexType defaultConfig;
5950 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5951 *outDefaultConfig = defaultConfig.value();
5952 return NO_ERROR;
5953 } else if (display->isVirtual()) {
5954 return BAD_VALUE;
5955 } else {
5956 const auto displayId = display->getId();
5957 if (!displayId) {
5958 return BAD_VALUE;
5959 }
5960 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5961 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5962 *outMinRefreshRate = 1e9f / vsyncPeriod;
5963 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5964 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005965 }
Ana Krulec0782b882019-10-15 17:34:54 -07005966}
5967
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005968void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005969 mFlinger->setInputWindowsFinished();
5970}
5971
Robert Carrc0df3122019-04-11 13:18:21 -07005972sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005973 BBinder* b = nullptr;
5974 if (handle) {
5975 b = handle->localBinder();
5976 }
Robert Carrc0df3122019-04-11 13:18:21 -07005977 if (b == nullptr) {
5978 return nullptr;
5979 }
5980 auto it = mLayersByLocalBinderToken.find(b);
5981 if (it != mLayersByLocalBinderToken.end()) {
5982 return it->second.promote();
5983 }
5984 return nullptr;
5985}
5986
Dominik Laskowski75848362019-11-11 17:57:20 -08005987void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005988 mNumLayers++;
5989 mScheduler->registerLayer(layer);
5990}
5991
5992void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5993 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005994 removeFromOffscreenLayers(layer);
5995}
5996
5997// WARNING: ONLY CALL THIS FROM LAYER DTOR
5998// Here we add children in the current state to offscreen layers and remove the
5999// layer itself from the offscreen layer list. Since
6000// this is the dtor, it is safe to access the current state. This keeps us
6001// from dangling children layers such that they are not reachable from the
6002// Drawing state nor the offscreen layer list
6003// See b/141111965
6004void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
6005 for (auto& child : layer->getCurrentChildren()) {
6006 mOffscreenLayers.emplace(child.get());
6007 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07006008 mOffscreenLayers.erase(layer);
6009}
6010
Alec Mouri4545a8a2019-08-08 20:05:32 -07006011void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
6012 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
6013}
6014
Vishnu Nair08f6eae2019-11-26 14:01:39 -08006015status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
6016 float lightPosY, float lightPosZ,
6017 float lightRadius) {
6018 Mutex::Autolock _l(mStateLock);
6019 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
6020 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
6021 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
6022 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
6023 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
6024
6025 // these values are overridden when calculating the shadow settings for a layer.
6026 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
6027 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08006028 return NO_ERROR;
6029}
6030
Lloyd Pique8d9f8362020-02-11 19:13:09 -08006031const std::unordered_map<std::string, uint32_t>& SurfaceFlinger::getGenericLayerMetadataKeyMap()
6032 const {
6033 // TODO(b/149500060): Remove this fixed/static mapping. Please prefer taking
6034 // on the work to remove the table in that bug rather than adding more to
6035 // it.
6036 static const std::unordered_map<std::string, uint32_t> genericLayerMetadataKeyMap{
6037 // Note: METADATA_OWNER_UID and METADATA_WINDOW_TYPE are officially
6038 // supported, and exposed via the
6039 // IVrComposerClient::VrCommand::SET_LAYER_INFO command.
6040 {"org.chromium.arc.V1_0.TaskId", METADATA_TASK_ID},
6041 {"org.chromium.arc.V1_0.CursorInfo", METADATA_MOUSE_CURSOR},
6042 };
6043 return genericLayerMetadataKeyMap;
6044}
6045
Steven Thomas62a4cf82020-01-31 12:04:03 -08006046status_t SurfaceFlinger::setFrameRate(const sp<IGraphicBufferProducer>& surface, float frameRate,
6047 int8_t compatibility) {
6048 if (!ValidateFrameRate(frameRate, compatibility, "SurfaceFlinger::setFrameRate")) {
6049 return BAD_VALUE;
6050 }
6051
6052 Mutex::Autolock lock(mStateLock);
6053 if (authenticateSurfaceTextureLocked(surface)) {
6054 sp<Layer> layer = (static_cast<MonitoredProducer*>(surface.get()))->getLayer();
6055 if (layer->setFrameRate(
6056 Layer::FrameRate(frameRate,
6057 Layer::FrameRate::convertCompatibility(compatibility)))) {
6058 setTransactionFlags(eTraversalNeeded);
6059 }
6060 } else {
6061 ALOGE("Attempt to set frame rate on an unrecognized IGraphicBufferProducer");
6062 return BAD_VALUE;
6063 }
6064 return NO_ERROR;
6065}
6066
Dominik Laskowski9dab3432019-03-27 13:21:10 -07006067} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07006068
Mathias Agopian3f844832013-08-07 21:24:32 -07006069#if defined(__gl_h_)
6070#error "don't include gl/gl.h in this file"
6071#endif
6072
6073#if defined(__gl2_h_)
6074#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08006075#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08006076
6077// TODO(b/129481165): remove the #pragma below and fix conversion issues
6078#pragma clang diagnostic pop // ignored "-Wconversion"