blob: 61e5e6647517359148106dd2cf0409eb39293686 [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
Mathias Agopian921e6ac2012-07-23 23:11:29 -070024#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080025#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070026#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080027
28#include <algorithm>
29#include <cinttypes>
30#include <cmath>
31#include <cstdint>
32#include <functional>
33#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070034#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080035#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070036
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080037#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070038#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080039
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070040#include <binder/IPCThreadState.h>
41#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070042#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070043
Lloyd Pique70d91362018-10-18 16:02:55 -070044#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080045#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070047#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080048#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070049#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070050#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080051#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070053#include <gui/DebugEGLImageTracker.h>
54
Andy McFadden4803b742012-09-24 19:07:20 -070055#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070056#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080057#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080058#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080059#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070060#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070061#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070062#include <ui/ColorSpace.h>
63#include <ui/DebugUtils.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080064#include <ui/DisplayConfig.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070065#include <ui/DisplayInfo.h>
66#include <ui/DisplayStatInfo.h>
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -080067#include <ui/DisplayState.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070068#include <ui/GraphicBufferAllocator.h>
69#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070070#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070072#include <utils/String16.h>
73#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070074#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080075#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070076#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080077
Mathias Agopian921e6ac2012-07-23 23:11:29 -070078#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070079#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080080
Robert Carr578038f2018-03-09 12:25:24 -080081#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070082#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070083#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020084#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080085#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020086#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080087#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080088#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070090#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080091#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070092#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070093#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070094#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070096#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080097
Steven Thomasb02664d2017-07-26 18:48:28 -070098#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070099#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -0700100#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -0700101#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700102#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700103#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700104#include "FrameTracer/FrameTracer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700105#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700106#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700107#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700108#include "Scheduler/EventControlThread.h"
109#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700110#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700111#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700112#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800113#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700114
Mathias Agopianff2ed702013-09-01 21:36:12 -0700115#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700116
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700117#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800118#include "android-base/stringprintf.h"
119
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800120#include <android/configuration.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900121#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800122#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
123#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700124#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900125#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900126
chaviw1d044282017-09-27 12:19:28 -0700127#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900128#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700129
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800130namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700131
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700132using namespace std::string_literals;
133
Jaesoo Lee43518572017-01-23 19:03:16 +0900134using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900135using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900136using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800137
Ady Abraham8532d012019-05-08 14:50:56 -0700138using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800139using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700140using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700141using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800142using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700143using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700144using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900145
Steven Thomasb02664d2017-07-26 18:48:28 -0700146namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700147
148#pragma clang diagnostic push
149#pragma clang diagnostic error "-Wswitch-enum"
150
151bool isWideColorMode(const ColorMode colorMode) {
152 switch (colorMode) {
153 case ColorMode::DISPLAY_P3:
154 case ColorMode::ADOBE_RGB:
155 case ColorMode::DCI_P3:
156 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700157 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700158 case ColorMode::BT2100_PQ:
159 case ColorMode::BT2100_HLG:
160 return true;
161 case ColorMode::NATIVE:
162 case ColorMode::STANDARD_BT601_625:
163 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
164 case ColorMode::STANDARD_BT601_525:
165 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
166 case ColorMode::STANDARD_BT709:
167 case ColorMode::SRGB:
168 return false;
169 }
170 return false;
171}
172
173#pragma clang diagnostic pop
174
Steven Thomasb02664d2017-07-26 18:48:28 -0700175class ConditionalLock {
176public:
177 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
178 if (lock) {
179 mMutex.lock();
180 }
181 }
182 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
183private:
184 Mutex& mMutex;
185 bool mLocked;
186};
Peiyong Linfca547f2018-07-09 13:03:33 -0700187
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800188// TODO(b/141333600): Consolidate with HWC2::Display::Config::Builder::getDefaultDensity.
189constexpr float FALLBACK_DENSITY = ACONFIGURATION_DENSITY_TV / 160.f;
190
191float getDensityFromProperty(const char* property, bool required) {
192 char value[PROPERTY_VALUE_MAX];
193 const float density = property_get(property, value, nullptr) > 0 ? std::atof(value) : 0.f;
194 if (!density && required) {
195 ALOGE("%s must be defined as a build property", property);
196 return FALLBACK_DENSITY;
197 }
198 return density / 160.f;
199}
200
Peiyong Lin9d846a52018-11-05 13:18:20 -0800201// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
202bool validateCompositionDataspace(Dataspace dataspace) {
203 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
204}
205
Steven Thomasb02664d2017-07-26 18:48:28 -0700206} // namespace anonymous
207
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800208// ---------------------------------------------------------------------------
209
Mathias Agopian99b49842011-06-27 16:05:52 -0700210const String16 sHardwareTest("android.permission.HARDWARE_TEST");
211const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
212const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
213const String16 sDump("android.permission.DUMP");
214
215// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700216int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700217bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800218uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800219bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800220bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800221int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600222bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800223ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700224bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700225bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700226Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
227ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
228Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
229ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700230
Kalle Raitaa099a242017-01-11 11:17:29 -0800231std::string getHwcServiceName() {
232 char value[PROPERTY_VALUE_MAX] = {};
233 property_get("debug.sf.hwc_service_name", value, "default");
234 ALOGI("Using HWComposer service: '%s'", value);
235 return std::string(value);
236}
237
238bool useTrebleTestingOverride() {
239 char value[PROPERTY_VALUE_MAX] = {};
240 property_get("debug.sf.treble_testing_override", value, "false");
241 ALOGI("Treble testing override: '%s'", value);
242 return std::string(value) == "true";
243}
244
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800245std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
246 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800247 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700248 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800249 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700250 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800251 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700252 return std::string("Enhanced");
253 default:
254 return std::string("Unknown ") +
255 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800256 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800257}
258
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700259SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800260
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700261SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
262 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700263 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700264 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700265 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700266 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700267 mCompositionEngine(mFactory.createCompositionEngine()),
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800268 mInternalDisplayDensity(getDensityFromProperty("ro.sf.lcd_density", true)),
269 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800270
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700271SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800272 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800273
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900274 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800275
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900276 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700277
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700279
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800281
Steven Thomas050b2c82017-03-06 11:45:16 -0800282 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900283 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800284
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900285 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800286
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900287 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700288
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900289 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600290
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900291 mDefaultCompositionDataspace =
292 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700293 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
294 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900295 defaultCompositionDataspace = mDefaultCompositionDataspace;
296 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
297 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
298 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
299 wideColorGamutCompositionPixelFormat =
300 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700301
Yichi Chenda901bf2019-06-28 14:58:27 +0800302 mColorSpaceAgnosticDataspace =
303 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
304
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900305 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800306
Dominik Laskowski718f9602019-11-09 20:01:35 -0800307 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
308 switch (primary_display_orientation(Values::ORIENTATION_0)) {
309 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800310 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800311 case Values::ORIENTATION_90:
312 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800313 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800314 case Values::ORIENTATION_180:
315 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800316 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800317 case Values::ORIENTATION_270:
318 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800319 break;
320 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800321 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800322
Sundong Ahn85131bd2019-02-18 15:51:53 +0900323 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800324
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800325 // debugging stuff...
326 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700327
Mathias Agopianb4b17302013-03-20 18:36:41 -0700328 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700329 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700330
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800331 property_get("debug.sf.showupdates", value, "0");
332 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700333
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700334 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000335
336 // DDMS debugging deprecated (b/120782499)
337 property_get("debug.sf.ddms", value, "0");
338 int debugDdms = atoi(value);
339 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700340
341 property_get("debug.sf.disable_backpressure", value, "0");
342 mPropagateBackpressure = !atoi(value);
343 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700344
Ady Abrahamadb9a992019-09-19 21:21:55 +0000345 property_get("debug.sf.enable_gl_backpressure", value, "0");
346 mPropagateBackpressureClientComposition = atoi(value);
347 ALOGI_IF(mPropagateBackpressureClientComposition,
348 "Enabling backpressure propagation for Client Composition");
349
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800350 property_get("debug.sf.enable_hwc_vds", value, "0");
351 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800352 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800353
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800354 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800355 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800356 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700357
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800358 property_get("ro.surface_flinger.supports_background_blur", value, "0");
359 bool supportsBlurs = atoi(value);
360 property_get("debug.sf.disableBlurs", value, "0");
361 bool disableBlurs = atoi(value);
362 mEnableBlurs = supportsBlurs && !disableBlurs;
363 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
364 disableBlurs);
365
Yiwei Zhang243b3782018-05-15 17:40:04 -0700366 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700367 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
368 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
369
Dan Stozaec460082018-12-17 15:35:09 -0800370 property_get("debug.sf.luma_sampling", value, "1");
371 mLumaSampling = atoi(value);
372
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800373 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800374 mDisableClientCompositionCache = atoi(value);
375
Romain Guy11d63f42017-07-20 12:47:14 -0700376 // We should be reading 'persist.sys.sf.color_saturation' here
377 // but since /data may be encrypted, we need to wait until after vold
378 // comes online to attempt to read the property. The property is
379 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800380
381 if (useTrebleTestingOverride()) {
382 // Without the override SurfaceFlinger cannot connect to HIDL
383 // services that are not listed in the manifests. Considered
384 // deriving the setting from the set service name, but it
385 // would be brittle if the name that's not 'default' is used
386 // for production purposes later on.
387 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
388 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389}
390
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800391void SurfaceFlinger::onFirstRef()
392{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800393 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800394}
395
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700396SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800397
Dan Stozac7014012014-02-14 15:03:43 -0800398void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800399{
400 // the window manager died on us. prepare its eulogy.
401
Andy McFadden13a082e2012-08-24 10:16:42 -0700402 // restore initial conditions (default device unblank, etc)
403 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800404
405 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700406 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800407}
408
Robert Carr1db73f62016-12-21 12:58:51 -0800409static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700410 status_t err = client->initCheck();
411 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800412 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800413 }
Robert Carr1db73f62016-12-21 12:58:51 -0800414 return nullptr;
415}
416
417sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
418 return initClient(new Client(this));
419}
420
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700421sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
422 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700423{
424 class DisplayToken : public BBinder {
425 sp<SurfaceFlinger> flinger;
426 virtual ~DisplayToken() {
427 // no more references, this display must be terminated
428 Mutex::Autolock _l(flinger->mStateLock);
429 flinger->mCurrentState.displays.removeItem(this);
430 flinger->setTransactionFlags(eDisplayTransactionNeeded);
431 }
432 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700433 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700434 : flinger(flinger) {
435 }
436 };
437
438 sp<BBinder> token = new DisplayToken(this);
439
440 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700441 // Display ID is assigned when virtual display is allocated by HWC.
442 DisplayDeviceState state;
443 state.isSecure = secure;
444 state.displayName = displayName;
445 mCurrentState.displays.add(token, state);
446 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700447 return token;
448}
449
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700450void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700451 Mutex::Autolock _l(mStateLock);
452
Dominik Laskowski075d3172018-05-24 15:50:06 -0700453 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
454 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700455 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700456 return;
457 }
458
Dominik Laskowski075d3172018-05-24 15:50:06 -0700459 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
460 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700461 ALOGE("destroyDisplay called for non-virtual display");
462 return;
463 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700464 mInterceptor->saveDisplayDeletion(state.sequenceId);
465 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700466 setTransactionFlags(eDisplayTransactionNeeded);
467}
468
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800469std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
470 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700471
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800472 const auto internalDisplayId = getInternalDisplayIdLocked();
473 if (!internalDisplayId) {
474 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700475 }
476
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800477 std::vector<PhysicalDisplayId> displayIds;
478 displayIds.reserve(mPhysicalDisplayTokens.size());
479 displayIds.push_back(internalDisplayId->value);
480
481 for (const auto& [id, token] : mPhysicalDisplayTokens) {
482 if (id != *internalDisplayId) {
483 displayIds.push_back(id.value);
484 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700486
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800487 return displayIds;
488}
489
490sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
491 Mutex::Autolock lock(mStateLock);
492 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700493}
494
Ady Abraham37965d42018-11-01 13:43:32 -0700495status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
496 if (!outGetColorManagement) {
497 return BAD_VALUE;
498 }
499 *outGetColorManagement = useColorManagement;
500 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700501}
502
Lloyd Pique441d5042018-10-18 16:49:51 -0700503HWComposer& SurfaceFlinger::getHwComposer() const {
504 return mCompositionEngine->getHwComposer();
505}
506
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700507renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
508 return mCompositionEngine->getRenderEngine();
509}
510
Lloyd Pique70d91362018-10-18 16:02:55 -0700511compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
512 return *mCompositionEngine.get();
513}
514
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800515void SurfaceFlinger::bootFinished()
516{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700517 if (mStartPropertySetThread->join() != NO_ERROR) {
518 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800519 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800520 const nsecs_t now = systemTime();
521 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000522 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700523
Mikael Pessa90092f42019-08-26 17:22:04 -0700524 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000525 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700526
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700527 // wait patiently for the window manager death
528 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700529 mWindowManager = defaultServiceManager()->getService(name);
530 if (mWindowManager != 0) {
531 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700532 }
Robert Carr720e5062018-07-30 17:45:14 -0700533 sp<IBinder> input(defaultServiceManager()->getService(
534 String16("inputflinger")));
535 if (input == nullptr) {
536 ALOGE("Failed to link to input service");
537 } else {
538 mInputFlinger = interface_cast<IInputFlinger>(input);
539 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700540
Steven Thomas050b2c82017-03-06 11:45:16 -0800541 if (mVrFlinger) {
542 mVrFlinger->OnBootFinished();
543 }
544
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700545 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700546 // formerly we would just kill the process, but we now ask it to exit so it
547 // can choose where to stop the animation.
548 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700549
550 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
551 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
552 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700553
Ana Krulecbd6654b2019-02-15 15:18:15 -0800554 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800555 readPersistentProperties();
556 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800557
Ady Abraham8a82ba62020-01-17 12:43:17 -0800558 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
559 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
560 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
561 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800562 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800563}
564
Dan Stoza436ccf32018-06-21 12:10:12 -0700565uint32_t SurfaceFlinger::getNewTexture() {
566 {
567 std::lock_guard lock(mTexturePoolMutex);
568 if (!mTexturePool.empty()) {
569 uint32_t name = mTexturePool.back();
570 mTexturePool.pop_back();
571 ATRACE_INT("TexturePoolSize", mTexturePool.size());
572 return name;
573 }
574
575 // The pool was too small, so increase it for the future
576 ++mTexturePoolSize;
577 }
578
579 // The pool was empty, so we need to get a new texture name directly using a
580 // blocking call to the main thread
581 uint32_t name = 0;
582 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
583 return name;
584}
585
Mathias Agopian3f844832013-08-07 21:24:32 -0700586void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700587 std::lock_guard lock(mTexturePoolMutex);
588 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
589 // to actually delete this or not based on mTexturePoolSize
590 mTexturePool.push_back(texture);
591 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700592}
593
Wei Wangf9b05ee2017-07-19 20:59:39 -0700594// Do not call property_set on main thread which will be blocked by init
595// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700596void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700597 ALOGI( "SurfaceFlinger's main thread ready to run. "
598 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700599 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800600
Steven Thomasb02664d2017-07-26 18:48:28 -0700601 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700602 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800603 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700604 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
605 renderengine::RenderEngineCreationArgs::Builder()
606 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
607 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
608 .setUseColorManagerment(useColorManagement)
609 .setEnableProtectedContext(enable_protected_contents(false))
610 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800611 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700612 .setContextPriority(useContextPriority
613 ? renderengine::RenderEngine::ContextPriority::HIGH
614 : renderengine::RenderEngine::ContextPriority::MEDIUM)
615 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800616 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700617
618 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
619 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700620 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
621 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800622 // Process any initial hotplug and resulting display changes.
623 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700624 const auto display = getDefaultDisplayDeviceLocked();
625 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700626 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700627 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800628
Steven Thomas050b2c82017-03-06 11:45:16 -0800629 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700630 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700631 // This callback is called from the vr flinger dispatch thread. We
632 // need to call signalTransaction(), which requires holding
633 // mStateLock when we're not on the main thread. Acquiring
634 // mStateLock from the vr flinger dispatch thread might trigger a
635 // deadlock in surface flinger (see b/66916578), so post a message
636 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700637 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700638 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
639 mVrFlingerRequestsDisplay = requestDisplay;
640 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700641 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800642 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700643 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
644 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700645 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700646 .value_or(0),
647 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800648 if (!mVrFlinger) {
649 ALOGE("Failed to start vrflinger");
650 }
651 }
652
Mathias Agopian92a979a2012-08-02 18:32:23 -0700653 // initialize our drawing state
654 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700655
Andy McFadden13a082e2012-08-24 10:16:42 -0700656 // set initial conditions (e.g. unblank default device)
657 initializeDisplays();
658
Steven Thomas137d4bc2019-07-25 16:55:14 -0700659 char primeShaderCache[PROPERTY_VALUE_MAX];
660 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
661 if (atoi(primeShaderCache)) {
662 getRenderEngine().primeCache();
663 }
Dan Stoza4e637772016-07-28 13:31:51 -0700664
Wei Wangf9b05ee2017-07-19 20:59:39 -0700665 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700666
667 const bool presentFenceReliable =
668 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
669 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700670
671 if (mStartPropertySetThread->Start() != NO_ERROR) {
672 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800673 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800674
Dan Stoza9e56aa02015-11-02 13:00:03 -0800675 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700676}
677
Romain Guy11d63f42017-07-20 12:47:14 -0700678void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700679 Mutex::Autolock _l(mStateLock);
680
Romain Guy11d63f42017-07-20 12:47:14 -0700681 char value[PROPERTY_VALUE_MAX];
682
683 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800684 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700685 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800686 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100687
688 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700689 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800690
691 property_get("persist.sys.sf.color_mode", value, "0");
692 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700693}
694
Mathias Agopiana67e4182012-06-19 17:26:12 -0700695void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800696 // Start boot animation service by setting a property mailbox
697 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800699 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700700 if (mStartPropertySetThread->join() != NO_ERROR) {
701 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800702 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700703}
704
Mathias Agopian875d8e12013-06-07 15:35:48 -0700705size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700706 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700707}
708
Mathias Agopian875d8e12013-06-07 15:35:48 -0700709size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700710 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700711}
712
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800713// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800714
Jamie Gennis582270d2011-08-17 18:19:00 -0700715bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800716 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800717 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800718 return authenticateSurfaceTextureLocked(bufferProducer);
719}
720
721bool SurfaceFlinger::authenticateSurfaceTextureLocked(
722 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800723 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800724 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800725}
726
Brian Anderson6b376712017-04-04 10:51:39 -0700727status_t SurfaceFlinger::getSupportedFrameTimestamps(
728 std::vector<FrameEvent>* outSupported) const {
729 *outSupported = {
730 FrameEvent::REQUESTED_PRESENT,
731 FrameEvent::ACQUIRE,
732 FrameEvent::LATCH,
733 FrameEvent::FIRST_REFRESH_START,
734 FrameEvent::LAST_REFRESH_START,
735 FrameEvent::GPU_COMPOSITION_DONE,
736 FrameEvent::DEQUEUE_READY,
737 FrameEvent::RELEASE,
738 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700739 ConditionalLock _l(mStateLock,
740 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700741 if (!getHwComposer().hasCapability(
742 HWC2::Capability::PresentFenceIsNotReliable)) {
743 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
744 }
745 return NO_ERROR;
746}
747
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800748status_t SurfaceFlinger::getDisplayState(const sp<IBinder>& displayToken, ui::DisplayState* state) {
749 if (!displayToken || !state) {
750 return BAD_VALUE;
751 }
752
753 Mutex::Autolock lock(mStateLock);
754
755 const auto display = getDisplayDeviceLocked(displayToken);
756 if (!display) {
757 return NAME_NOT_FOUND;
758 }
759
760 state->layerStack = display->getLayerStack();
761 state->orientation = display->getOrientation();
762
763 const Rect viewport = display->getViewport();
764 state->viewport = viewport.isValid() ? viewport.getSize() : display->getSize();
765
766 return NO_ERROR;
767}
768
769status_t SurfaceFlinger::getDisplayInfo(const sp<IBinder>& displayToken, DisplayInfo* info) {
770 if (!displayToken || !info) {
771 return BAD_VALUE;
772 }
773
774 Mutex::Autolock lock(mStateLock);
775
776 const auto display = getDisplayDeviceLocked(displayToken);
777 if (!display) {
778 return NAME_NOT_FOUND;
779 }
780
781 if (display->isVirtual()) {
782 return INVALID_OPERATION;
783 }
784
785 if (mEmulatedDisplayDensity) {
786 info->density = mEmulatedDisplayDensity;
787 } else {
788 info->density = display->isPrimary() ? mInternalDisplayDensity : FALLBACK_DENSITY;
789 }
790
791 info->secure = display->isSecure();
792
793 return NO_ERROR;
794}
795
Dominik Laskowski22488f62019-03-28 09:53:04 -0700796status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800797 Vector<DisplayConfig>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700798 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700799 return BAD_VALUE;
800 }
801
Dominik Laskowski22488f62019-03-28 09:53:04 -0700802 Mutex::Autolock lock(mStateLock);
803
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800804 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700805 if (!displayId) {
806 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700807 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700808
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800809 const bool isInternal = (displayId == getInternalDisplayIdLocked());
Mathias Agopian1604f772012-09-18 21:54:42 -0700810
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700812
Dominik Laskowski075d3172018-05-24 15:50:06 -0700813 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800814 DisplayConfig config;
Dan Stoza7f7da322014-05-02 15:26:25 -0700815
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800816 auto width = hwConfig->getWidth();
817 auto height = hwConfig->getHeight();
Dan Stoza7f7da322014-05-02 15:26:25 -0700818
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800819 auto xDpi = hwConfig->getDpiX();
820 auto yDpi = hwConfig->getDpiY();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700821
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800822 if (isInternal &&
823 (internalDisplayOrientation == ui::ROTATION_90 ||
824 internalDisplayOrientation == ui::ROTATION_270)) {
825 std::swap(width, height);
826 std::swap(xDpi, yDpi);
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 }
828
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800829 config.resolution = ui::Size(width, height);
Ady Abraham2139f732019-11-13 18:56:40 -0800830
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800831 if (mEmulatedDisplayDensity) {
832 config.xDpi = mEmulatedDisplayDensity;
833 config.yDpi = mEmulatedDisplayDensity;
834 } else {
835 config.xDpi = xDpi;
836 config.yDpi = yDpi;
837 }
838
839 const nsecs_t period = hwConfig->getVsyncPeriod();
840 config.refreshRate = 1e9f / period;
841
842 const auto offsets = mPhaseConfiguration->getOffsetsForRefreshRate(config.refreshRate);
843 config.appVsyncOffset = offsets.late.app;
844 config.sfVsyncOffset = offsets.late.sf;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800845
Andy McFadden91b2ca82014-06-13 14:04:23 -0700846 // This is how far in advance a buffer must be queued for
847 // presentation at a given time. If you want a buffer to appear
848 // on the screen at time N, you must submit the buffer before
849 // (N - presentationDeadline).
850 //
851 // Normally it's one full refresh period (to give SF a chance to
852 // latch the buffer), but this can be reduced by configuring a
853 // DispSync offset. Any additional delays introduced by the hardware
854 // composer or panel must be accounted for here.
855 //
856 // We add an additional 1ms to allow for processing time and
857 // differences between the ideal and actual refresh rate.
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800858 config.presentationDeadline = period - config.sfVsyncOffset + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700859
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -0800860 configs->push_back(config);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700861 }
862
Dan Stoza7f7da322014-05-02 15:26:25 -0700863 return NO_ERROR;
864}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700865
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700866status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
867 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700868 return BAD_VALUE;
869 }
870
Ana Krulecc2870422019-01-29 19:00:58 -0800871 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700872 return NO_ERROR;
873}
874
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700875int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
876 const auto display = getDisplayDevice(displayToken);
877 if (!display) {
878 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800879 return BAD_VALUE;
880 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700881
Steven Thomasc9098452019-09-30 17:15:05 -0700882 if (display->isPrimary()) {
883 std::lock_guard<std::mutex> lock(mActiveConfigLock);
884 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800885 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700886 }
Steven Thomasc9098452019-09-30 17:15:05 -0700887 }
Ady Abraham2139f732019-11-13 18:56:40 -0800888
889 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700890}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700891
Ady Abraham03b02dd2019-03-21 15:40:11 -0700892void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800893 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800894 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
895 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800896
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800897 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800898 // config twice. However event generation config might have changed so we need to update it
899 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800900 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700901 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
902 mDesiredActiveConfig = info;
903 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800904
905 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800906 // This will trigger HWC refresh without resetting the idle timer.
907 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700908 // Start receiving vsync samples now, so that we can detect a period
909 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800910 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700911 // As we called to set period, we will call to onRefreshRateChangeCompleted once
912 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700913 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800914
Ady Abraham9e16a482019-12-03 17:19:41 -0800915 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
916 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800917 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800918 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700919
920 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800921 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700922 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800923}
924
925status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
926 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800927
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100928 if (!displayToken) {
929 return BAD_VALUE;
930 }
Ady Abraham838de062019-02-04 10:24:03 -0800931
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100932 status_t result = NO_ERROR;
933
934 postMessageSync(new LambdaMessage([&]() {
935 const auto display = getDisplayDeviceLocked(displayToken);
936 if (!display) {
937 ALOGE("Attempt to set allowed display configs for invalid display token %p",
938 displayToken.get());
939 result = BAD_VALUE;
940 } else if (display->isVirtual()) {
941 ALOGW("Attempt to set allowed display configs for virtual display");
942 result = BAD_VALUE;
943 } else {
944 HwcConfigIndexType config(mode);
945 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
946 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
947 refreshRate.fps);
948 }
949 }));
950
951 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800952}
953
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800954void SurfaceFlinger::setActiveConfigInternal() {
955 ATRACE_CALL();
956
Dominik Laskowski22488f62019-03-28 09:53:04 -0700957 const auto display = getDefaultDisplayDeviceLocked();
958 if (!display) {
959 return;
960 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800961
Dominik Laskowski22488f62019-03-28 09:53:04 -0700962 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800963 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700964 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800965 display->setActiveConfig(mUpcomingActiveConfig.configId);
966
Ady Abraham2139f732019-11-13 18:56:40 -0800967 auto refreshRate =
968 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800969 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
970 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800971 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700972
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800973 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700974 const nsecs_t vsyncPeriod =
975 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
976 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800977 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700978 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800979 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800980}
981
Ady Abraham53852a52019-05-28 18:07:44 -0700982void SurfaceFlinger::desiredActiveConfigChangeDone() {
983 std::lock_guard<std::mutex> lock(mActiveConfigLock);
984 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
985 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700986
Kevin DuBois5988f482020-01-17 09:03:32 -0800987 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -0800988 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -0800989 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -0800990 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
991 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700992}
993
Dominik Laskowski22488f62019-03-28 09:53:04 -0700994bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800995 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800996 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -0800997 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700998 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800999 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -07001000 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001001 return true;
1002 }
1003
1004 // We received the present fence from the HWC, so we assume it successfully updated
1005 // the config, hence we update SF.
1006 mCheckPendingFence = false;
1007 setActiveConfigInternal();
1008 }
1009
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001010 // Store the local variable to release the lock.
1011 ActiveConfigInfo desiredActiveConfig;
1012 {
1013 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001014 if (!mDesiredActiveConfigChanged) {
1015 return false;
1016 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001017 desiredActiveConfig = mDesiredActiveConfig;
1018 }
1019
Ady Abraham2139f732019-11-13 18:56:40 -08001020 auto refreshRate =
1021 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1022 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1023 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001024 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001025 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1026 // display is not valid or we are already in the requested mode
1027 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001028 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001029 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001030 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001031
Ady Abraham838de062019-02-04 10:24:03 -08001032 // Desired active config was set, it is different than the config currently in use, however
1033 // allowed configs might have change by the time we process the refresh.
1034 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001035 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001036 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001037 return false;
1038 }
Alec Mouri7f015182019-07-11 13:56:22 -07001039
Ady Abrahamb838aed2019-02-12 15:30:16 -08001040 mUpcomingActiveConfig = desiredActiveConfig;
1041 const auto displayId = display->getId();
1042 LOG_ALWAYS_FATAL_IF(!displayId);
1043
Ady Abraham2139f732019-11-13 18:56:40 -08001044 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001045
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001046 // TODO(b/142753666) use constrains
1047 HWC2::VsyncPeriodChangeConstraints constraints;
1048 constraints.desiredTimeNanos = systemTime();
1049 constraints.seamlessRequired = false;
1050
1051 HWC2::VsyncPeriodChangeTimeline outTimeline;
1052 auto status =
1053 getHwComposer().setActiveConfigWithConstraints(*displayId,
1054 mUpcomingActiveConfig.configId.value(),
1055 constraints, &outTimeline);
1056 if (status != NO_ERROR) {
1057 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1058 return false;
1059 }
1060
1061 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1062 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001063 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001064 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001065}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001066
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001067status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1068 Vector<ColorMode>* outColorModes) {
1069 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001070 return BAD_VALUE;
1071 }
1072
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001074 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001075 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001076 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1077
1078 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1079 if (!displayId) {
1080 return NAME_NOT_FOUND;
1081 }
1082
Dominik Laskowski075d3172018-05-24 15:50:06 -07001083 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001084 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001085 }
Michael Wright28f24d02016-07-12 13:30:53 -07001086 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001087
1088 // If it's built-in display and the configuration claims it's not wide color capable,
1089 // filter out all wide color modes. The typical reason why this happens is that the
1090 // hardware is not good enough to support GPU composition of wide color, and thus the
1091 // OEMs choose to disable this capability.
1092 if (isInternalDisplay && !hasWideColorDisplay) {
1093 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1094 isWideColorMode);
1095 } else {
1096 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1097 }
Michael Wright28f24d02016-07-12 13:30:53 -07001098
1099 return NO_ERROR;
1100}
1101
Daniel Solomon42d04562019-01-20 21:03:19 -08001102status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1103 ui::DisplayPrimaries &primaries) {
1104 if (!displayToken) {
1105 return BAD_VALUE;
1106 }
1107
1108 // Currently we only support this API for a single internal display.
1109 if (getInternalDisplayToken() != displayToken) {
1110 return BAD_VALUE;
1111 }
1112
1113 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1114 return NO_ERROR;
1115}
1116
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001117ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1118 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001119 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001120 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001121 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001122}
1123
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001124status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001125 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126 Vector<ColorMode> modes;
1127 getDisplayColorModes(displayToken, &modes);
1128 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1129 if (mode < ColorMode::NATIVE || !exists) {
1130 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1131 decodeColorMode(mode).c_str(), mode, displayToken.get());
1132 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001133 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001134 const auto display = getDisplayDevice(displayToken);
1135 if (!display) {
1136 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1137 decodeColorMode(mode).c_str(), mode, displayToken.get());
1138 } else if (display->isVirtual()) {
1139 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1140 decodeColorMode(mode).c_str(), mode);
1141 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001142 display->getCompositionDisplay()->setColorProfile(
1143 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1144 RenderIntent::COLORIMETRIC,
1145 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001146 }
1147 }));
1148
Michael Wright28f24d02016-07-12 13:30:53 -07001149 return NO_ERROR;
1150}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001151
Galia Peycheva5492cb52019-10-30 14:13:16 +01001152status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1153 bool* outSupport) const {
1154 Mutex::Autolock _l(mStateLock);
1155
1156 if (!displayToken) {
1157 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1158 return BAD_VALUE;
1159 }
1160 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1161 if (!displayId) {
1162 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1163 displayToken.get());
1164 return NAME_NOT_FOUND;
1165 }
1166 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1167 HWC2::DisplayCapability::AutoLowLatencyMode);
1168 return NO_ERROR;
1169}
1170
1171void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1172 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1173}
1174
1175void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1176 if (!displayToken) {
1177 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1178 return;
1179 }
1180 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1181 if (!displayId) {
1182 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1183 displayToken.get());
1184 return;
1185 }
1186
1187 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1188}
1189
1190status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1191 bool* outSupport) const {
1192 Mutex::Autolock _l(mStateLock);
1193
1194 if (!displayToken) {
1195 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1196 return BAD_VALUE;
1197 }
1198 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1199 if (!displayId) {
1200 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1201 displayToken.get());
1202 return NAME_NOT_FOUND;
1203 }
1204
1205 std::vector<HWC2::ContentType> outSupportedContentTypes;
1206 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1207 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1208 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1209 return NO_ERROR;
1210}
1211
1212void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1213 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1214}
1215
1216void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1217 if (!displayToken) {
1218 ALOGE("setGameContentType() failed. Missing display token.");
1219 return;
1220 }
1221 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1222 if (!displayId) {
1223 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1224 displayToken.get());
1225 return;
1226 }
1227
1228 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1229 getHwComposer().setContentType(*displayId, type);
1230}
1231
Svetoslavd85084b2014-03-20 10:28:31 -07001232status_t SurfaceFlinger::clearAnimationFrameStats() {
1233 Mutex::Autolock _l(mStateLock);
1234 mAnimFrameTracker.clearStats();
1235 return NO_ERROR;
1236}
1237
1238status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1239 Mutex::Autolock _l(mStateLock);
1240 mAnimFrameTracker.getStats(outStats);
1241 return NO_ERROR;
1242}
1243
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001244status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1245 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001246 Mutex::Autolock _l(mStateLock);
1247
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001248 const auto display = getDisplayDeviceLocked(displayToken);
1249 if (!display) {
1250 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001251 return BAD_VALUE;
1252 }
1253
Peiyong Linfb069302018-04-25 14:34:31 -07001254 // At this point the DisplayDeivce should already be set up,
1255 // meaning the luminance information is already queried from
1256 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001257 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001258 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1259 capabilities.getDesiredMaxLuminance(),
1260 capabilities.getDesiredMaxAverageLuminance(),
1261 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001262
1263 return NO_ERROR;
1264}
1265
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001266status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1267 ui::PixelFormat* outFormat,
1268 ui::Dataspace* outDataspace,
1269 uint8_t* outComponentMask) const {
1270 if (!outFormat || !outDataspace || !outComponentMask) {
1271 return BAD_VALUE;
1272 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001273 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001274 if (!display || !display->getId()) {
1275 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1276 return BAD_VALUE;
1277 }
1278 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1279 outDataspace, outComponentMask);
1280}
1281
Kevin DuBois74e53772018-11-19 10:52:38 -08001282status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1283 bool enable, uint8_t componentMask,
1284 uint64_t maxFrames) const {
1285 const auto display = getDisplayDevice(displayToken);
1286 if (!display || !display->getId()) {
1287 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1288 return BAD_VALUE;
1289 }
1290
1291 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1292 componentMask, maxFrames);
1293}
1294
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001295status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1296 uint64_t maxFrames, uint64_t timestamp,
1297 DisplayedFrameStats* outStats) const {
1298 const auto display = getDisplayDevice(displayToken);
1299 if (!display || !display->getId()) {
1300 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1301 return BAD_VALUE;
1302 }
1303
1304 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1305 outStats);
1306}
1307
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001308status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1309 if (!outSupported) {
1310 return BAD_VALUE;
1311 }
1312 *outSupported = getRenderEngine().supportsProtectedContent();
1313 return NO_ERROR;
1314}
1315
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001316status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1317 bool* outIsWideColorDisplay) const {
1318 if (!displayToken || !outIsWideColorDisplay) {
1319 return BAD_VALUE;
1320 }
1321 Mutex::Autolock _l(mStateLock);
1322 const auto display = getDisplayDeviceLocked(displayToken);
1323 if (!display) {
1324 return BAD_VALUE;
1325 }
Peiyong Linff84a152019-05-17 18:36:19 -07001326
1327 // Use hasWideColorDisplay to override built-in display.
1328 const auto displayId = display->getId();
1329 if (displayId && displayId == getInternalDisplayIdLocked()) {
1330 *outIsWideColorDisplay = hasWideColorDisplay;
1331 return NO_ERROR;
1332 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001333 *outIsWideColorDisplay = display->hasWideColorGamut();
1334 return NO_ERROR;
1335}
1336
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001337status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001338 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001339 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001340
Dominik Laskowski6505f792019-09-18 11:10:05 -07001341 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1342 mEventQueue->setEventConnection(
1343 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001344 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001345 }));
1346
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001347 return NO_ERROR;
1348}
1349
1350status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001351 Mutex::Autolock lock(mStateLock);
1352 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001353}
1354
Lloyd Pique755e3192018-01-31 16:46:15 -08001355status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1356 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001357 // Try to acquire a lock for 1s, fail gracefully
1358 const status_t err = mStateLock.timedLock(s2ns(1));
1359 const bool locked = (err == NO_ERROR);
1360 if (!locked) {
1361 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1362 return TIMED_OUT;
1363 }
1364
1365 outLayers->clear();
1366 mCurrentState.traverseInZOrder([&](Layer* layer) {
1367 outLayers->push_back(layer->getLayerDebugInfo());
1368 });
1369
1370 mStateLock.unlock();
1371 return NO_ERROR;
1372}
1373
Peiyong Linc6780972018-10-28 15:24:08 -07001374status_t SurfaceFlinger::getCompositionPreference(
1375 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1376 Dataspace* outWideColorGamutDataspace,
1377 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001378 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001379 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001380 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001381 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001382 return NO_ERROR;
1383}
1384
Dan Stozaec460082018-12-17 15:35:09 -08001385status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1386 const sp<IBinder>& stopLayerHandle,
1387 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001388 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001389 return BAD_VALUE;
1390 }
1391 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001392 return NO_ERROR;
1393}
1394
Dan Stozaec460082018-12-17 15:35:09 -08001395status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001396 if (!listener) {
1397 return BAD_VALUE;
1398 }
Dan Stozaec460082018-12-17 15:35:09 -08001399 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001400 return NO_ERROR;
1401}
Dan Gittik57e63c52019-01-18 16:37:54 +00001402
1403status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1404 bool* outSupport) const {
1405 if (!displayToken || !outSupport) {
1406 return BAD_VALUE;
1407 }
1408 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1409 if (!displayId) {
1410 return NAME_NOT_FOUND;
1411 }
1412 *outSupport =
1413 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1414 return NO_ERROR;
1415}
1416
1417status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1418 float brightness) const {
1419 if (!displayToken) {
1420 return BAD_VALUE;
1421 }
1422 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1423 if (!displayId) {
1424 return NAME_NOT_FOUND;
1425 }
1426 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1427}
1428
Ady Abraham8532d012019-05-08 14:50:56 -07001429status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1430 PowerHint powerHint = static_cast<PowerHint>(hintId);
1431
1432 if (powerHint == PowerHint::INTERACTION) {
1433 mScheduler->notifyTouchEvent();
1434 }
1435
1436 return NO_ERROR;
1437}
1438
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001439// ----------------------------------------------------------------------------
1440
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001441sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001442 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001443 const auto& handle =
1444 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001445
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001446 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001447}
1448
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001449// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001450
1451void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001452 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001453}
1454
1455void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001456 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001457 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001458}
1459
1460void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001461 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001462 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001463}
1464
1465void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001466 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001467 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001468}
1469
1470status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001471 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001472 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001473}
1474
1475status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001476 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001477 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001478 if (res == NO_ERROR) {
1479 msg->wait();
1480 }
1481 return res;
1482}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001483
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001484void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001485 do {
1486 waitForEvent();
1487 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001488}
1489
Dominik Laskowski83b88212018-12-11 13:34:06 -08001490nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001491 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001492 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1493 return 0;
1494 }
1495
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001496 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001497}
1498
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001499void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001500 int64_t timestamp,
1501 std::optional<hwc2_vsync_period_t> /*vsyncPeriod*/) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001502 ATRACE_NAME("SF onVsync");
1503
Ady Abraham7159f572019-10-11 11:10:18 -07001504 // TODO(b/140201379): use vsyncPeriod in the new DispSync
1505
Steven Thomas3cfac282017-02-06 12:29:30 -08001506 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001507 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001508 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001509 return;
1510 }
1511
Dominik Laskowski075d3172018-05-24 15:50:06 -07001512 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001513 return;
1514 }
1515
Dominik Laskowski075d3172018-05-24 15:50:06 -07001516 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001517 // For now, we don't do anything with external display vsyncs.
1518 return;
1519 }
1520
Alec Mourif8e689c2019-05-20 18:32:22 -07001521 bool periodFlushed = false;
1522 mScheduler->addResyncSample(timestamp, &periodFlushed);
1523 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001524 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001525 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001526}
1527
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001528void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001529 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1530 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001531}
1532
Ady Abraham2139f732019-11-13 18:56:40 -08001533bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001534 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001535}
1536
Ady Abraham2139f732019-11-13 18:56:40 -08001537void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1538 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001539 const auto display = getDefaultDisplayDeviceLocked();
1540 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001541 return;
1542 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001543 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001544
Ana Krulec7d1d6832018-12-27 11:10:09 -08001545 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001546 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1547 ALOGV("Skipping config %d as it is not part of allowed configs",
1548 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001549 return;
1550 }
1551
Ady Abraham2139f732019-11-13 18:56:40 -08001552 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001553}
1554
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001555void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001556 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001557 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001558 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001559
Lloyd Piqueba04e622017-12-14 17:11:26 -08001560 // Ignore events that do not have the right sequenceId.
1561 if (sequenceId != getBE().mComposerSequenceId) {
1562 return;
1563 }
1564
Steven Thomasb02664d2017-07-26 18:48:28 -07001565 // Only lock if we're not on the main thread. This function is normally
1566 // called on a hwbinder thread, but for the primary display it's called on
1567 // the main thread with the state lock already held, so don't attempt to
1568 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001569 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001570
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001571 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001572
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001573 if (std::this_thread::get_id() == mMainThreadId) {
1574 // Process all pending hot plug events immediately if we are on the main thread.
1575 processDisplayHotplugEventsLocked();
1576 }
1577
Lloyd Piqueba04e622017-12-14 17:11:26 -08001578 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001579}
1580
Ady Abraham7159f572019-10-11 11:10:18 -07001581void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001582 int32_t sequenceId, hwc2_display_t /*display*/,
1583 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1584 Mutex::Autolock lock(mStateLock);
1585 if (sequenceId != getBE().mComposerSequenceId) {
1586 return;
1587 }
1588 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001589}
1590
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001591void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1592 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1593 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1594}
1595
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001596void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001597 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001598 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001599 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001600 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001601 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001602}
1603
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001604void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001605 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001606
1607 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1608 // display power state.
1609 postMessageAsync(new LambdaMessage(
1610 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1611}
1612
1613void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1614 ATRACE_CALL();
1615
Ady Abraham27c70212019-06-11 10:52:26 -07001616 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1617
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001618 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001619 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1620 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001621 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001622 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001623 }
Mathias Agopian86303202012-07-24 22:46:10 -07001624}
1625
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001626// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001627void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001628 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001629 // Clear the drawing state so that the logic inside of
1630 // handleTransactionLocked will fire. It will determine the delta between
1631 // mCurrentState and mDrawingState and re-apply all changes when we make the
1632 // transition.
1633 mDrawingState.displays.clear();
1634 mDisplays.clear();
1635}
1636
Steven Thomas050b2c82017-03-06 11:45:16 -08001637void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001638 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001639 if (!mVrFlinger)
1640 return;
1641 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001642 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001643 return;
1644 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001645
Lloyd Pique441d5042018-10-18 16:49:51 -07001646 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001647 ALOGE("Vr flinger is only supported for remote hardware composer"
1648 " service connections. Ignoring request to transition to vr"
1649 " flinger.");
1650 mVrFlingerRequestsDisplay = false;
1651 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001652 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001653
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001654 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001655
Steven Thomas0123ac62018-07-12 11:32:34 -07001656 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001657 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001658
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001659 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001660
1661 // Clear out all the output layers from the composition engine for all
1662 // displays before destroying the hardware composer interface. This ensures
1663 // any HWC layers are destroyed through that interface before it becomes
1664 // invalid.
1665 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001666 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001667 }
1668
Steven Thomas0123ac62018-07-12 11:32:34 -07001669 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1670 // called below. Clear the reference now so we don't accidentally use it
1671 // later.
1672 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001673
Steven Thomasb02664d2017-07-26 18:48:28 -07001674 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001675 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001676 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001677
Steven Thomasb02664d2017-07-26 18:48:28 -07001678 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001679 // Delete the current instance before creating the new one
1680 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1681 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1682 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1683 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001684
Lloyd Pique441d5042018-10-18 16:49:51 -07001685 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001686 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001687
1688 if (vrFlingerRequestsDisplay) {
1689 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001690 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001691
1692 mVisibleRegionsDirty = true;
1693 invalidateHwcGeometry();
1694
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001695 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001696 display = getDefaultDisplayDeviceLocked();
1697 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001698 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001699
Steven Thomasb02664d2017-07-26 18:48:28 -07001700 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001701 const nsecs_t vsyncPeriod = getVsyncPeriod();
1702 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001703
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001704 // The present fences returned from vr_hwc are not an accurate
1705 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001706 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001707
Steven Thomasb02664d2017-07-26 18:48:28 -07001708 // Use phase of 0 since phase is not known.
1709 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001710 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001711 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001712
Ana Krulecc2870422019-01-29 19:00:58 -08001713 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001714
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001715 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001716 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001717}
1718
Ady Abraham11579302019-09-19 12:35:58 -07001719bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1720 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001721 // We are storing the last 2 present fences. If sf's phase offset is to be
1722 // woken up before the actual vsync but targeting the next vsync, we need to check
1723 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001724 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1725 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001726
Ady Abraham11579302019-09-19 12:35:58 -07001727 if (fence == Fence::NO_FENCE) {
1728 return false;
1729 }
1730
1731 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1732 fence->wait(graceTimeMs);
1733 }
1734
1735 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001736}
1737
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001738void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001739 DisplayStatInfo stats;
1740 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001741 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001742 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001743 mExpectedPresentTime.store(
1744 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001745}
1746
Dominik Laskowski22488f62019-03-28 09:53:04 -07001747void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001748 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001749 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001750 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001751 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001752 // calculate the expected present time once and use the cached
1753 // value throughout this frame to make sure all layers are
1754 // seeing this same value.
1755 populateExpectedPresentTime();
1756
Ady Abraham11579302019-09-19 12:35:58 -07001757 // When Backpressure propagation is enabled we want to give a small grace period
1758 // for the present fence to fire instead of just giving up on this frame to handle cases
1759 // where present fence is just about to get signaled.
1760 const int graceTimeForPresentFenceMs =
1761 (mPropagateBackpressure &&
1762 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1763 ? 1
1764 : 0;
1765 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1766 previousFrameMissed(
1767 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001768 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1769 mHadDeviceComposition && frameMissed};
1770 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1771 mHadClientComposition && frameMissed};
1772
Alec Mouricc0fc602019-02-26 21:45:19 -08001773 if (frameMissed) {
1774 mFrameMissedCount++;
1775 mTimeStats->incrementMissedFrames();
1776 }
1777
Alec Mouri40189b02019-03-05 15:07:54 -08001778 if (hwcFrameMissed) {
1779 mHwcFrameMissedCount++;
1780 }
1781
1782 if (gpuFrameMissed) {
1783 mGpuFrameMissedCount++;
1784 }
1785
Ady Abrahamadb9a992019-09-19 21:21:55 +00001786 if (frameMissed && mPropagateBackpressure) {
1787 if ((hwcFrameMissed && !gpuFrameMissed) ||
1788 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001789 signalLayerUpdate();
1790 break;
1791 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001792 }
Dan Stoza50182882016-07-08 12:02:20 -07001793
Steven Thomas050b2c82017-03-06 11:45:16 -08001794 // Now that we're going to make it to the handleMessageTransaction()
1795 // call below it's safe to call updateVrFlinger(), which will
1796 // potentially trigger a display handoff.
1797 updateVrFlinger();
1798
Dan Stoza6b9454d2014-11-07 16:00:59 -08001799 bool refreshNeeded = handleMessageTransaction();
1800 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001801
Ana Krulecc84d09b2019-11-02 23:10:29 +01001802 // Layers need to get updated (in the previous line) before we can use them for
1803 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001804 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1805 // and may eventually call to ~Layer() if it holds the last reference
1806 {
1807 Mutex::Autolock _l(mStateLock);
1808 mScheduler->chooseRefreshRateForContent();
1809 }
1810
Ana Krulecc84d09b2019-11-02 23:10:29 +01001811 if (performSetActiveConfig()) {
1812 break;
1813 }
1814
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001815 updateCursorAsync();
1816 updateInputFlinger();
1817
Dan Stoza58784442014-12-02 16:58:17 -08001818 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001819 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001820 // Signal a refresh if a transaction modified the window state,
1821 // a new buffer was latched, or if HWC has requested a full
1822 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001823 if (mFrameStartTime <= 0) {
1824 // We should only use the time of the first invalidate
1825 // message that signals a refresh as the beginning of the
1826 // frame. Otherwise the real frame time will be
1827 // underestimated.
1828 mFrameStartTime = frameStart;
1829 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001830 signalRefresh();
1831 }
1832 break;
1833 }
1834 case MessageQueue::REFRESH: {
1835 handleMessageRefresh();
1836 break;
1837 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001838 }
1839}
1840
Dan Stoza6b9454d2014-11-07 16:00:59 -08001841bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001842 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001843 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001844
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001845 bool flushedATransaction = flushTransactionQueues();
1846
1847 bool runHandleTransaction = transactionFlags &&
1848 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1849
1850 if (runHandleTransaction) {
1851 handleTransaction(eTransactionMask);
1852 } else {
1853 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001854 }
1855
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001856 if (transactionFlushNeeded()) {
1857 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001858 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001859
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001860 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001861}
1862
Mathias Agopian4fec8732012-06-29 14:12:52 -07001863void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001865
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001866 mRefreshPending = false;
1867
Lloyd Piqueab039b52019-02-13 14:22:42 -08001868 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001869 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001870 for (const auto& [_, display] : mDisplays) {
1871 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1872 }
1873 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1874 auto compositionLayer = layer->getCompositionLayer();
1875 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1876 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001877 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1878 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1879 auto compositionLayer = layer->getCompositionLayer();
Adithya Srinivasan87c1b80e2019-11-21 11:43:06 -08001880 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001881 }
1882
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001883 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001884 refreshArgs.outputColorSetting = useColorManagement
1885 ? mDisplayColorSetting
1886 : compositionengine::OutputColorSetting::kUnmanaged;
1887 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1888 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001889
1890 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1891 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001892
1893 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1894 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1895 mDrawingState.colorMatrixChanged = false;
1896 }
1897
1898 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1899
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001900 if (mDebugRegion != 0) {
1901 refreshArgs.devOptFlashDirtyRegionsDelay =
1902 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1903 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001904
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001905 mGeometryInvalid = false;
1906
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001907 // Store the present time just before calling to the composition engine so we could notify
1908 // the scheduler.
1909 const auto presentTime = systemTime();
1910
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001911 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001912 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1913 // Reset the frame start time now that we've recorded this frame.
1914 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001915
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001916 mScheduler->onDisplayRefreshed(presentTime);
1917
David Sodmanfa9b2af2017-12-24 13:28:59 -08001918 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001919 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001920
Lloyd Pique66d68602019-02-13 14:23:31 -08001921 mHadClientComposition =
1922 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1923 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001924 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
1925 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08001926 });
1927 mHadDeviceComposition =
1928 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1929 auto& displayDevice = tokenDisplayPair.second;
1930 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1931 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08001932 mReusedClientComposition =
1933 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1934 auto& displayDevice = tokenDisplayPair.second;
1935 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
1936 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001937
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001938 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001939
David Sodman7e4ae112018-02-09 15:02:28 -08001940 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001941 if (mVisibleRegionsDirty) {
1942 mVisibleRegionsDirty = false;
1943 if (mTracingEnabled) {
1944 mTracing.notify("visibleRegionsDirty");
1945 }
1946 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001947
1948 if (mCompositionEngine->needsAnotherUpdate()) {
1949 signalLayerUpdate();
1950 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001951}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001952
David Sodmanfa9b2af2017-12-24 13:28:59 -08001953
1954bool SurfaceFlinger::handleMessageInvalidate() {
1955 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001956 bool refreshNeeded = handlePageFlip();
1957
Vishnu Nair4351ad52019-02-11 14:13:02 -08001958 if (mVisibleRegionsDirty) {
1959 computeLayerBounds();
1960 }
1961
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001962 for (auto& layer : mLayersPendingRefresh) {
1963 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001964 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001965 invalidateLayerStack(layer, visibleReg);
1966 }
1967 mLayersPendingRefresh.clear();
1968 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001969}
1970
Ana Krulece588e312018-09-18 12:32:24 -07001971void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1972 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001973 // Update queue of past composite+present times and determine the
1974 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001975 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001976 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001977 while (!getBE().mCompositePresentTimes.empty()) {
1978 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001979 // Cached values should have been updated before calling this method,
1980 // which helps avoid duplicate syscalls.
1981 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1982 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1983 break;
1984 }
1985 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001986 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001987 }
1988
1989 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001990 while (getBE().mCompositePresentTimes.size() > 16) {
1991 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001992 }
1993
Ana Krulece588e312018-09-18 12:32:24 -07001994 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001995}
1996
Ana Krulece588e312018-09-18 12:32:24 -07001997void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1998 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001999 // Integer division and modulo round toward 0 not -inf, so we need to
2000 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08002001 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
2002 ? (stats.vsyncPeriod -
2003 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
2004 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002005
Ady Abraham9e16a482019-12-03 17:19:41 -08002006 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08002007 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07002008 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08002009 }
2010
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002011 // Snap the latency to a value that removes scheduling jitter from the
2012 // composition and present times, which often have >1ms of jitter.
2013 // Reducing jitter is important if an app attempts to extrapolate
2014 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08002015 // Snapping also allows an app to precisely calculate
2016 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07002017 nsecs_t bias = stats.vsyncPeriod / 2;
2018 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
2019 nsecs_t snappedCompositeToPresentLatency =
2020 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002021
David Sodman99974d22017-11-28 12:04:33 -08002022 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002023 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2024 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002025 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002026}
2027
David Sodman2b406362017-12-15 13:33:47 -08002028void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002029{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002030 ATRACE_CALL();
2031 ALOGV("postComposition");
2032
Brian Anderson3546a3f2016-07-14 11:51:14 -07002033 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002034 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002035 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002036 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002037 }
2038
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002039 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002040 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002041
David Sodman73beded2017-11-15 11:56:06 -08002042 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002043 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002044 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002045 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002046 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2047 ->getRenderSurface()
2048 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002049 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002050 } else {
2051 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2052 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002053
David Sodman73beded2017-11-15 11:56:06 -08002054 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002055 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2056 mPreviousPresentFences[0] = displayDevice
2057 ? getHwComposer().getPresentFence(*displayDevice->getId())
2058 : Fence::NO_FENCE;
2059 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002060 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002061
Ana Krulece588e312018-09-18 12:32:24 -07002062 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002063 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002064
Lloyd Piqueab039b52019-02-13 14:22:42 -08002065 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2066 // be sampled a little later than when we started doing work for this frame,
2067 // but that should be okay since updateCompositorTiming has snapping logic.
2068 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2069 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002070 CompositorTiming compositorTiming;
2071 {
David Sodman99974d22017-11-28 12:04:33 -08002072 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2073 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002074 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002075
Edgar Arriaga844fa672020-01-16 14:21:42 -08002076 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002077 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2078 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002079 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002080 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002081 }
Robert Carr2047fae2016-11-28 14:09:09 -08002082 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002083
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002084 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002085 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002086 }
2087
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002088 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002089 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2090 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002091 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002092 }
2093 }
2094
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002095 if (mAnimCompositionPending) {
2096 mAnimCompositionPending = false;
2097
Brian Anderson4e606e32017-03-16 15:34:57 -07002098 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002099 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002100 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002101 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002102 // The HWC doesn't support present fences, so use the refresh
2103 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002104 const nsecs_t presentTime =
2105 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002106 mAnimFrameTracker.setActualPresentTime(presentTime);
2107 }
2108 mAnimFrameTracker.advanceFrame();
2109 }
Dan Stozab90cf072015-03-05 11:05:59 -08002110
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002111 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002112 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002113 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002114 }
2115
Vishnu Nair9b079a22020-01-21 14:36:08 -08002116 if (mReusedClientComposition) {
2117 mTimeStats->incrementClientCompositionReusedFrames();
2118 }
2119
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002120 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002121
Lloyd Pique32cbe282018-10-19 13:09:22 -07002122 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2123 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002124 return;
2125 }
2126
2127 nsecs_t currentTime = systemTime();
2128 if (mHasPoweredOff) {
2129 mHasPoweredOff = false;
2130 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002131 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002132 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002133 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2134 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002135 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002136 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002137 }
David Sodman4a36e932017-11-07 14:29:47 -08002138 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002139 }
David Sodman4a36e932017-11-07 14:29:47 -08002140 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002141
2142 {
2143 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002144 if (mTexturePool.size() < mTexturePoolSize) {
2145 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002146 const size_t offset = mTexturePool.size();
2147 mTexturePool.resize(mTexturePoolSize);
2148 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2149 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002150 } else if (mTexturePool.size() > mTexturePoolSize) {
2151 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2152 const size_t offset = mTexturePoolSize;
2153 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2154 mTexturePool.resize(mTexturePoolSize);
2155 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002156 }
2157 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002158
Ady Abrahambe0f9482019-04-24 15:41:53 -07002159 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002160 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002161
Kevin DuBois413287f2019-02-25 08:46:47 -08002162 if (mLumaSampling && mRegionSamplingThread) {
2163 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002164 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002165
2166 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2167 // side-effect of getTotalSize(), so we check that again here
2168 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002169 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002170 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2171 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002172}
2173
Vishnu Nair4351ad52019-02-11 14:13:02 -08002174void SurfaceFlinger::computeLayerBounds() {
2175 for (const auto& pair : mDisplays) {
2176 const auto& displayDevice = pair.second;
2177 const auto display = displayDevice->getCompositionDisplay();
2178 for (const auto& layer : mDrawingState.layersSortedByZ) {
2179 // only consider the layers on the given layer stack
2180 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002181 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002182 }
2183
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002184 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2185 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002186 }
2187 }
2188}
2189
David Sodmanfa9b2af2017-12-24 13:28:59 -08002190void SurfaceFlinger::postFrame()
2191{
2192 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002193 const auto display = getDefaultDisplayDeviceLocked();
2194 if (display && getHwComposer().isConnected(*display->getId())) {
2195 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002196 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2197 logFrameStats();
2198 }
2199 }
2200}
2201
Mathias Agopian87baae12012-07-31 12:38:26 -07002202void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002203{
Mathias Agopian841cde52012-03-01 15:44:37 -08002204 ATRACE_CALL();
2205
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002206 // here we keep a copy of the drawing state (that is the state that's
2207 // going to be overwritten by handleTransactionLocked()) outside of
2208 // mStateLock so that the side-effects of the State assignment
2209 // don't happen with mStateLock held (which can cause deadlocks).
2210 State drawingState(mDrawingState);
2211
Mathias Agopianca4d3602011-05-19 15:38:14 -07002212 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002213 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002214
Mathias Agopianca4d3602011-05-19 15:38:14 -07002215 // Here we're guaranteed that some transaction flags are set
2216 // so we can call handleTransactionLocked() unconditionally.
2217 // We call getTransactionFlags(), which will also clear the flags,
2218 // with mStateLock held to guarantee that mCurrentState won't change
2219 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002220
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002221 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002222 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002223 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002224
Mathias Agopianca4d3602011-05-19 15:38:14 -07002225 mDebugInTransaction = 0;
2226 invalidateHwcGeometry();
2227 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002228}
2229
Lloyd Piqueba04e622017-12-14 17:11:26 -08002230void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2231 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002232 const std::optional<DisplayIdentificationInfo> info =
2233 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002234
Dominik Laskowski075d3172018-05-24 15:50:06 -07002235 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002236 continue;
2237 }
2238
Lloyd Piqueba04e622017-12-14 17:11:26 -08002239 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002240 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002241 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002242 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2243 initScheduler(info->id);
2244 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002245 mPhysicalDisplayTokens[info->id] = new BBinder();
2246 DisplayDeviceState state;
2247 state.displayId = info->id;
2248 state.isSecure = true; // All physical displays are currently considered secure.
2249 state.displayName = info->name;
2250 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2251 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002252 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002253 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002254 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002255
Dominik Laskowski075d3172018-05-24 15:50:06 -07002256 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2257 if (index >= 0) {
2258 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2259 mInterceptor->saveDisplayDeletion(state.sequenceId);
2260 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002261 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002262 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002263 }
2264
2265 processDisplayChangesLocked();
2266 }
2267
2268 mPendingHotplugEvents.clear();
2269}
2270
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002271void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002272 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2273 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002274}
2275
Lloyd Pique99d3da52018-01-22 17:48:03 -08002276sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002277 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002278 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002279 const sp<IGraphicBufferProducer>& producer) {
2280 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002281 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002282 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002283 creationArgs.isSecure = state.isSecure;
2284 creationArgs.displaySurface = dispSurface;
2285 creationArgs.hasWideColorGamut = false;
2286 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002287 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002288
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002289 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002290 creationArgs.isPrimary = isInternalDisplay;
2291
2292 if (useColorManagement && displayId) {
2293 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002294 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002295 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002296 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002297 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002298
Dominik Laskowski7e045462018-05-30 13:02:02 -07002299 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002300 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002301 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002302 }
tangrobin6753a022018-08-10 10:58:54 +08002303 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002304
Dominik Laskowski075d3172018-05-24 15:50:06 -07002305 if (displayId) {
2306 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002307 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002308 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002309 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002310
Lloyd Pique90c115d2018-09-18 21:39:42 -07002311 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002312 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002313 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002314
Lloyd Pique99d3da52018-01-22 17:48:03 -08002315 // Make sure that composition can never be stalled by a virtual display
2316 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002317 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002318 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002319 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2320 }
2321
Dominik Laskowski718f9602019-11-09 20:01:35 -08002322 creationArgs.physicalOrientation =
2323 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002324
Lloyd Pique99d3da52018-01-22 17:48:03 -08002325 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002326 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002327
Lloyd Pique90c115d2018-09-18 21:39:42 -07002328 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002329
2330 if (maxFrameBufferAcquiredBuffers >= 3) {
2331 nativeWindowSurface->preallocateBuffers();
2332 }
2333
2334 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002335 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002336 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002337 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002338 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002339 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002340 display->getCompositionDisplay()->setColorProfile(
2341 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2342 RenderIntent::COLORIMETRIC,
2343 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002344 if (!state.isVirtual()) {
2345 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002346 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2347 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002348 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002349
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002350 display->setLayerStack(state.layerStack);
2351 display->setProjection(state.orientation, state.viewport, state.frame);
2352 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002353
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002354 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002355}
2356
Lloyd Pique347200f2017-12-14 17:00:15 -08002357void SurfaceFlinger::processDisplayChangesLocked() {
2358 // here we take advantage of Vector's copy-on-write semantics to
2359 // improve performance by skipping the transaction entirely when
2360 // know that the lists are identical
2361 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2362 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2363 if (!curr.isIdenticalTo(draw)) {
2364 mVisibleRegionsDirty = true;
2365 const size_t cc = curr.size();
2366 size_t dc = draw.size();
2367
2368 // find the displays that were removed
2369 // (ie: in drawing state but not in current state)
2370 // also handle displays that changed
2371 // (ie: displays that are in both lists)
2372 for (size_t i = 0; i < dc;) {
2373 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2374 if (j < 0) {
2375 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002376 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002377 // Save display ID before disconnecting.
2378 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002379 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002380
2381 if (!display->isVirtual()) {
2382 LOG_ALWAYS_FATAL_IF(!displayId);
2383 dispatchDisplayHotplugEvent(displayId->value, false);
2384 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002385 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002386
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002387 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002388 } else {
2389 // this display is in both lists. see if something changed.
2390 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002391 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002392 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2393 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2394 if (state_binder != draw_binder) {
2395 // changing the surface is like destroying and
2396 // recreating the DisplayDevice, so we just remove it
2397 // from the drawing state, so that it get re-added
2398 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002399 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002400 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002401 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002402 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002403 mDrawingState.displays.removeItemsAt(i);
2404 dc--;
2405 // at this point we must loop to the next item
2406 continue;
2407 }
2408
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002409 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002410 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002411 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002412 }
2413 if ((state.orientation != draw[i].orientation) ||
2414 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002415 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002416 }
2417 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002418 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002419 if (display->isPrimary()) {
2420 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2421 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002422 }
2423 }
2424 }
2425 ++i;
2426 }
2427
2428 // find displays that were added
2429 // (ie: in current state but not in drawing state)
2430 for (size_t i = 0; i < cc; i++) {
2431 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2432 const DisplayDeviceState& state(curr[i]);
2433
Lloyd Pique542307f2018-10-19 13:24:08 -07002434 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002435 sp<IGraphicBufferProducer> producer;
2436 sp<IGraphicBufferProducer> bqProducer;
2437 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002438 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002439
Dominik Laskowski075d3172018-05-24 15:50:06 -07002440 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002441 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002442 // Virtual displays without a surface are dormant:
2443 // they have external state (layer stack, projection,
2444 // etc.) but no internal state (i.e. a DisplayDevice).
2445 if (state.surface != nullptr) {
2446 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002447 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002448 int width = 0;
2449 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2450 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2451 int height = 0;
2452 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2453 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2454 int intFormat = 0;
2455 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2456 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002457 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002458
Dominik Laskowski075d3172018-05-24 15:50:06 -07002459 displayId =
2460 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002461 }
2462
2463 // TODO: Plumb requested format back up to consumer
2464
2465 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002466 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002467 bqProducer, bqConsumer,
2468 state.displayName);
2469
2470 dispSurface = vds;
2471 producer = vds;
2472 }
2473 } else {
2474 ALOGE_IF(state.surface != nullptr,
2475 "adding a supported display, but rendering "
2476 "surface is provided (%p), ignoring it",
2477 state.surface.get());
2478
Dominik Laskowski075d3172018-05-24 15:50:06 -07002479 displayId = state.displayId;
2480 LOG_ALWAYS_FATAL_IF(!displayId);
2481 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002482 producer = bqProducer;
2483 }
2484
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002485 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002486 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002487 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002488 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002489 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002490 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002491 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002492 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002493 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002494
2495 const auto displayDevice = mDisplays[displayToken];
2496 if (displayDevice->isPrimary()) {
2497 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2498 displayDevice->getHeight());
2499 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002500 }
2501 }
2502 }
2503 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002504
2505 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002506}
2507
Mathias Agopian87baae12012-07-31 12:38:26 -07002508void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002509{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002510 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2511
Dan Stoza7dde5992015-05-22 09:51:44 -07002512 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002513 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002514 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002515 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002516
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002517 /*
2518 * Traversal of the children
2519 * (perform the transaction for each of them if needed)
2520 */
2521
Marissa Wall06255332019-03-27 13:48:27 -07002522 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002523 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002524 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002525 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526
2527 const uint32_t flags = layer->doTransaction(0);
2528 if (flags & Layer::eVisibleRegion)
2529 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002530
2531 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002532 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002533 }
Robert Carr2047fae2016-11-28 14:09:09 -08002534 });
Marissa Wall06255332019-03-27 13:48:27 -07002535 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002536 }
2537
2538 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002539 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002540 */
2541
Mathias Agopiane57f2922012-08-09 16:29:12 -07002542 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002543 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002544 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002545 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002546
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002547 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002548 // The transform hint might have changed for some layers
2549 // (either because a display has changed, or because a layer
2550 // as changed).
2551 //
2552 // Walk through all the layers in currentLayers,
2553 // and update their transform hint.
2554 //
2555 // If a layer is visible only on a single display, then that
2556 // display is used to calculate the hint, otherwise we use the
2557 // default display.
2558 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002559 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002560 // the hint is set before we acquire a buffer from the surface texture.
2561 //
2562 // NOTE: layer transactions have taken place already, so we use their
2563 // drawing state. However, SurfaceFlinger's own transaction has not
2564 // happened yet, so we must use the current state layer list
2565 // (soon to become the drawing state list).
2566 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002567 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002568 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002569 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002570 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002571 // NOTE: we rely on the fact that layers are sorted by
2572 // layerStack first (so we don't have to traverse the list
2573 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002574 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002575 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002576 currentlayerStack = layerStack;
2577 // figure out if this layerstack is mirrored
2578 // (more than one display) if so, pick the default display,
2579 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002580 hintDisplay = nullptr;
2581 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002582 if (display->getCompositionDisplay()
2583 ->belongsInOutput(layer->getLayerStack(),
2584 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002585 if (hintDisplay) {
2586 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002587 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002588 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002589 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002590 }
2591 }
2592 }
2593 }
Chet Haase91d25932013-04-11 15:24:55 -07002594
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002595 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002596 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2597 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002598
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002599 // could be null when this layer is using a layerStack
2600 // that is not visible on any display. Also can occur at
2601 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002602 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002603 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002604
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002605 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002606 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002607 if (hintDisplay) {
2608 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002609 }
Robert Carr2047fae2016-11-28 14:09:09 -08002610
2611 first = false;
2612 });
Mathias Agopian84300952012-11-21 16:02:13 -08002613 }
2614
2615
Mathias Agopian3559b072012-08-15 13:46:03 -07002616 /*
2617 * Perform our own transaction if needed
2618 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002619
2620 if (mLayersAdded) {
2621 mLayersAdded = false;
2622 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002623 mVisibleRegionsDirty = true;
2624 }
2625
2626 // some layers might have been removed, so
2627 // we need to update the regions they're exposing.
2628 if (mLayersRemoved) {
2629 mLayersRemoved = false;
2630 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002631 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002632 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002633 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002634 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002635 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002636 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002637 }
Robert Carr2047fae2016-11-28 14:09:09 -08002638 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002639 }
2640
Vishnu Nairec0ab382019-02-13 15:32:56 -08002641 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002642 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002643}
2644
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002645void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002646 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002647 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002648 return;
2649 }
2650
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002651 if (mVisibleRegionsDirty || mInputInfoChanged) {
2652 mInputInfoChanged = false;
2653 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002654 } else if (mInputWindowCommands.syncInputWindows) {
2655 // If the caller requested to sync input windows, but there are no
2656 // changes to input windows, notify immediately.
2657 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002658 }
2659
Arthur Hung6cbb9752019-09-05 16:38:18 +08002660 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002661}
2662
2663void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002664 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002665
2666 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2667 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002668 // When calculating the screen bounds we ignore the transparent region since it may
2669 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002670 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002671 }
2672 });
chaviw291d88a2019-02-14 10:33:58 -08002673
2674 mInputFlinger->setInputWindows(inputHandles,
2675 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2676 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002677}
2678
Vishnu Nairec0ab382019-02-13 15:32:56 -08002679void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002680 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002681 mPendingInputWindowCommands.clear();
2682}
2683
Riley Andrews03414a12014-07-01 14:22:59 -07002684void SurfaceFlinger::updateCursorAsync()
2685{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002686 compositionengine::CompositionRefreshArgs refreshArgs;
2687 for (const auto& [_, display] : mDisplays) {
2688 if (display->getId()) {
2689 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002690 }
2691 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002692
2693 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002694}
2695
Ady Abraham2139f732019-11-13 18:56:40 -08002696void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002697 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2698 // If this is called from the main thread mStateLock must be locked before
2699 // Currently the only way to call this function from the main thread is from
2700 // Sheduler::chooseRefreshRateForContent
2701
2702 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002703 changeRefreshRateLocked(refreshRate, event);
2704}
2705
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002706void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2707 if (mScheduler) {
2708 // In practice it's not allowed to hotplug in/out the primary display once it's been
2709 // connected during startup, but some tests do it, so just warn and return.
2710 ALOGW("Can't re-init scheduler");
2711 return;
2712 }
2713
Ady Abraham2139f732019-11-13 18:56:40 -08002714 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002715 mRefreshRateConfigs =
Ana Krulec8c6f3f62020-01-23 15:48:01 -08002716 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002717 primaryDisplayId),
2718 currentConfig);
2719 mRefreshRateStats =
2720 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2721 currentConfig, HWC_POWER_MODE_OFF);
2722 mRefreshRateStats->setConfigMode(currentConfig);
2723
Ady Abraham9e16a482019-12-03 17:19:41 -08002724 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2725
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002726 // start the EventThread
2727 mScheduler =
2728 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002729 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002730 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002731 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002732 impl::EventThread::InterceptVSyncsCallback());
2733 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002734 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002735 [this](nsecs_t timestamp) {
2736 mInterceptor->saveVSyncEvent(timestamp);
2737 });
2738
2739 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2740 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002741 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002742
2743 mRegionSamplingThread =
2744 new RegionSamplingThread(*this, *mScheduler,
2745 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002746 // Dispatch a config change request for the primary display on scheduler
2747 // initialization, so that the EventThreads always contain a reference to a
2748 // prior configuration.
2749 //
2750 // This is a bit hacky, but this avoids a back-pointer into the main SF
2751 // classes from EventThread, and there should be no run-time binder cost
2752 // anyway since there are no connected apps at this point.
2753 const nsecs_t vsyncPeriod =
2754 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2755 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2756 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002757}
2758
Mathias Agopian4fec8732012-06-29 14:12:52 -07002759void SurfaceFlinger::commitTransaction()
2760{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002761 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002762
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002763 mTransactionPending = false;
2764 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002765 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002766}
2767
Lloyd Pique58e24a32019-08-01 15:50:14 -07002768void SurfaceFlinger::commitTransactionLocked() {
2769 if (!mLayersPendingRemoval.isEmpty()) {
2770 // Notify removed layers now that they can't be drawn from
2771 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002772 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002773
2774 // Ensure any buffers set to display on any children are released.
2775 if (l->isRemovedFromCurrentState()) {
2776 l->latchAndReleaseBuffer();
2777 }
2778
2779 // If the layer has been removed and has no parent, then it will not be reachable
2780 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2781 // ensure we can copy its current to drawing state.
2782 if (!l->getParent()) {
2783 mOffscreenLayers.emplace(l.get());
2784 }
2785 }
2786 mLayersPendingRemoval.clear();
2787 }
2788
2789 // If this transaction is part of a window animation then the next frame
2790 // we composite should be considered an animation as well.
2791 mAnimCompositionPending = mAnimTransactionPending;
2792
2793 mDrawingState = mCurrentState;
2794 // clear the "changed" flags in current state
2795 mCurrentState.colorMatrixChanged = false;
2796
Edgar Arriaga844fa672020-01-16 14:21:42 -08002797 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002798 layer->commitChildList();
2799
2800 // If the layer can be reached when traversing mDrawingState, then the layer is no
2801 // longer offscreen. Remove the layer from the offscreenLayer set.
2802 if (mOffscreenLayers.count(layer)) {
2803 mOffscreenLayers.erase(layer);
2804 }
2805 });
2806
2807 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002808 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002809}
2810
Nataniel Borges2b796da2019-02-15 13:32:18 -08002811void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2812 if (mTracingEnabledChanged) {
2813 mTracingEnabled = mTracing.isEnabled();
2814 mTracingEnabledChanged = false;
2815 }
2816
2817 // Synchronize with Tracing thread
2818 std::unique_lock<std::mutex> lock;
2819 if (mTracingEnabled) {
2820 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2821 }
2822
2823 lockedOperation();
2824
2825 // Synchronize with Tracing thread
2826 if (mTracingEnabled) {
2827 lock.unlock();
2828 }
2829}
2830
chaviw74d90ad2019-04-26 14:45:26 -07002831void SurfaceFlinger::commitOffscreenLayers() {
2832 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002833 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002834 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2835 if (!trFlags) return;
2836
2837 layer->doTransaction(0);
2838 layer->commitChildList();
2839 });
2840 }
2841}
2842
Chia-I Wuab0c3192017-08-01 11:29:00 -07002843void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002844 for (const auto& [token, displayDevice] : mDisplays) {
2845 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002846 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002847 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002848 }
2849 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002850}
2851
Dan Stoza6b9454d2014-11-07 16:00:59 -08002852bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002853{
Ady Abraham09bd3922019-04-08 10:44:56 -07002854 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002855 ALOGV("handlePageFlip");
2856
Brian Andersond6927fb2016-07-23 23:37:30 -07002857 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002858
Mathias Agopian4fec8732012-06-29 14:12:52 -07002859 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002860 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002861 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002862
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002863 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2864
Eric Penner51c59cd2014-07-28 19:51:58 -07002865 // Store the set of layers that need updates. This set must not change as
2866 // buffers are being latched, as this could result in a deadlock.
2867 // Example: Two producers share the same command stream and:
2868 // 1.) Layer 0 is latched
2869 // 2.) Layer 0 gets a new frame
2870 // 2.) Layer 1 gets a new frame
2871 // 3.) Layer 1 is latched.
2872 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2873 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002874 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002875 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002876 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002877 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002878 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002879 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002880 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002881 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002882 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002883 } else {
2884 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002885 }
Robert Carr2047fae2016-11-28 14:09:09 -08002886 });
2887
chaviw49a108c2019-08-12 11:23:06 -07002888 // The client can continue submitting buffers for offscreen layers, but they will not
2889 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2890 // layers to ensure dequeueBuffer doesn't block indefinitely.
2891 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002892 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002893 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2894 }
2895
Lloyd Piquef2c79392018-12-20 16:23:33 -08002896 if (!mLayersWithQueuedFrames.empty()) {
2897 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2898 // writes to Layer current state. See also b/119481871
2899 Mutex::Autolock lock(mStateLock);
2900
2901 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002902 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002903 mLayersPendingRefresh.push_back(layer);
2904 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002905 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002906 if (layer->isBufferLatched()) {
2907 newDataLatched = true;
2908 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002909 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002910 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002911
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002912 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002913
2914 // If we will need to wake up at some time in the future to deal with a
2915 // queued frame that shouldn't be displayed during this vsync period, wake
2916 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002917 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002918 signalLayerUpdate();
2919 }
2920
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002921 // enter boot animation on first buffer latch
2922 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2923 ALOGI("Enter boot animation");
2924 mBootStage = BootStage::BOOTANIMATION;
2925 }
2926
Edgar Arriaga844fa672020-01-16 14:21:42 -08002927 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07002928
Dan Stoza6b9454d2014-11-07 16:00:59 -08002929 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002930 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002931}
2932
Mathias Agopianad456f92011-01-13 17:53:01 -08002933void SurfaceFlinger::invalidateHwcGeometry()
2934{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002935 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002936}
2937
Robert Carrc0df3122019-04-11 13:18:21 -07002938status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2939 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2940 const sp<IBinder>& parentHandle,
2941 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002942 // add this layer to the current state list
2943 {
2944 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002945 sp<Layer> parent;
2946 if (parentHandle != nullptr) {
2947 parent = fromHandle(parentHandle);
2948 if (parent == nullptr) {
2949 return NAME_NOT_FOUND;
2950 }
2951 } else {
2952 parent = parentLayer;
2953 }
2954
Robert Carr1f0a16a2016-10-24 16:27:39 -07002955 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002956 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002957 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002958 return NO_MEMORY;
2959 }
Robert Carrc0df3122019-04-11 13:18:21 -07002960
2961 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2962
Robert Carrb89ea9d2018-12-10 13:01:14 -08002963 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002964 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002965 } else if (parent == nullptr) {
2966 lbc->onRemovedFromCurrentState();
2967 } else if (parent->isRemovedFromCurrentState()) {
2968 parent->addChild(lbc);
2969 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002970 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002971 parent->addChild(lbc);
2972 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002973
Yiwei Zhang243b3782018-05-15 17:40:04 -07002974 if (gbc != nullptr) {
2975 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2976 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2977 mMaxGraphicBufferProducerListSize,
2978 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2979 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002980 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002981 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002982 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002983 }
2984
Mathias Agopian96f08192010-06-02 23:28:45 -07002985 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002986 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002987
Dan Stoza7d89d062015-04-30 13:29:25 -07002988 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002989}
2990
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002991uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002992 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002993}
2994
Mathias Agopian3f844832013-08-07 21:24:32 -07002995uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002996 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002997}
2998
Mathias Agopian3f844832013-08-07 21:24:32 -07002999uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003000 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07003001}
3002
3003uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003004 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07003005 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07003006 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003007 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08003008 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003009 }
3010 return old;
3011}
3012
Marissa Wall713b63f2018-10-17 15:42:43 -07003013bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07003014 // to prevent onHandleDestroyed from being called while the lock is held,
3015 // we must keep a copy of the transactions (specifically the composer
3016 // states) around outside the scope of the lock
3017 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003018 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07003019 {
3020 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003021
Valerie Haufce31b82019-04-30 16:41:14 -07003022 auto it = mTransactionQueues.begin();
3023 while (it != mTransactionQueues.end()) {
3024 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003025
Valerie Haufce31b82019-04-30 16:41:14 -07003026 while (!transactionQueue.empty()) {
3027 const auto& transaction = transactionQueue.front();
3028 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003029 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003030 transaction.states)) {
3031 setTransactionFlags(eTransactionFlushNeeded);
3032 break;
3033 }
3034 transactions.push_back(transaction);
3035 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3036 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003037 transaction.buffer, transaction.postTime,
3038 transaction.privileged, transaction.hasListenerCallbacks,
3039 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003040 transactionQueue.pop();
3041 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003042 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003043
Valerie Haufce31b82019-04-30 16:41:14 -07003044 if (transactionQueue.empty()) {
3045 it = mTransactionQueues.erase(it);
3046 mTransactionCV.broadcast();
3047 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003048 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003049 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003050 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003051 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003052 return flushedATransaction;
3053}
3054
3055bool SurfaceFlinger::transactionFlushNeeded() {
3056 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003057}
3058
chaviwca27f252018-02-06 16:46:39 -08003059
Marissa Wall17b4e452018-12-26 16:32:34 -08003060bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003061 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003062 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003063 if (!useCachedExpectedPresentTime)
3064 populateExpectedPresentTime();
3065
3066 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003067 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3068 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3069 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3070 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3071 return false;
3072 }
3073
Marissa Wall713b63f2018-10-17 15:42:43 -07003074 for (const ComposerState& state : states) {
3075 const layer_state_t& s = state.state;
3076 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3077 continue;
3078 }
3079 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003080 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003081 }
3082 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003083 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003084}
3085
Valerie Hau9dab9732019-08-20 09:29:25 -07003086void SurfaceFlinger::setTransactionState(
3087 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3088 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3089 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3090 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003091 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003092
Valerie Haubc6ddb12019-03-08 11:10:15 -08003093 const int64_t postTime = systemTime();
3094
Robert Carr14167e02019-02-13 13:50:55 -08003095 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3096
Mathias Agopian698c0872011-06-28 19:09:31 -07003097 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003098
Marissa Wall713b63f2018-10-17 15:42:43 -07003099 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003100 auto itr = mTransactionQueues.find(applyToken);
3101 // if this is an animation frame, wait until prior animation frame has
3102 // been applied by SF
3103 if (flags & eAnimation) {
3104 while (itr != mTransactionQueues.end()) {
3105 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3106 if (CC_UNLIKELY(err != NO_ERROR)) {
3107 ALOGW_IF(err == TIMED_OUT,
3108 "setTransactionState timed out "
3109 "waiting for animation frame to apply");
3110 break;
3111 }
3112 itr = mTransactionQueues.find(applyToken);
3113 }
3114 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003115
3116 // Expected present time is computed and cached on invalidate, so it may be stale.
3117 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3118 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003119 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003120 uncacheBuffer, postTime, privileged,
3121 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003122 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003123 return;
3124 }
3125
Valerie Haubc6ddb12019-03-08 11:10:15 -08003126 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003127 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3128 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003129}
3130
Valerie Hau9dab9732019-08-20 09:29:25 -07003131void SurfaceFlinger::applyTransactionState(
3132 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3133 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3134 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3135 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3136 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003137 uint32_t transactionFlags = 0;
3138
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003139 if (flags & eAnimation) {
3140 // For window updates that are part of an animation we must wait for
3141 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003142 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003143 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003144 if (CC_UNLIKELY(err != NO_ERROR)) {
3145 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003146 // caller after a few seconds.
3147 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3148 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003149 mAnimTransactionPending = false;
3150 break;
3151 }
3152 }
3153 }
3154
chaviwca27f252018-02-06 16:46:39 -08003155 for (const DisplayState& display : displays) {
3156 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003157 }
3158
Valerie Hau9dab9732019-08-20 09:29:25 -07003159 // start and end registration for listeners w/ no surface so they can get their callback. Note
3160 // that listeners with SurfaceControls will start registration during setClientStateLocked
3161 // below.
3162 for (const auto& listener : listenerCallbacks) {
3163 mTransactionCompletedThread.startRegistration(listener);
3164 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003165 }
3166
Valerie Hau9dab9732019-08-20 09:29:25 -07003167 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003168 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003169 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003170 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3171 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003172 }
3173
Valerie Hau9dab9732019-08-20 09:29:25 -07003174 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003175 mTransactionCompletedThread.endRegistration(listenerCallback);
3176 }
3177
Marissa Walle2ffb422018-10-12 11:33:52 -07003178 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003179 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003180 mTransactionCompletedThread.sendCallbacks();
3181 }
3182 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003183
chaviw273171b2018-12-26 11:46:30 -08003184 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3185
Marissa Wall947d34e2019-03-29 14:03:53 -07003186 if (uncacheBuffer.isValid()) {
3187 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003188 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003189 }
3190
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003191 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3192 // anyway. This can be used as a flush mechanism for previous async transactions.
3193 // Empty animation transaction can be used to simulate back-pressure, so also force a
3194 // transaction for empty animation transactions.
3195 if (transactionFlags == 0 &&
3196 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003197 transactionFlags = eTransactionNeeded;
3198 }
3199
Marissa Wall06255332019-03-27 13:48:27 -07003200 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3201 // so we don't have to wake up again next frame to preform an uneeded traversal.
3202 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3203 transactionFlags = transactionFlags & (~eTraversalNeeded);
3204 mTraversalNeededMainThread = true;
3205 }
3206
Mathias Agopian386aa982011-11-07 21:58:03 -08003207 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003208 if (mInterceptor->isEnabled()) {
3209 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003210 }
Irvel468051e2016-06-13 16:44:44 -07003211
Mathias Agopian386aa982011-11-07 21:58:03 -08003212 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003213 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3214 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003215 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003216
3217 // if this is a synchronous transaction, wait for it to take effect
3218 // before returning.
3219 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003220 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003221 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003222 if (flags & eAnimation) {
3223 mAnimTransactionPending = true;
3224 }
chaviw4fe36852019-04-15 16:25:49 -07003225 if (mPendingInputWindowCommands.syncInputWindows) {
3226 mPendingSyncInputWindows = true;
3227 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003228
3229 // applyTransactionState can be called by either the main SF thread or by
3230 // another process through setTransactionState. While a given process may wish
3231 // to wait on synchronous transactions, the main SF thread should never
3232 // be blocked. Therefore, we only wait if isMainThread is false.
3233 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003234 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3235 if (CC_UNLIKELY(err != NO_ERROR)) {
3236 // just in case something goes wrong in SF, return to the
3237 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003238 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3239 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003240 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003241 break;
3242 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003243 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003244 }
3245}
3246
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003247uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3248 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3249 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003250
Mathias Agopiane57f2922012-08-09 16:29:12 -07003251 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003252 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3253
3254 const uint32_t what = s.what;
3255 if (what & DisplayState::eSurfaceChanged) {
3256 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3257 state.surface = s.surface;
3258 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003259 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003260 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003261 if (what & DisplayState::eLayerStackChanged) {
3262 if (state.layerStack != s.layerStack) {
3263 state.layerStack = s.layerStack;
3264 flags |= eDisplayTransactionNeeded;
3265 }
3266 }
3267 if (what & DisplayState::eDisplayProjectionChanged) {
3268 if (state.orientation != s.orientation) {
3269 state.orientation = s.orientation;
3270 flags |= eDisplayTransactionNeeded;
3271 }
3272 if (state.frame != s.frame) {
3273 state.frame = s.frame;
3274 flags |= eDisplayTransactionNeeded;
3275 }
3276 if (state.viewport != s.viewport) {
3277 state.viewport = s.viewport;
3278 flags |= eDisplayTransactionNeeded;
3279 }
3280 }
3281 if (what & DisplayState::eDisplaySizeChanged) {
3282 if (state.width != s.width) {
3283 state.width = s.width;
3284 flags |= eDisplayTransactionNeeded;
3285 }
3286 if (state.height != s.height) {
3287 state.height = s.height;
3288 flags |= eDisplayTransactionNeeded;
3289 }
3290 }
3291
Mathias Agopiane57f2922012-08-09 16:29:12 -07003292 return flags;
3293}
3294
Robert Carr14167e02019-02-13 13:50:55 -08003295bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003296 IPCThreadState* ipc = IPCThreadState::self();
3297 const int pid = ipc->getCallingPid();
3298 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003299 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003300 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003301 return false;
3302 }
3303 return true;
3304}
3305
Marissa Wall3dad52d2019-03-22 14:03:19 -07003306uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003307 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3308 bool privileged,
3309 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003310 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003311
Valerie Hau9dab9732019-08-20 09:29:25 -07003312 for (auto& listener : s.listeners) {
3313 // note that startRegistration will not re-register if the listener has
3314 // already be registered for a prior surface control
3315 mTransactionCompletedThread.startRegistration(listener);
3316 listenerCallbacks.insert(listener);
3317 }
3318
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003319 sp<Layer> layer = nullptr;
3320 if (s.surface) {
3321 layer = fromHandle(s.surface);
3322 } else {
3323 // The client may provide us a null handle. Treat it as if the layer was removed.
3324 ALOGW("Attempt to set client state with a null layer handle");
3325 }
chaviw8b3871a2017-11-01 17:41:01 -07003326 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003327 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003328 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003329 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003330 }
chaviw8b3871a2017-11-01 17:41:01 -07003331 return 0;
3332 }
3333
chaviw8b3871a2017-11-01 17:41:01 -07003334 uint32_t flags = 0;
3335
Garfield Tan8a3083e2018-12-03 13:21:07 -08003336 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003337
3338 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3339 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003340 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003341 layer->pushPendingState();
3342 }
3343
chaviw8b3871a2017-11-01 17:41:01 -07003344 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003345 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003346 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003347 }
chaviw8b3871a2017-11-01 17:41:01 -07003348 }
3349 if (what & layer_state_t::eLayerChanged) {
3350 // NOTE: index needs to be calculated before we update the state
3351 const auto& p = layer->getParent();
3352 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003353 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003354 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003355 mCurrentState.layersSortedByZ.removeAt(idx);
3356 mCurrentState.layersSortedByZ.add(layer);
3357 // we need traversal (state changed)
3358 // AND transaction (list changed)
3359 flags |= eTransactionNeeded|eTraversalNeeded;
3360 }
chaviw8b3871a2017-11-01 17:41:01 -07003361 } else {
3362 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003363 flags |= eTransactionNeeded|eTraversalNeeded;
3364 }
3365 }
chaviw8b3871a2017-11-01 17:41:01 -07003366 }
3367 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003368 // NOTE: index needs to be calculated before we update the state
3369 const auto& p = layer->getParent();
3370 if (p == nullptr) {
3371 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3372 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3373 mCurrentState.layersSortedByZ.removeAt(idx);
3374 mCurrentState.layersSortedByZ.add(layer);
3375 // we need traversal (state changed)
3376 // AND transaction (list changed)
3377 flags |= eTransactionNeeded|eTraversalNeeded;
3378 }
3379 } else {
3380 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3381 flags |= eTransactionNeeded|eTraversalNeeded;
3382 }
chaviw8b3871a2017-11-01 17:41:01 -07003383 }
3384 }
3385 if (what & layer_state_t::eSizeChanged) {
3386 if (layer->setSize(s.w, s.h)) {
3387 flags |= eTraversalNeeded;
3388 }
3389 }
3390 if (what & layer_state_t::eAlphaChanged) {
3391 if (layer->setAlpha(s.alpha))
3392 flags |= eTraversalNeeded;
3393 }
3394 if (what & layer_state_t::eColorChanged) {
3395 if (layer->setColor(s.color))
3396 flags |= eTraversalNeeded;
3397 }
Peiyong Lind3788632018-09-18 16:01:31 -07003398 if (what & layer_state_t::eColorTransformChanged) {
3399 if (layer->setColorTransform(s.colorTransform)) {
3400 flags |= eTraversalNeeded;
3401 }
3402 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003403 if (what & layer_state_t::eBackgroundColorChanged) {
3404 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3405 flags |= eTraversalNeeded;
3406 }
3407 }
chaviw8b3871a2017-11-01 17:41:01 -07003408 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003409 // TODO: b/109894387
3410 //
3411 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3412 // rotation. To see the problem observe that if we have a square parent, and a child
3413 // of the same size, then we rotate the child 45 degrees around it's center, the child
3414 // must now be cropped to a non rectangular 8 sided region.
3415 //
3416 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3417 // private API, and the WindowManager only uses rotation in one case, which is on a top
3418 // level layer in which cropping is not an issue.
3419 //
3420 // However given that abuse of rotation matrices could lead to surfaces extending outside
3421 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3422 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3423 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003424 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003425 flags |= eTraversalNeeded;
3426 }
3427 if (what & layer_state_t::eTransparentRegionChanged) {
3428 if (layer->setTransparentRegionHint(s.transparentRegion))
3429 flags |= eTraversalNeeded;
3430 }
3431 if (what & layer_state_t::eFlagsChanged) {
3432 if (layer->setFlags(s.flags, s.mask))
3433 flags |= eTraversalNeeded;
3434 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003435 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003436 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003437 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003438 if (what & layer_state_t::eCornerRadiusChanged) {
3439 if (layer->setCornerRadius(s.cornerRadius))
3440 flags |= eTraversalNeeded;
3441 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003442 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3443 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3444 }
chaviw8b3871a2017-11-01 17:41:01 -07003445 if (what & layer_state_t::eLayerStackChanged) {
3446 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3447 // We only allow setting layer stacks for top level layers,
3448 // everything else inherits layer stack from its parent.
3449 if (layer->hasParent()) {
3450 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003451 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003452 } else if (idx < 0) {
3453 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003454 "that also does not appear in the top level layer list. Something"
3455 " has gone wrong.",
3456 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003457 } else if (layer->setLayerStack(s.layerStack)) {
3458 mCurrentState.layersSortedByZ.removeAt(idx);
3459 mCurrentState.layersSortedByZ.add(layer);
3460 // we need traversal (state changed)
3461 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003462 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003463 }
3464 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003465 if (what & layer_state_t::eDeferTransaction_legacy) {
3466 if (s.barrierHandle_legacy != nullptr) {
3467 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3468 } else if (s.barrierGbp_legacy != nullptr) {
3469 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003470 if (authenticateSurfaceTextureLocked(gbp)) {
3471 const auto& otherLayer =
3472 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003473 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003474 } else {
3475 ALOGE("Attempt to defer transaction to to an"
3476 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003477 }
3478 }
chaviw8b3871a2017-11-01 17:41:01 -07003479 // We don't trigger a traversal here because if no other state is
3480 // changed, we don't want this to cause any more work
3481 }
chaviw8b3871a2017-11-01 17:41:01 -07003482 if (what & layer_state_t::eReparentChildren) {
3483 if (layer->reparentChildren(s.reparentHandle)) {
3484 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003485 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003486 }
chaviw8b3871a2017-11-01 17:41:01 -07003487 if (what & layer_state_t::eDetachChildren) {
3488 layer->detachChildren();
3489 }
3490 if (what & layer_state_t::eOverrideScalingModeChanged) {
3491 layer->setOverrideScalingMode(s.overrideScalingMode);
3492 // We don't trigger a traversal here because if no other state is
3493 // changed, we don't want this to cause any more work
3494 }
Marissa Wall61c58622018-07-18 10:12:20 -07003495 if (what & layer_state_t::eTransformChanged) {
3496 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3497 }
3498 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3499 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3500 flags |= eTraversalNeeded;
3501 }
3502 if (what & layer_state_t::eCropChanged) {
3503 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3504 }
Marissa Wall861616d2018-10-22 12:52:23 -07003505 if (what & layer_state_t::eFrameChanged) {
3506 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3507 }
Marissa Wall61c58622018-07-18 10:12:20 -07003508 if (what & layer_state_t::eAcquireFenceChanged) {
3509 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3510 }
3511 if (what & layer_state_t::eDataspaceChanged) {
3512 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3513 }
3514 if (what & layer_state_t::eHdrMetadataChanged) {
3515 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3516 }
3517 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3518 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3519 }
3520 if (what & layer_state_t::eApiChanged) {
3521 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3522 }
3523 if (what & layer_state_t::eSidebandStreamChanged) {
3524 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3525 }
Robert Carr720e5062018-07-30 17:45:14 -07003526 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003527 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003528 layer->setInputInfo(s.inputInfo);
3529 flags |= eTraversalNeeded;
3530 } else {
3531 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3532 }
Robert Carr720e5062018-07-30 17:45:14 -07003533 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003534 if (what & layer_state_t::eMetadataChanged) {
3535 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3536 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003537 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3538 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3539 flags |= eTraversalNeeded;
3540 }
3541 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003542 if (what & layer_state_t::eShadowRadiusChanged) {
3543 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3544 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003545 if (what & layer_state_t::eFrameRateSelectionPriority) {
3546 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3547 flags |= eTraversalNeeded;
3548 }
3549 }
Steven Thomas3172e202020-01-06 19:25:30 -08003550 if (what & layer_state_t::eFrameRateChanged) {
Ady Abraham71c437d2020-01-31 15:56:57 -08003551 if (layer->setFrameRate(
3552 Layer::FrameRate(s.frameRate, Layer::FrameRateCompatibility::Default)))
3553 flags |= eTraversalNeeded;
Steven Thomas3172e202020-01-06 19:25:30 -08003554 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003555 // This has to happen after we reparent children because when we reparent to null we remove
3556 // child layers from current state and remove its relative z. If the children are reparented in
3557 // the same transaction, then we have to make sure we reparent the children first so we do not
3558 // lose its relative z order.
3559 if (what & layer_state_t::eReparent) {
3560 bool hadParent = layer->hasParent();
3561 if (layer->reparent(s.parentHandleForChild)) {
3562 if (!hadParent) {
3563 mCurrentState.layersSortedByZ.remove(layer);
3564 }
3565 flags |= eTransactionNeeded | eTraversalNeeded;
3566 }
3567 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003568 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003569 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3570 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003571 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3572 }
3573 }
Marissa Wall78b72202019-03-15 14:58:34 -07003574 bool bufferChanged = what & layer_state_t::eBufferChanged;
3575 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3576 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003577 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003578 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003579 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3580 if (success) {
3581 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3582 success = ClientCache::getInstance()
3583 .registerErasedRecipient(s.cachedBuffer,
3584 wp<ClientCache::ErasedRecipient>(this));
3585 if (!success) {
3586 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3587 }
3588 }
Marissa Wall78b72202019-03-15 14:58:34 -07003589 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003590 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003591 } else if (bufferChanged) {
3592 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003593 }
Marissa Wall78b72202019-03-15 14:58:34 -07003594 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003595 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003596 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003597 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003598 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003599 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3600 // Do not put anything that updates layer state or modifies flags after
3601 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003602 return flags;
3603}
3604
chaviw273171b2018-12-26 11:46:30 -08003605uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3606 uint32_t flags = 0;
3607 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3608 flags |= eTraversalNeeded;
3609 }
3610
chaviwa911b102019-02-14 10:18:33 -08003611 if (inputWindowCommands.syncInputWindows) {
3612 flags |= eTraversalNeeded;
3613 }
3614
Vishnu Nairec0ab382019-02-13 15:32:56 -08003615 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003616 return flags;
3617}
3618
chaviwfe94a222019-08-21 13:52:59 -07003619status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3620 sp<IBinder>* outHandle) {
3621 if (!mirrorFromHandle) {
3622 return NAME_NOT_FOUND;
3623 }
3624
3625 sp<Layer> mirrorLayer;
3626 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003627 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003628
3629 {
3630 Mutex::Autolock _l(mStateLock);
3631 mirrorFrom = fromHandle(mirrorFromHandle);
3632 if (!mirrorFrom) {
3633 return NAME_NOT_FOUND;
3634 }
3635
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003636 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3637 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003638 if (result != NO_ERROR) {
3639 return result;
3640 }
3641
3642 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3643 }
3644
3645 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3646}
3647
Marissa Wall2d814fb2019-04-09 18:52:57 +00003648status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3649 uint32_t h, PixelFormat format, uint32_t flags,
3650 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003651 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003652 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3653 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003654 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003655 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003656 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003657 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003658 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003659
Robert Carrc0df3122019-04-11 13:18:21 -07003660 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3661 "Expected only one of parentLayer or parentHandle to be non-null. "
3662 "Programmer error?");
3663
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003664 status_t result = NO_ERROR;
3665
3666 sp<Layer> layer;
3667
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003668 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003669
Evan Roskya1f1e152019-01-24 16:17:46 -08003670 bool primaryDisplayOnly = false;
3671
3672 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3673 // TODO b/64227542
3674 if (metadata.has(METADATA_WINDOW_TYPE)) {
3675 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3676 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003677 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003678 primaryDisplayOnly = true;
3679 }
3680 }
3681
Mathias Agopian3165cc22012-08-08 19:42:09 -07003682 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003683 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003684 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3685 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003686
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003687 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003688 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003689 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003690 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003691 break;
chaviw13fdc492017-06-27 12:40:18 -07003692 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003693 // check if buffer size is set for color layer.
3694 if (w > 0 || h > 0) {
3695 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3696 int(w), int(h));
3697 return BAD_VALUE;
3698 }
3699
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003700 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3701 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003702 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003703 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003704 // check if buffer size is set for container layer.
3705 if (w > 0 || h > 0) {
3706 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3707 int(w), int(h));
3708 return BAD_VALUE;
3709 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003710 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3711 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003712 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003713 default:
3714 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003715 break;
3716 }
3717
Dan Stoza7d89d062015-04-30 13:29:25 -07003718 if (result != NO_ERROR) {
3719 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003720 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003721
Evan Roskya1f1e152019-01-24 16:17:46 -08003722 if (primaryDisplayOnly) {
3723 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003724 }
3725
Robert Carrb89ea9d2018-12-10 13:01:14 -08003726 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003727 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3728 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003729 if (result != NO_ERROR) {
3730 return result;
3731 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003732 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003733
3734 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003735 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003736}
3737
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003738std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3739 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003740
3741 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003742 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003743
Dan Stoza436ccf32018-06-21 12:10:12 -07003744 // Grab the state lock since we're accessing mCurrentState
3745 Mutex::Autolock lock(mStateLock);
3746
Cody Northropbc755282017-03-31 12:00:08 -06003747 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003748 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003749 while (matchFound) {
3750 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003751 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003752 if (layer->getName() == uniqueName) {
3753 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003754 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003755 }
3756 });
3757 }
3758
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003759 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003760 return uniqueName;
3761}
3762
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003763status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003764 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003765 LayerMetadata metadata, PixelFormat& format,
3766 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003767 sp<IGraphicBufferProducer>* gbp,
3768 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003769 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003770 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003771 case PIXEL_FORMAT_TRANSPARENT:
3772 case PIXEL_FORMAT_TRANSLUCENT:
3773 format = PIXEL_FORMAT_RGBA_8888;
3774 break;
3775 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003776 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003777 break;
3778 }
3779
chaviwb4c6e582019-08-16 14:35:07 -07003780 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003781 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003782 args.textureName = getNewTexture();
3783 {
3784 // Grab the SF state lock during this since it's the only safe way to access
3785 // RenderEngine when creating a BufferLayerConsumer
3786 // TODO: Check if this lock is still needed here
3787 Mutex::Autolock lock(mStateLock);
3788 layer = getFactory().createBufferQueueLayer(args);
3789 }
3790
Marissa Wallfd668622018-05-10 10:21:13 -07003791 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003792 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003793 *handle = layer->getHandle();
3794 *gbp = layer->getProducer();
3795 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003796 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003797
Marissa Wallfd668622018-05-10 10:21:13 -07003798 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003799 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003800}
3801
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003802status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003803 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003804 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003805 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003806 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003807 args.displayDevice = getDefaultDisplayDevice();
3808 args.textureName = getNewTexture();
3809 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003810 if (outTransformHint) {
3811 *outTransformHint = layer->getTransformHint();
3812 }
Marissa Wall61c58622018-07-18 10:12:20 -07003813 *handle = layer->getHandle();
3814 *outLayer = layer;
3815
3816 return NO_ERROR;
3817}
3818
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003819status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003820 uint32_t h, uint32_t flags, LayerMetadata metadata,
3821 sp<IBinder>* handle, sp<Layer>* outLayer) {
3822 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003823 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003824 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003825 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003826}
3827
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003828status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003829 uint32_t w, uint32_t h, uint32_t flags,
3830 LayerMetadata metadata, sp<IBinder>* handle,
3831 sp<Layer>* outLayer) {
3832 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003833 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003834 *handle = (*outLayer)->getHandle();
3835 return NO_ERROR;
3836}
3837
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003838void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003839 mLayersPendingRemoval.add(layer);
3840 mLayersRemoved = true;
3841 setTransactionFlags(eTransactionNeeded);
3842}
3843
Robert Carr695d5282018-12-18 15:27:58 -08003844void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003845{
Robert Carr2e102c92018-10-23 12:11:15 -07003846 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003847 // If a layer has a parent, we allow it to out-live it's handle
3848 // with the idea that the parent holds a reference and will eventually
3849 // be cleaned up. However no one cleans up the top-level so we do so
3850 // here.
3851 if (layer->getParent() == nullptr) {
3852 mCurrentState.layersSortedByZ.remove(layer);
3853 }
3854 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003855
3856 auto it = mLayersByLocalBinderToken.begin();
3857 while (it != mLayersByLocalBinderToken.end()) {
3858 if (it->second == layer) {
3859 it = mLayersByLocalBinderToken.erase(it);
3860 } else {
3861 it++;
3862 }
3863 }
3864
Robert Carr695d5282018-12-18 15:27:58 -08003865 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003866}
3867
Mathias Agopianb60314a2012-04-10 22:09:54 -07003868// ---------------------------------------------------------------------------
3869
Andy McFadden13a082e2012-08-24 10:16:42 -07003870void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003871 const auto display = getDefaultDisplayDeviceLocked();
3872 if (!display) return;
3873
3874 const sp<IBinder> token = display->getDisplayToken().promote();
3875 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003876
Jesse Hall01e29052013-02-19 16:13:35 -08003877 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003878 Vector<ComposerState> state;
3879 Vector<DisplayState> displays;
3880 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003881 d.what = DisplayState::eDisplayProjectionChanged |
3882 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003883 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003884 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003885 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003886 d.frame.makeInvalid();
3887 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003888 d.width = 0;
3889 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003890 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003891 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3892 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003893
Dominik Laskowskie9774092018-12-11 10:04:24 -08003894 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003895
Dominik Laskowski83b88212018-12-11 13:34:06 -08003896 const nsecs_t vsyncPeriod = getVsyncPeriod();
3897 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003898
Brian Andersond0010582017-03-07 13:20:31 -08003899 // Use phase of 0 since phase is not known.
3900 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003901 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003902 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003903}
3904
3905void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003906 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003907 postMessageAsync(
3908 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003909}
3910
Ady Abraham27c70212019-06-11 10:52:26 -07003911void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3912 if (mHWCVsyncState != enabled) {
3913 getHwComposer().setVsyncEnabled(displayId, enabled);
3914 mHWCVsyncState = enabled;
3915 }
3916}
3917
Dominik Laskowskie9774092018-12-11 10:04:24 -08003918void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003919 if (display->isVirtual()) {
3920 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003921 return;
3922 }
3923
Dominik Laskowski075d3172018-05-24 15:50:06 -07003924 const auto displayId = display->getId();
3925 LOG_ALWAYS_FATAL_IF(!displayId);
3926
Dominik Laskowski34157762018-10-31 13:07:19 -07003927 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003928
3929 int currentMode = display->getPowerMode();
3930 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003931 return;
3932 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003933
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003934 display->setPowerMode(mode);
3935
Lloyd Pique4dccc412018-01-22 17:21:36 -08003936 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003937 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003938 }
3939
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003940 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003941 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003942 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003943 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003944 mScheduler->onScreenAcquired(mAppConnectionHandle);
3945 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003946 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003947
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003948 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003949 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003950 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003951
3952 struct sched_param param = {0};
3953 param.sched_priority = 1;
3954 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3955 ALOGW("Couldn't set SCHED_FIFO on display on");
3956 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003957 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003958 // Turn off the display
3959 struct sched_param param = {0};
3960 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3961 ALOGW("Couldn't set SCHED_OTHER on display off");
3962 }
3963
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003964 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003965 mScheduler->disableHardwareVsync(true);
3966 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003967 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003968
Ady Abraham27c70212019-06-11 10:52:26 -07003969 // Make sure HWVsync is disabled before turning off the display
3970 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3971
Dominik Laskowski075d3172018-05-24 15:50:06 -07003972 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003973 mVisibleRegionsDirty = true;
3974 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003975 } else if (mode == HWC_POWER_MODE_DOZE ||
3976 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003977 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003978 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003979 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003980 mScheduler->onScreenAcquired(mAppConnectionHandle);
3981 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003982 }
3983 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3984 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003985 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003986 mScheduler->disableHardwareVsync(true);
3987 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003988 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003989 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003990 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003991 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003992 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003993 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003994
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003995 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003996 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003997 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003998 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003999 }
4000
Dominik Laskowski34157762018-10-31 13:07:19 -07004001 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004002}
4003
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004004void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004005 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004006 const auto display = getDisplayDevice(displayToken);
4007 if (!display) {
4008 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
4009 displayToken.get());
4010 } else if (display->isVirtual()) {
4011 ALOGW("Attempt to set power mode %d for virtual display", mode);
4012 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08004013 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07004014 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004015 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07004016}
4017
4018// ---------------------------------------------------------------------------
4019
Dominik Laskowskic2867142019-01-21 11:33:38 -08004020status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4021 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004022 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004023
Mathias Agopianbd115332013-04-18 16:41:04 -07004024 IPCThreadState* ipc = IPCThreadState::self();
4025 const int pid = ipc->getCallingPid();
4026 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004027
Mathias Agopianbd115332013-04-18 16:41:04 -07004028 if ((uid != AID_SHELL) &&
4029 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004030 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4031 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004032 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004033 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004034 // (this would indicate SF is stuck, but we want to be able to
4035 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004036 status_t err = mStateLock.timedLock(s2ns(1));
4037 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004038 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004039 StringAppendF(&result,
4040 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4041 "(no locks held)\n",
4042 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004043 }
4044
Dominik Laskowskic2867142019-01-21 11:33:38 -08004045 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004046 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004047 {"--dispsync"s,
4048 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004049 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004050 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4051 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4052 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4053 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4054 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4055 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004056 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004057 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4058 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004059
Dominik Laskowskic2867142019-01-21 11:33:38 -08004060 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004061
Dominik Laskowski46470112019-08-02 13:13:11 -07004062 const auto it = dumpers.find(flag);
4063 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004064 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004065 } else if (!asProto) {
4066 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004067 }
4068
Mathias Agopian9795c422009-08-26 16:36:26 -07004069 if (locked) {
4070 mStateLock.unlock();
4071 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004072
Dominik Laskowski46470112019-08-02 13:13:11 -07004073 if (it == dumpers.end()) {
4074 const LayersProto layersProto = dumpProtoFromMainThread();
4075 if (asProto) {
4076 result.append(layersProto.SerializeAsString());
4077 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004078 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004079 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4080 result.append(LayerProtoParser::layerTreeToString(layerTree));
4081 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004082 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004083 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004084 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004085 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004086 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004087 return NO_ERROR;
4088}
4089
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004090status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4091 if (asProto && mTracing.isEnabled()) {
4092 mTracing.writeToFileAsync();
4093 }
4094
4095 return doDump(fd, DumpArgs(), asProto);
4096}
4097
Dominik Laskowskic2867142019-01-21 11:33:38 -08004098void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004099 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004100 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004101}
4102
Dominik Laskowskic2867142019-01-21 11:33:38 -08004103void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004104 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004105
Dominik Laskowskic2867142019-01-21 11:33:38 -08004106 if (args.size() > 1) {
4107 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004108 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004109 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004110 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004111 }
Robert Carr2047fae2016-11-28 14:09:09 -08004112 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004113 } else {
4114 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004115 }
4116}
4117
Dominik Laskowskic2867142019-01-21 11:33:38 -08004118void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004119 const bool clearAll = args.size() < 2;
4120 const auto name = clearAll ? String8() : String8(args[1]);
4121
Edgar Arriaga844fa672020-01-16 14:21:42 -08004122 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004123 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004124 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004125 }
Robert Carr2047fae2016-11-28 14:09:09 -08004126 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004127
Svetoslavd85084b2014-03-20 10:28:31 -07004128 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004129}
4130
Dominik Laskowskic2867142019-01-21 11:33:38 -08004131void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4132 mTimeStats->parseArgs(asProto, args, result);
4133}
4134
Jamie Gennis6547ff42013-07-16 20:12:42 -07004135// This should only be called from the main thread. Otherwise it would need
4136// the lock and should use mCurrentState rather than mDrawingState.
4137void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004138 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004139 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004140 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004141
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004142 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004143}
4144
Yiwei Zhang5434a782018-12-05 18:06:32 -08004145void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004146 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004147
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004148 if (isLayerTripleBufferingDisabled())
4149 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004150
Yiwei Zhang5434a782018-12-05 18:06:32 -08004151 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4152 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4153 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4154 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4155 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4156 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004157 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004158}
4159
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004160void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004161 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004162
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004163 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004164 result.append("\n");
4165
Ady Abraham9e16a482019-12-03 17:19:41 -08004166 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004167 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004168 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004169 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004170
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004171 HwcConfigIndexType defaultConfig;
4172 float minFps, maxFps;
4173 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004174 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004175 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004176 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004177 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004178 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4179 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004180
Ana Krulecc2870422019-01-29 19:00:58 -08004181 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004182}
4183
Yiwei Zhang5434a782018-12-05 18:06:32 -08004184void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4185 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004186 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4187 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004188 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004189 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004190 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004191 }
David Sodman4a36e932017-11-07 14:29:47 -08004192 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004193 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004194 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004195 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4196 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004197}
4198
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004199void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4200 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004201 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4202 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004203 for (const auto& segment : history) {
4204 if (!segment.usedThirdBuffer) {
4205 stats.twoBufferTime += segment.totalTime;
4206 }
4207 if (segment.occupancyAverage < 1.0f) {
4208 stats.doubleBufferedTime += segment.totalTime;
4209 } else if (segment.occupancyAverage < 2.0f) {
4210 stats.tripleBufferedTime += segment.totalTime;
4211 }
4212 ++stats.numSegments;
4213 stats.totalTime += segment.totalTime;
4214 }
4215}
4216
Yiwei Zhang5434a782018-12-05 18:06:32 -08004217void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4218 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004219
4220 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4221 const size_t count = currentLayers.size();
4222 for (size_t i=0 ; i<count ; i++) {
4223 currentLayers[i]->dumpFrameEvents(result);
4224 }
4225}
4226
Yiwei Zhang5434a782018-12-05 18:06:32 -08004227void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004228 result.append("Buffering stats:\n");
4229 result.append(" [Layer name] <Active time> <Two buffer> "
4230 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004231 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004232 typedef std::tuple<std::string, float, float, float> BufferTuple;
4233 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004234 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004235 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004236 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004237 if (stats.numSegments == 0) {
4238 continue;
4239 }
4240 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4241 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4242 stats.totalTime;
4243 float doubleBufferRatio = static_cast<float>(
4244 stats.doubleBufferedTime) / stats.totalTime;
4245 float tripleBufferRatio = static_cast<float>(
4246 stats.tripleBufferedTime) / stats.totalTime;
4247 sorted.insert({activeTime, {name, twoBufferRatio,
4248 doubleBufferRatio, tripleBufferRatio}});
4249 }
4250 for (const auto& sortedPair : sorted) {
4251 float activeTime = sortedPair.first;
4252 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004253 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4254 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004255 }
4256 result.append("\n");
4257}
4258
Yiwei Zhang5434a782018-12-05 18:06:32 -08004259void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004260 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004261 const auto displayId = display->getId();
4262 if (!displayId) {
4263 continue;
4264 }
4265 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004266 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004267 continue;
4268 }
4269
Yiwei Zhang5434a782018-12-05 18:06:32 -08004270 StringAppendF(&result,
4271 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4272 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004273 uint8_t port;
4274 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004275 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004276 result.append("no identification data\n");
4277 continue;
4278 }
4279
4280 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004281 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004282 continue;
4283 }
4284
4285 const auto edid = parseEdid(data);
4286 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004287 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004288 continue;
4289 }
4290
Yiwei Zhang5434a782018-12-05 18:06:32 -08004291 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004292 result.append(edid->displayName.data(), edid->displayName.length());
4293 result.append("\"\n");
4294 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004295}
4296
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004297void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4298 std::string& result) const {
4299 hwc2_display_t hwcDisplayId;
4300 uint8_t port;
4301 DisplayIdentificationData data;
4302
4303 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4304 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4305 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4306 }
4307}
4308
Yiwei Zhang5434a782018-12-05 18:06:32 -08004309void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004310 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004311 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4312 StringAppendF(&result, "DisplayColorSetting: %s\n",
4313 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004314
4315 // TODO: print out if wide-color mode is active or not
4316
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004317 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004318 const auto displayId = display->getId();
4319 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004320 continue;
4321 }
4322
Yiwei Zhang5434a782018-12-05 18:06:32 -08004323 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004324 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004325 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004326 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004327 }
4328
Lloyd Pique32cbe282018-10-19 13:09:22 -07004329 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004330 StringAppendF(&result, " Current color mode: %s (%d)\n",
4331 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004332 }
4333 result.append("\n");
4334}
4335
Vishnu Nair8406fd72019-07-30 11:29:31 -07004336LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004337 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004338 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4339 layer->writeToProto(layersProto, traceFlags);
4340 }
chaviw1d044282017-09-27 12:19:28 -07004341 return layersProto;
4342}
4343
Vishnu Nair0f085c62019-08-30 08:49:12 -07004344void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4345 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4346 // it.
4347 LayerProto* rootProto = layersProto.add_layers();
4348 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4349 rootProto->set_id(offscreenRootLayerId);
4350 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004351 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004352
4353 for (Layer* offscreenLayer : mOffscreenLayers) {
4354 // Add layer as child of the fake root
4355 rootProto->add_children(offscreenLayer->sequence);
4356
4357 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004358 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004359 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004360 }
4361}
4362
Vishnu Nair8406fd72019-07-30 11:29:31 -07004363LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4364 LayersProto layersProto;
4365 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4366 return layersProto;
4367}
4368
Vishnu Nair0f085c62019-08-30 08:49:12 -07004369void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4370 result.append("Offscreen Layers:\n");
4371 postMessageSync(new LambdaMessage([&]() {
4372 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004373 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004374 layer->dumpCallingUidPid(result);
4375 });
4376 }
4377 }));
4378}
4379
Dominik Laskowskic2867142019-01-21 11:33:38 -08004380void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4381 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004382 Colorizer colorizer(colorize);
4383
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004384 // figure out if we're stuck somewhere
4385 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004386 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004387 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4388
4389 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004390 * Dump library configuration.
4391 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004392
4393 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004394 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004395 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004396 appendSfConfigString(result);
4397 appendUiConfigString(result);
4398 appendGuiConfigString(result);
4399 result.append("\n");
4400
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004401 result.append("\nDisplay identification data:\n");
4402 dumpDisplayIdentificationData(result);
4403
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004404 result.append("\nWide-Color information:\n");
4405 dumpWideColorInfo(result);
4406
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004407 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004408 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004409 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004410 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004411 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004412
Andy McFadden41d67d72014-04-25 16:58:34 -07004413 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004414 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004415 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004416 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004417 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004418
Dan Stozab90cf072015-03-05 11:05:59 -08004419 dumpStaticScreenStats(result);
4420 result.append("\n");
4421
Alec Mouri40189b02019-03-05 15:07:54 -08004422 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4423 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4424 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004425
Dan Stozae77c7662016-05-13 11:37:28 -07004426 dumpBufferingStats(result);
4427
Andy McFadden4803b742012-09-24 19:07:20 -07004428 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004429 * Dump the visible layer list
4430 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004431 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004432 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004433 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4434 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004435 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004436
Chia-I Wu2f884132018-09-13 15:17:58 -07004437 {
Lloyd Pique207def92019-02-28 16:09:52 -08004438 StringAppendF(&result, "Composition layers\n");
4439 mDrawingState.traverseInZOrder([&](Layer* layer) {
4440 auto compositionLayer = layer->getCompositionLayer();
4441 if (compositionLayer) compositionLayer->dump(result);
4442 });
4443 }
4444
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004445 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004446 * Dump Display state
4447 */
4448
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004449 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004450 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004451 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004452 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004453 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004454 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004455 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004456
4457 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004458 * Dump CompositionEngine state
4459 */
4460
4461 mCompositionEngine->dump(result);
4462
4463 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004464 * Dump SurfaceFlinger global state
4465 */
4466
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004467 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004468 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004469 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004470
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004471 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004472
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004473 DebugEGLImageTracker::getInstance()->dump(result);
4474
Dominik Laskowski075d3172018-05-24 15:50:06 -07004475 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004476 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4477 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004478 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4479 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004480 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004481 StringAppendF(&result,
4482 " transaction-flags : %08x\n"
4483 " gpu_to_cpu_unsupported : %d\n",
4484 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004485
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004486 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004487 displayId && getHwComposer().isConnected(*displayId)) {
4488 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004489 StringAppendF(&result,
4490 " refresh-rate : %f fps\n"
4491 " x-dpi : %f\n"
4492 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004493 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4494 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004495 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004496
Yiwei Zhang5434a782018-12-05 18:06:32 -08004497 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004498
Dan Stozae22aec72016-08-01 13:20:59 -07004499 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004500 * Tracing state
4501 */
4502 mTracing.dump(result);
4503 result.append("\n");
4504
4505 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004506 * HWC layer minidump
4507 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004508 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004509 const auto displayId = display->getId();
4510 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004511 continue;
4512 }
4513
Yiwei Zhang5434a782018-12-05 18:06:32 -08004514 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004515 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004516 const sp<DisplayDevice> displayDevice = display;
4517 mCurrentState.traverseInZOrder(
4518 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004519 result.append("\n");
4520 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004521
4522 /*
4523 * Dump HWComposer state
4524 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004525 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004526 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004527 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004528 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004529 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004530 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004531
4532 /*
4533 * Dump gralloc state
4534 */
4535 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4536 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004537
4538 /*
4539 * Dump VrFlinger state if in use.
4540 */
4541 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4542 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004543 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004544 result.append("\n");
4545 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004546
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004547 result.append(mTimeStats->miniDump());
4548 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004549}
4550
Chia-I Wu28f320b2018-05-03 11:02:56 -07004551void SurfaceFlinger::updateColorMatrixLocked() {
4552 mat4 colorMatrix;
4553 if (mGlobalSaturationFactor != 1.0f) {
4554 // Rec.709 luma coefficients
4555 float3 luminance{0.213f, 0.715f, 0.072f};
4556 luminance *= 1.0f - mGlobalSaturationFactor;
4557 mat4 saturationMatrix = mat4(
4558 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4559 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4560 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4561 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4562 );
4563 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4564 } else {
4565 colorMatrix = mClientColorMatrix * mDaltonizer();
4566 }
4567
4568 if (mCurrentState.colorMatrix != colorMatrix) {
4569 mCurrentState.colorMatrix = colorMatrix;
4570 mCurrentState.colorMatrixChanged = true;
4571 setTransactionFlags(eTransactionNeeded);
4572 }
4573}
4574
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004575status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004576#pragma clang diagnostic push
4577#pragma clang diagnostic error "-Wswitch-enum"
4578 switch (static_cast<ISurfaceComposerTag>(code)) {
4579 // These methods should at minimum make sure that the client requested
4580 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004581 case BOOT_FINISHED:
4582 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004583 case CREATE_DISPLAY:
4584 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004585 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004586 case GET_ANIMATION_FRAME_STATS:
4587 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004588 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004589 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004590 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004591 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4592 case SET_AUTO_LOW_LATENCY_MODE:
4593 case GET_GAME_CONTENT_TYPE_SUPPORT:
4594 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004595 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004596 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004597 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004598 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004599 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004600 case NOTIFY_POWER_HINT:
4601 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004602 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4603 IPCThreadState* ipc = IPCThreadState::self();
4604 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4605 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004606 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004607 }
Robert Carr1db73f62016-12-21 12:58:51 -08004608 return OK;
4609 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004610 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004611 IPCThreadState* ipc = IPCThreadState::self();
4612 const int pid = ipc->getCallingPid();
4613 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004614 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4615 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004616 return PERMISSION_DENIED;
4617 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004618 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004619 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004620 // Used by apps to hook Choreographer to SurfaceFlinger.
4621 case CREATE_DISPLAY_EVENT_CONNECTION:
4622 // The following calls are currently used by clients that do not
4623 // request necessary permissions. However, they do not expose any secret
4624 // information, so it is OK to pass them.
4625 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004626 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004627 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004628 case GET_PHYSICAL_DISPLAY_IDS:
4629 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004630 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004631 case GET_DISPLAY_NATIVE_PRIMARIES:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004632 case GET_DISPLAY_INFO:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004633 case GET_DISPLAY_CONFIGS:
Dominik Laskowski3cb3d4e2019-11-21 11:14:45 -08004634 case GET_DISPLAY_STATE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004635 case GET_DISPLAY_STATS:
4636 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4637 // Calling setTransactionState is safe, because you need to have been
4638 // granted a reference to Client* and Handle* to do anything with it.
4639 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004640 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004641 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004642 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004643 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004644 case IS_WIDE_COLOR_DISPLAY:
4645 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4646 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004647 return OK;
4648 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004649 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004650 case CAPTURE_SCREEN:
4651 case ADD_REGION_SAMPLING_LISTENER:
4652 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004653 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004654 IPCThreadState* ipc = IPCThreadState::self();
4655 const int pid = ipc->getCallingPid();
4656 const int uid = ipc->getCallingUid();
4657 if ((uid != AID_GRAPHICS) &&
4658 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4659 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4660 return PERMISSION_DENIED;
4661 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004662 return OK;
4663 }
chaviw93df2ea2019-04-30 16:45:12 -07004664 case CAPTURE_SCREEN_BY_ID: {
4665 IPCThreadState* ipc = IPCThreadState::self();
4666 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004667 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004668 return OK;
4669 }
4670 return PERMISSION_DENIED;
4671 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004672 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004673
4674 // These codes are used for the IBinder protocol to either interrogate the recipient
4675 // side of the transaction for its canonical interface descriptor or to dump its state.
4676 // We let them pass by default.
4677 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4678 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4679 code == IBinder::SYSPROPS_TRANSACTION) {
4680 return OK;
4681 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004682 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004683 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004684 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004685 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4686 return OK;
4687 }
4688 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4689 return PERMISSION_DENIED;
4690#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004691}
4692
Ana Krulec13be8ad2018-08-21 02:43:56 +00004693status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4694 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004695 status_t credentialCheck = CheckTransactCodeCredentials(code);
4696 if (credentialCheck != OK) {
4697 return credentialCheck;
4698 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004699
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004700 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4701 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004702 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004703 IPCThreadState* ipc = IPCThreadState::self();
4704 const int uid = ipc->getCallingUid();
4705 if (CC_UNLIKELY(uid != AID_SYSTEM
4706 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004707 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004708 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004709 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004710 return PERMISSION_DENIED;
4711 }
4712 int n;
4713 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004714 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004715 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004716 return NO_ERROR;
4717 case 1002: // SHOW_UPDATES
4718 n = data.readInt32();
4719 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004720 invalidateHwcGeometry();
4721 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004722 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004723 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004724 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004725 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004726 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004727 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004728 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004729 setTransactionFlags(
4730 eTransactionNeeded|
4731 eDisplayTransactionNeeded|
4732 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004733 return NO_ERROR;
4734 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004735 case 1006:{ // send empty update
4736 signalRefresh();
4737 return NO_ERROR;
4738 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004739 case 1008: // toggle use of hw composer
4740 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004741 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004742 invalidateHwcGeometry();
4743 repaintEverything();
4744 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004745 case 1009: // toggle use of transform hint
4746 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004747 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004748 invalidateHwcGeometry();
4749 repaintEverything();
4750 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004751 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004752 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004753 reply->writeInt32(0);
4754 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004755 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004756 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004757 return NO_ERROR;
4758 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004759 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004760 if (!display) {
4761 return NAME_NOT_FOUND;
4762 }
4763
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004764 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004765 return NO_ERROR;
4766 }
4767 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004768 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004769 // daltonize
4770 n = data.readInt32();
4771 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004772 case 1:
4773 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4774 break;
4775 case 2:
4776 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4777 break;
4778 case 3:
4779 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4780 break;
4781 default:
4782 mDaltonizer.setType(ColorBlindnessType::None);
4783 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004784 }
4785 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004786 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004787 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004788 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004789 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004790
4791 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004792 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004793 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004794 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004795 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004796 // apply a color matrix
4797 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004798 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004799 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004800 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004801 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004802 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004803 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004804 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004805 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004806 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004807 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004808
4809 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4810 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004811 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004812 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4813 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4814 }
4815
Chia-I Wu28f320b2018-05-03 11:02:56 -07004816 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004817 return NO_ERROR;
4818 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004819 case 1016: { // Unused.
4820 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004821 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004822 case 1017: {
4823 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004824 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004825 return NO_ERROR;
4826 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004827 case 1018: { // Modify Choreographer's phase offset
4828 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004829 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004830 return NO_ERROR;
4831 }
4832 case 1019: { // Modify SurfaceFlinger's phase offset
4833 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004834 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004835 return NO_ERROR;
4836 }
Irvel468051e2016-06-13 16:44:44 -07004837 case 1020: { // Layer updates interceptor
4838 n = data.readInt32();
4839 if (n) {
4840 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004841 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004842 }
4843 else{
4844 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004845 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004846 }
4847 return NO_ERROR;
4848 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004849 case 1021: { // Disable HWC virtual displays
4850 n = data.readInt32();
4851 mUseHwcVirtualDisplays = !n;
4852 return NO_ERROR;
4853 }
Romain Guy0147a172017-06-01 13:53:56 -07004854 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004855 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004856 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004857
Chia-I Wu28f320b2018-05-03 11:02:56 -07004858 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004859 return NO_ERROR;
4860 }
Romain Guy54f154a2017-10-24 21:40:32 +01004861 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004862 int32_t colorMode;
4863
Chia-I Wu0d711262018-05-21 15:19:35 -07004864 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004865 if (data.readInt32(&colorMode) == NO_ERROR) {
4866 mForceColorMode = static_cast<ColorMode>(colorMode);
4867 }
Romain Guy54f154a2017-10-24 21:40:32 +01004868 invalidateHwcGeometry();
4869 repaintEverything();
4870 return NO_ERROR;
4871 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004872 // Deprecate, use 1030 to check whether the device is color managed.
4873 case 1024: {
4874 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004875 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004876 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004877 n = data.readInt32();
4878 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004879 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004880 Mutex::Autolock lock(mStateLock);
4881 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004882 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004883 reply->writeInt32(NO_ERROR);
4884 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004885 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004886 bool writeFile = false;
4887 {
4888 Mutex::Autolock lock(mStateLock);
4889 mTracingEnabledChanged = true;
4890 writeFile = mTracing.disable();
4891 }
4892
4893 if (writeFile) {
4894 reply->writeInt32(mTracing.writeToFile());
4895 } else {
4896 reply->writeInt32(NO_ERROR);
4897 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004898 }
4899 return NO_ERROR;
4900 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004901 case 1026: { // Get layer tracing status
4902 reply->writeBool(mTracing.isEnabled());
4903 return NO_ERROR;
4904 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004905 // Is a DisplayColorSetting supported?
4906 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004907 const auto display = getDefaultDisplayDevice();
4908 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004909 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004910 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004911
4912 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4913 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004914 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004915 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004916 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004917 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004918 reply->writeBool(true);
4919 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004920 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004921 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004922 break;
4923 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004924 reply->writeBool(
4925 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004926 break;
4927 }
4928 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004929 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004930 // Is VrFlinger active?
4931 case 1028: {
4932 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004933 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004934 return NO_ERROR;
4935 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004936 // Set buffer size for SF tracing (value in KB)
4937 case 1029: {
4938 n = data.readInt32();
4939 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4940 ALOGW("Invalid buffer size: %d KB", n);
4941 reply->writeInt32(BAD_VALUE);
4942 return BAD_VALUE;
4943 }
4944
4945 ALOGD("Updating trace buffer to %d KB", n);
4946 mTracing.setBufferSize(n * 1024);
4947 reply->writeInt32(NO_ERROR);
4948 return NO_ERROR;
4949 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004950 // Is device color managed?
4951 case 1030: {
4952 reply->writeBool(useColorManagement);
4953 return NO_ERROR;
4954 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004955 // Override default composition data space
4956 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4957 // && adb shell stop zygote && adb shell start zygote
4958 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4959 // adb shell stop zygote && adb shell start zygote
4960 case 1031: {
4961 Mutex::Autolock _l(mStateLock);
4962 n = data.readInt32();
4963 if (n) {
4964 n = data.readInt32();
4965 if (n) {
4966 Dataspace dataspace = static_cast<Dataspace>(n);
4967 if (!validateCompositionDataspace(dataspace)) {
4968 return BAD_VALUE;
4969 }
4970 mDefaultCompositionDataspace = dataspace;
4971 }
4972 n = data.readInt32();
4973 if (n) {
4974 Dataspace dataspace = static_cast<Dataspace>(n);
4975 if (!validateCompositionDataspace(dataspace)) {
4976 return BAD_VALUE;
4977 }
4978 mWideColorGamutCompositionDataspace = dataspace;
4979 }
4980 } else {
4981 // restore composition data space.
4982 mDefaultCompositionDataspace = defaultCompositionDataspace;
4983 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4984 }
4985 return NO_ERROR;
4986 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004987 // Set trace flags
4988 case 1033: {
4989 n = data.readUint32();
4990 ALOGD("Updating trace flags to 0x%x", n);
4991 mTracing.setTraceFlags(n);
4992 reply->writeInt32(NO_ERROR);
4993 return NO_ERROR;
4994 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004995 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004996 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004997 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004998 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08004999 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
5000 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08005001 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07005002 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08005003 } else {
5004 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07005005 }
5006 return NO_ERROR;
5007 }
Ady Abraham34392f72019-04-10 11:29:27 -07005008 case 1035: {
5009 n = data.readInt32();
5010 mDebugDisplayConfigSetByBackdoor = false;
5011 if (n >= 0) {
5012 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005013 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07005014 if (result != NO_ERROR) {
5015 return result;
5016 }
5017 mDebugDisplayConfigSetByBackdoor = true;
5018 }
5019 return NO_ERROR;
5020 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005021 }
5022 }
5023 return err;
5024}
5025
Steven Thomas6d8110b2017-08-31 18:24:21 -07005026void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005027 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005028 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005029}
5030
Ana Krulec7d1d6832018-12-27 11:10:09 -08005031void SurfaceFlinger::repaintEverythingForHWC() {
5032 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005033 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005034}
5035
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005036// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5037class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005038public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005039 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5040 ~WindowDisconnector() {
5041 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005042 }
5043
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005044private:
5045 ANativeWindow* mWindow;
5046 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005047};
5048
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005049status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005050 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005051 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5052 const Rect& sourceCrop, uint32_t reqWidth,
5053 uint32_t reqHeight, bool useIdentityTransform,
5054 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005055 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005056
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005057 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005058
Dominik Laskowski718f9602019-11-09 20:01:35 -08005059 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5060 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5061 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5062 renderAreaRotation = ui::Transform::ROT_0;
5063 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005064
Chia-I Wu20261cb2018-08-23 12:55:44 -07005065 sp<DisplayDevice> display;
5066 {
5067 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005068
Chia-I Wu20261cb2018-08-23 12:55:44 -07005069 display = getDisplayDeviceLocked(displayToken);
5070 if (!display) return BAD_VALUE;
5071
Chia-I Wucb023152018-08-28 12:57:23 -07005072 // set the requested width/height to the logical display viewport size
5073 // by default
5074 if (reqWidth == 0 || reqHeight == 0) {
5075 reqWidth = uint32_t(display->getViewport().width());
5076 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005077 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005078 }
5079
Peiyong Lin0e003c92018-09-17 11:09:51 -07005080 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005081 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005082
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005083 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5084 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005085 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005086 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005087}
5088
chaviw93df2ea2019-04-30 16:45:12 -07005089static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5090 switch (colorMode) {
5091 case ColorMode::DISPLAY_P3:
5092 case ColorMode::BT2100_PQ:
5093 case ColorMode::BT2100_HLG:
5094 case ColorMode::DISPLAY_BT2020:
5095 return Dataspace::DISPLAY_P3;
5096 default:
5097 return Dataspace::V0_SRGB;
5098 }
5099}
5100
5101const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5102 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5103 if (displayToken) {
5104 return getDisplayDeviceLocked(displayToken);
5105 }
5106 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5107 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005108 return getDisplayByLayerStack(displayOrLayerStack);
5109}
5110
5111const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005112 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005113 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005114 return display;
5115 }
5116 }
5117 return nullptr;
5118}
5119
5120status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5121 sp<GraphicBuffer>* outBuffer) {
5122 sp<DisplayDevice> display;
5123 uint32_t width;
5124 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005125 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005126 {
5127 Mutex::Autolock _l(mStateLock);
5128 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5129 if (!display) {
5130 return BAD_VALUE;
5131 }
5132
5133 width = uint32_t(display->getViewport().width());
5134 height = uint32_t(display->getViewport().height());
5135
Dominik Laskowski718f9602019-11-09 20:01:35 -08005136 const auto orientation = display->getOrientation();
5137 captureOrientation = ui::Transform::toRotationFlags(orientation);
5138
5139 switch (captureOrientation) {
5140 case ui::Transform::ROT_90:
5141 captureOrientation = ui::Transform::ROT_270;
5142 break;
5143
5144 case ui::Transform::ROT_270:
5145 captureOrientation = ui::Transform::ROT_90;
5146 break;
5147
5148 case ui::Transform::ROT_INVALID:
5149 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5150 captureOrientation = ui::Transform::ROT_0;
5151 break;
5152
5153 default:
5154 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005155 }
chaviw93df2ea2019-04-30 16:45:12 -07005156 *outDataspace =
5157 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5158 }
5159
5160 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5161 false /* captureSecureLayers */);
5162
5163 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5164 std::placeholders::_1);
5165 bool ignored = false;
5166 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5167 false /* useIdentityTransform */,
5168 ignored /* outCapturedSecureLayers */);
5169}
5170
Robert Carr866455f2019-04-02 16:28:26 -07005171status_t SurfaceFlinger::captureLayers(
5172 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5173 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5174 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5175 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005176 ATRACE_CALL();
5177
5178 class LayerRenderArea : public RenderArea {
5179 public:
Robert Carr578038f2018-03-09 12:25:24 -08005180 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005181 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005182 bool childrenOnly, const Rect& displayViewport)
5183 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005184 mLayer(layer),
5185 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005186 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005187 mFlinger(flinger),
5188 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005189 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005190 Rect getBounds() const override {
5191 const Layer::State& layerState(mLayer->getDrawingState());
5192 return mLayer->getBufferSize(layerState);
5193 }
Marissa Wall61c58622018-07-18 10:12:20 -07005194 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005195 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005196 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005197 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005198 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005199 }
chaviwa76b2712017-09-20 12:02:26 -07005200 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005201 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005202 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005203 Rect getSourceCrop() const override {
5204 if (mCrop.isEmpty()) {
5205 return getBounds();
5206 } else {
5207 return mCrop;
5208 }
5209 }
Robert Carr578038f2018-03-09 12:25:24 -08005210 class ReparentForDrawing {
5211 public:
5212 const sp<Layer>& oldParent;
5213 const sp<Layer>& newParent;
5214
Vishnu Nair4351ad52019-02-11 14:13:02 -08005215 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5216 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005217 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005218 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005219 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5220 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005221 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005222 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005223 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005224 };
5225
5226 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005227 const Rect sourceCrop = getSourceCrop();
5228 // no need to check rotation because there is none
5229 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5230 sourceCrop.height() != getReqHeight();
5231
Robert Carr578038f2018-03-09 12:25:24 -08005232 if (!mChildrenOnly) {
5233 mTransform = mLayer->getTransform().inverse();
5234 drawLayers();
5235 } else {
5236 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005237 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5238 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005239 // In the "childrenOnly" case we reparent the children to a screenshot
5240 // layer which has no properties set and which does not draw.
5241 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005242 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5243 "Screenshot Parent"s, w, h, 0,
5244 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005245
Vishnu Nair4351ad52019-02-11 14:13:02 -08005246 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005247 drawLayers();
5248 }
5249 }
chaviwa76b2712017-09-20 12:02:26 -07005250
chaviwa76b2712017-09-20 12:02:26 -07005251 private:
chaviw7206d492017-11-10 16:16:12 -08005252 const sp<Layer> mLayer;
5253 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005254
Peiyong Linefefaac2018-08-17 12:27:51 -07005255 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005256 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005257
5258 SurfaceFlinger* mFlinger;
5259 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005260 };
5261
Robert Carrc0df3122019-04-11 13:18:21 -07005262 int reqWidth = 0;
5263 int reqHeight = 0;
5264 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005265 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005266 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005267 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005268 {
5269 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005270
Robert Carrc0df3122019-04-11 13:18:21 -07005271 parent = fromHandle(layerHandleBinder);
5272 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5273 ALOGE("captureLayers called with an invalid or removed parent");
5274 return NAME_NOT_FOUND;
5275 }
5276
5277 const int uid = IPCThreadState::self()->getCallingUid();
5278 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5279 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5280 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5281 return PERMISSION_DENIED;
5282 }
5283
Vishnu Nairefc42e22019-12-03 17:36:12 -08005284 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005285 if (sourceCrop.width() <= 0) {
5286 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005287 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005288 }
5289
5290 if (sourceCrop.height() <= 0) {
5291 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005292 crop.bottom = parentSourceBounds.getHeight();
5293 }
5294
5295 if (crop.isEmpty() || frameScale <= 0.0f) {
5296 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5297 // crop was not specified, or an invalid frame scale was provided.
5298 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005299 }
5300 reqWidth = crop.width() * frameScale;
5301 reqHeight = crop.height() * frameScale;
5302
5303 for (const auto& handle : excludeHandles) {
5304 sp<Layer> excludeLayer = fromHandle(handle);
5305 if (excludeLayer != nullptr) {
5306 excludeLayers.emplace(excludeLayer);
5307 } else {
5308 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5309 return NAME_NOT_FOUND;
5310 }
5311 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005312
5313 auto display = getDisplayByLayerStack(parent->getLayerStack());
5314 if (!display) {
5315 return BAD_VALUE;
5316 }
5317
5318 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005319 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005320
Chia-I Wu20261cb2018-08-23 12:55:44 -07005321 // really small crop or frameScale
5322 if (reqWidth <= 0) {
5323 reqWidth = 1;
5324 }
5325 if (reqHeight <= 0) {
5326 reqHeight = 1;
5327 }
5328
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005329 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5330 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005331 auto traverseLayers = [parent, childrenOnly,
5332 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005333 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5334 if (!layer->isVisible()) {
5335 return;
Robert Carr578038f2018-03-09 12:25:24 -08005336 } else if (childrenOnly && layer == parent.get()) {
5337 return;
chaviwa76b2712017-09-20 12:02:26 -07005338 }
Robert Carr866455f2019-04-02 16:28:26 -07005339
5340 sp<Layer> p = layer;
5341 while (p != nullptr) {
5342 if (excludeLayers.count(p) != 0) {
5343 return;
5344 }
5345 p = p->getParent();
5346 }
5347
chaviwa76b2712017-09-20 12:02:26 -07005348 visitor(layer);
5349 });
5350 };
Robert Carr108b2c72019-04-02 16:32:58 -07005351
5352 bool outCapturedSecureLayers = false;
5353 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5354 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005355}
5356
5357status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5358 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005359 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005360 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005361 bool useIdentityTransform,
5362 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005363 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005364
Peiyong Lin0e003c92018-09-17 11:09:51 -07005365 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005366 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5367 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005368 *outBuffer =
5369 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5370 static_cast<android_pixel_format>(reqPixelFormat), 1,
5371 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005372
Robert Carr108b2c72019-04-02 16:32:58 -07005373 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5374 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005375}
5376
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005377status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5378 TraverseLayersFunction traverseLayers,
5379 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005380 bool useIdentityTransform,
5381 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005382 // This mutex protects syncFd and captureResult for communication of the return values from the
5383 // main thread back to this Binder thread
5384 std::mutex captureMutex;
5385 std::condition_variable captureCondition;
5386 std::unique_lock<std::mutex> captureLock(captureMutex);
5387 int syncFd = -1;
5388 std::optional<status_t> captureResult;
5389
Robert Carr03480e22018-01-04 16:02:06 -08005390 const int uid = IPCThreadState::self()->getCallingUid();
5391 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5392
Dominik Laskowski8c001672018-05-30 16:52:06 -07005393 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005394 // If there is a refresh pending, bug out early and tell the binder thread to try again
5395 // after the refresh.
5396 if (mRefreshPending) {
5397 ATRACE_NAME("Skipping screenshot for now");
5398 std::unique_lock<std::mutex> captureLock(captureMutex);
5399 captureResult = std::make_optional<status_t>(EAGAIN);
5400 captureCondition.notify_one();
5401 return;
5402 }
5403
5404 status_t result = NO_ERROR;
5405 int fd = -1;
5406 {
5407 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005408 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005409 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005410 useIdentityTransform, forSystem, &fd,
5411 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005412 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005413 }
5414
5415 {
5416 std::unique_lock<std::mutex> captureLock(captureMutex);
5417 syncFd = fd;
5418 captureResult = std::make_optional<status_t>(result);
5419 captureCondition.notify_one();
5420 }
5421 });
5422
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005423 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005424 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005425 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005426 while (*captureResult == EAGAIN) {
5427 captureResult.reset();
5428 result = postMessageAsync(message);
5429 if (result != NO_ERROR) {
5430 return result;
5431 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005432 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005433 }
5434 result = *captureResult;
5435 }
5436
5437 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005438 sync_wait(syncFd, -1);
5439 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005440 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005441
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005442 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005443}
5444
chaviwa76b2712017-09-20 12:02:26 -07005445void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005446 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005447 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5448 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005449 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005450
chaviwa76b2712017-09-20 12:02:26 -07005451 const auto reqWidth = renderArea.getReqWidth();
5452 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005453 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005454 const auto transform = renderArea.getTransform();
5455 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005456 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005457
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005458 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005459 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005460
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005461 // assume that bounds are never offset, and that they are the same as the
5462 // buffer bounds.
5463 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005464 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005465 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005466
5467 // Now take into account the rotation flag. We append a transform that
5468 // rotates the layer stack about the origin, then translate by buffer
5469 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005470 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005471 int displacementX = 0;
5472 int displacementY = 0;
5473 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5474 switch (rotation) {
5475 case ui::Transform::ROT_90:
5476 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005477 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005478 break;
5479 case ui::Transform::ROT_180:
5480 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005481 displacementY = renderArea.getBounds().getWidth();
5482 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005483 break;
5484 case ui::Transform::ROT_270:
5485 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005486 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005487 break;
5488 default:
5489 break;
5490 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005491
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005492 // We need to transform the clipping window into the right spot.
5493 // First, rotate the clipping rectangle by the rotation hint to get the
5494 // right orientation
5495 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5496 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5497 const vec4 rotClipTL = rotMatrix * clipTL;
5498 const vec4 rotClipBR = rotMatrix * clipBR;
5499 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5500 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5501 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5502 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5503
5504 // Now reposition the clipping rectangle with the displacement vector
5505 // computed above.
5506 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005507 clientCompositionDisplay.clip =
5508 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5509 newClipRight + displacementX, newClipBottom + displacementY);
5510
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005511 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005512 clientCompositionDisplay.globalTransform =
5513 clipTransform * clientCompositionDisplay.globalTransform;
5514
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005515 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5516 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005517
chaviw50da5042018-04-09 13:49:37 -07005518 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005519
Vishnu Nair9b079a22020-01-21 14:36:08 -08005520 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005521 fillLayer.source.buffer.buffer = nullptr;
5522 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5523 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5524 fillLayer.alpha = half(alpha);
5525 clientCompositionLayers.push_back(fillLayer);
5526
5527 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005528 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005529 const bool supportProtectedContent = false;
5530 Region clip(renderArea.getBounds());
5531 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5532 clip,
5533 useIdentityTransform,
5534 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5535 renderArea.isSecure(),
5536 supportProtectedContent,
5537 clearRegion,
5538 };
5539 auto result = layer->prepareClientComposition(targetSettings);
5540 if (result) {
Vishnu Nair9b079a22020-01-21 14:36:08 -08005541 std::optional<compositionengine::LayerFE::LayerSettings> shadowLayer =
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005542 layer->prepareShadowClientComposition(*result, displayViewport,
5543 clientCompositionDisplay.outputDataspace);
5544 if (shadowLayer) {
5545 clientCompositionLayers.push_back(*shadowLayer);
5546 }
Lloyd Piquef16688f2019-02-19 17:47:57 -08005547 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005548 }
chaviwa76b2712017-09-20 12:02:26 -07005549 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005550
Vishnu Nair9b079a22020-01-21 14:36:08 -08005551 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5552 clientCompositionLayers.reserve(clientCompositionLayers.size());
5553 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5554 std::back_inserter(clientCompositionLayerPointers),
5555 [](compositionengine::LayerFE::LayerSettings& settings)
5556 -> renderengine::LayerSettings* { return &settings; });
5557
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005558 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005559 // Use an empty fence for the buffer fence, since we just created the buffer so
5560 // there is no need for synchronization with the GPU.
5561 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005562 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005563 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005564 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005565 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005566
5567 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005568}
5569
chaviwa76b2712017-09-20 12:02:26 -07005570status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5571 TraverseLayersFunction traverseLayers,
5572 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005573 bool useIdentityTransform, bool forSystem,
5574 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005575 ATRACE_CALL();
5576
chaviwa76b2712017-09-20 12:02:26 -07005577 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005578 outCapturedSecureLayers =
5579 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005580 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005581
Robert Carr03480e22018-01-04 16:02:06 -08005582 // We allow the system server to take screenshots of secure layers for
5583 // use in situations like the Screen-rotation animation and place
5584 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005585 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005586 ALOGW("FB is protected: PERMISSION_DENIED");
5587 return PERMISSION_DENIED;
5588 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005589 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005590 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005591}
5592
chaviw95ef3c42019-02-14 10:55:09 -08005593void SurfaceFlinger::setInputWindowsFinished() {
5594 Mutex::Autolock _l(mStateLock);
5595
5596 mPendingSyncInputWindows = false;
5597 mTransactionCV.broadcast();
5598}
chaviw5f21a5e2019-02-14 10:00:34 -08005599
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005600// ---------------------------------------------------------------------------
5601
Edgar Arriaga844fa672020-01-16 14:21:42 -08005602void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5603 layersSortedByZ.traverse(visitor);
5604}
5605
Dan Stoza412903f2017-04-27 13:42:17 -07005606void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5607 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005608}
5609
Dan Stoza412903f2017-04-27 13:42:17 -07005610void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5611 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005612}
5613
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005614void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005615 const LayerVector::Visitor& visitor) {
5616 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005617 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005618 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005619 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005620 continue;
5621 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005622 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005623 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005624 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005625 return;
5626 }
chaviwa76b2712017-09-20 12:02:26 -07005627 if (!layer->isVisible()) {
5628 return;
5629 }
5630 visitor(layer);
5631 });
5632 }
5633}
5634
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005635status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5636 HwcConfigIndexType defaultConfig,
5637 float minRefreshRate,
5638 float maxRefreshRate) {
5639 Mutex::Autolock lock(mStateLock);
5640
Dominik Laskowski22488f62019-03-28 09:53:04 -07005641 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005642 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5643 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5644 // it should go thru setDesiredActiveConfig, similar to primary display.
5645 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5646 const auto displayId = display->getId();
5647 LOG_ALWAYS_FATAL_IF(!displayId);
5648
5649 HWC2::VsyncPeriodChangeConstraints constraints;
5650 constraints.desiredTimeNanos = systemTime();
5651 constraints.seamlessRequired = false;
5652
5653 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005654 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5655 constraints, &timeline) < 0) {
5656 return BAD_VALUE;
5657 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005658 if (timeline.refreshRequired) {
5659 repaintEverythingForHWC();
5660 }
5661
Ady Abrahamdfa37362020-01-21 18:02:39 -08005662 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005663 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005664 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5665 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005666 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005667 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005668 }
5669
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005670 if (mDebugDisplayConfigSetByBackdoor) {
5671 // ignore this request as config is overridden by backdoor
5672 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005673 }
5674
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005675 bool policyChanged;
5676 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5677 &policyChanged) < 0) {
5678 return BAD_VALUE;
5679 }
5680 if (!policyChanged) {
5681 return NO_ERROR;
5682 }
5683
5684 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5685 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005686
5687 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5688 // that listeners that care about a change in allowed configs can get the notification.
5689 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005690 const nsecs_t vsyncPeriod =
5691 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005692 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005693 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005694
Ana Krulec8c6f3f62020-01-23 15:48:01 -08005695 auto configId = mScheduler->getPreferredConfigId();
5696 auto preferredRefreshRate = configId
5697 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5698 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5699 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5700 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5701 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5702
5703 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5704 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5705 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005706 } else {
Ana Krulec8c6f3f62020-01-23 15:48:01 -08005707 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005708 }
5709
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005710 return NO_ERROR;
5711}
5712
Ana Krulec0782b882019-10-15 17:34:54 -07005713status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005714 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005715 float maxRefreshRate) {
5716 ATRACE_CALL();
5717
5718 if (!displayToken) {
5719 return BAD_VALUE;
5720 }
5721
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005722 status_t result = NO_ERROR;
5723
Ana Krulec234bb162019-11-10 22:55:55 +01005724 postMessageSync(new LambdaMessage([&]() {
5725 const auto display = getDisplayDeviceLocked(displayToken);
5726 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005727 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005728 ALOGE("Attempt to set desired display configs for invalid display token %p",
5729 displayToken.get());
5730 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005731 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005732 ALOGW("Attempt to set desired display configs for virtual display");
5733 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005734 result =
5735 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5736 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005737 }
5738 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005739
5740 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005741}
5742
5743status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005744 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005745 float* outMinRefreshRate,
5746 float* outMaxRefreshRate) {
5747 ATRACE_CALL();
5748
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005749 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005750 return BAD_VALUE;
5751 }
5752
5753 Mutex::Autolock lock(mStateLock);
5754 const auto display = getDisplayDeviceLocked(displayToken);
5755 if (!display) {
5756 return NAME_NOT_FOUND;
5757 }
5758
5759 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005760 HwcConfigIndexType defaultConfig;
5761 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5762 *outDefaultConfig = defaultConfig.value();
5763 return NO_ERROR;
5764 } else if (display->isVirtual()) {
5765 return BAD_VALUE;
5766 } else {
5767 const auto displayId = display->getId();
5768 if (!displayId) {
5769 return BAD_VALUE;
5770 }
5771 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5772 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5773 *outMinRefreshRate = 1e9f / vsyncPeriod;
5774 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5775 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005776 }
Ana Krulec0782b882019-10-15 17:34:54 -07005777}
5778
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005779void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005780 mFlinger->setInputWindowsFinished();
5781}
5782
Robert Carrc0df3122019-04-11 13:18:21 -07005783sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005784 BBinder* b = nullptr;
5785 if (handle) {
5786 b = handle->localBinder();
5787 }
Robert Carrc0df3122019-04-11 13:18:21 -07005788 if (b == nullptr) {
5789 return nullptr;
5790 }
5791 auto it = mLayersByLocalBinderToken.find(b);
5792 if (it != mLayersByLocalBinderToken.end()) {
5793 return it->second.promote();
5794 }
5795 return nullptr;
5796}
5797
Dominik Laskowski75848362019-11-11 17:57:20 -08005798void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005799 mNumLayers++;
5800 mScheduler->registerLayer(layer);
5801}
5802
5803void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5804 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005805 removeFromOffscreenLayers(layer);
5806}
5807
5808// WARNING: ONLY CALL THIS FROM LAYER DTOR
5809// Here we add children in the current state to offscreen layers and remove the
5810// layer itself from the offscreen layer list. Since
5811// this is the dtor, it is safe to access the current state. This keeps us
5812// from dangling children layers such that they are not reachable from the
5813// Drawing state nor the offscreen layer list
5814// See b/141111965
5815void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5816 for (auto& child : layer->getCurrentChildren()) {
5817 mOffscreenLayers.emplace(child.get());
5818 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005819 mOffscreenLayers.erase(layer);
5820}
5821
Alec Mouri4545a8a2019-08-08 20:05:32 -07005822void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5823 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5824}
5825
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005826status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5827 float lightPosY, float lightPosZ,
5828 float lightRadius) {
5829 Mutex::Autolock _l(mStateLock);
5830 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5831 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5832 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5833 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5834 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5835
5836 // these values are overridden when calculating the shadow settings for a layer.
5837 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5838 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005839 return NO_ERROR;
5840}
5841
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005842} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005843
Mathias Agopian3f844832013-08-07 21:24:32 -07005844#if defined(__gl_h_)
5845#error "don't include gl/gl.h in this file"
5846#endif
5847
5848#if defined(__gl2_h_)
5849#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005850#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005851
5852// TODO(b/129481165): remove the #pragma below and fix conversion issues
5853#pragma clang diagnostic pop // ignored "-Wconversion"