blob: 899ae02c29fa8facfc45fa6f373d29112769f2f6 [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>
64#include <ui/DisplayInfo.h>
65#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070066#include <ui/GraphicBufferAllocator.h>
67#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070068#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080069#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/String16.h>
71#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070072#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080073#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070074#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080075
Mathias Agopian921e6ac2012-07-23 23:11:29 -070076#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070077#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080078
Robert Carr578038f2018-03-09 12:25:24 -080079#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070080#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070081#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020082#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080083#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020084#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080085#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080086#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080087#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070088#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080089#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070090#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070091#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070092#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080093#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070094#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080095
Steven Thomasb02664d2017-07-26 18:48:28 -070096#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070097#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070098#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070099#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -0700100#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -0700101#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -0700102#include "FrameTracer/FrameTracer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700103#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700104#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700105#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700106#include "Scheduler/EventControlThread.h"
107#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700108#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700109#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700110#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800111#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700112
Mathias Agopianff2ed702013-09-01 21:36:12 -0700113#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700114
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700115#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800116#include "android-base/stringprintf.h"
117
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900118#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800119#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
120#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700121#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900122#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900123
chaviw1d044282017-09-27 12:19:28 -0700124#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900125#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700126
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800127namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700128
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700129using namespace std::string_literals;
130
Jaesoo Lee43518572017-01-23 19:03:16 +0900131using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900132using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900133using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800134
Ady Abraham8532d012019-05-08 14:50:56 -0700135using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800136using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700137using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700138using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800139using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700140using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700141using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900142
Steven Thomasb02664d2017-07-26 18:48:28 -0700143namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700144
145#pragma clang diagnostic push
146#pragma clang diagnostic error "-Wswitch-enum"
147
148bool isWideColorMode(const ColorMode colorMode) {
149 switch (colorMode) {
150 case ColorMode::DISPLAY_P3:
151 case ColorMode::ADOBE_RGB:
152 case ColorMode::DCI_P3:
153 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700154 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700155 case ColorMode::BT2100_PQ:
156 case ColorMode::BT2100_HLG:
157 return true;
158 case ColorMode::NATIVE:
159 case ColorMode::STANDARD_BT601_625:
160 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
161 case ColorMode::STANDARD_BT601_525:
162 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
163 case ColorMode::STANDARD_BT709:
164 case ColorMode::SRGB:
165 return false;
166 }
167 return false;
168}
169
170#pragma clang diagnostic pop
171
Steven Thomasb02664d2017-07-26 18:48:28 -0700172class ConditionalLock {
173public:
174 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
175 if (lock) {
176 mMutex.lock();
177 }
178 }
179 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
180private:
181 Mutex& mMutex;
182 bool mLocked;
183};
Peiyong Linfca547f2018-07-09 13:03:33 -0700184
Peiyong Lin9d846a52018-11-05 13:18:20 -0800185// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
186bool validateCompositionDataspace(Dataspace dataspace) {
187 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
188}
189
Steven Thomasb02664d2017-07-26 18:48:28 -0700190} // namespace anonymous
191
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800192// ---------------------------------------------------------------------------
193
Mathias Agopian99b49842011-06-27 16:05:52 -0700194const String16 sHardwareTest("android.permission.HARDWARE_TEST");
195const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
196const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
197const String16 sDump("android.permission.DUMP");
198
199// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700200int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700201bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800202uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800203bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800204bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800205int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600206bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800207ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700208bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700209bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700210Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
211ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
212Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
213ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700214
Kalle Raitaa099a242017-01-11 11:17:29 -0800215std::string getHwcServiceName() {
216 char value[PROPERTY_VALUE_MAX] = {};
217 property_get("debug.sf.hwc_service_name", value, "default");
218 ALOGI("Using HWComposer service: '%s'", value);
219 return std::string(value);
220}
221
222bool useTrebleTestingOverride() {
223 char value[PROPERTY_VALUE_MAX] = {};
224 property_get("debug.sf.treble_testing_override", value, "false");
225 ALOGI("Treble testing override: '%s'", value);
226 return std::string(value) == "true";
227}
228
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800229std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
230 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800231 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700232 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800233 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700234 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800235 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700236 return std::string("Enhanced");
237 default:
238 return std::string("Unknown ") +
239 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800240 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800241}
242
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700243SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800244
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700245SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
246 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700247 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700248 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700249 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700250 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700251 mCompositionEngine(mFactory.createCompositionEngine()),
Valerie Haud251afb2019-03-29 14:19:02 -0700252 mPendingSyncInputWindows(false) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800253
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700254SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800255 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800256
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900257 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800258
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900259 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700260
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900261 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700262
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900263 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800264
Steven Thomas050b2c82017-03-06 11:45:16 -0800265 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900266 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800267
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900268 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800269
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900270 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700271
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900272 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600273
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900274 mDefaultCompositionDataspace =
275 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700276 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
277 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 defaultCompositionDataspace = mDefaultCompositionDataspace;
279 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
280 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
281 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
282 wideColorGamutCompositionPixelFormat =
283 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700284
Yichi Chenda901bf2019-06-28 14:58:27 +0800285 mColorSpaceAgnosticDataspace =
286 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
287
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800289
Dominik Laskowski718f9602019-11-09 20:01:35 -0800290 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
291 switch (primary_display_orientation(Values::ORIENTATION_0)) {
292 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800293 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800294 case Values::ORIENTATION_90:
295 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800296 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800297 case Values::ORIENTATION_180:
298 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800299 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800300 case Values::ORIENTATION_270:
301 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800302 break;
303 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800304 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800305
Sundong Ahn85131bd2019-02-18 15:51:53 +0900306 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800307
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800308 // debugging stuff...
309 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700310
Mathias Agopianb4b17302013-03-20 18:36:41 -0700311 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700312 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700313
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800314 property_get("debug.sf.showupdates", value, "0");
315 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700316
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700317 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000318
319 // DDMS debugging deprecated (b/120782499)
320 property_get("debug.sf.ddms", value, "0");
321 int debugDdms = atoi(value);
322 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700323
324 property_get("debug.sf.disable_backpressure", value, "0");
325 mPropagateBackpressure = !atoi(value);
326 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700327
Ady Abrahamadb9a992019-09-19 21:21:55 +0000328 property_get("debug.sf.enable_gl_backpressure", value, "0");
329 mPropagateBackpressureClientComposition = atoi(value);
330 ALOGI_IF(mPropagateBackpressureClientComposition,
331 "Enabling backpressure propagation for Client Composition");
332
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800333 property_get("debug.sf.enable_hwc_vds", value, "0");
334 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800335 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800336
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800337 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800338 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800339 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700340
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800341 property_get("ro.surface_flinger.supports_background_blur", value, "0");
342 bool supportsBlurs = atoi(value);
343 property_get("debug.sf.disableBlurs", value, "0");
344 bool disableBlurs = atoi(value);
345 mEnableBlurs = supportsBlurs && !disableBlurs;
346 ALOGI_IF(!mEnableBlurs, "Disabling blur effects. supported: %d, disabled: %d", supportsBlurs,
347 disableBlurs);
348
Yiwei Zhang243b3782018-05-15 17:40:04 -0700349 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700350 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
351 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
352
Dan Stozaec460082018-12-17 15:35:09 -0800353 property_get("debug.sf.luma_sampling", value, "1");
354 mLumaSampling = atoi(value);
355
Vishnu Nairb2a999b2020-01-23 13:43:02 -0800356 property_get("debug.sf.disable_client_composition_cache", value, "0");
Vishnu Nair9b079a22020-01-21 14:36:08 -0800357 mDisableClientCompositionCache = atoi(value);
358
Romain Guy11d63f42017-07-20 12:47:14 -0700359 // We should be reading 'persist.sys.sf.color_saturation' here
360 // but since /data may be encrypted, we need to wait until after vold
361 // comes online to attempt to read the property. The property is
362 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800363
364 if (useTrebleTestingOverride()) {
365 // Without the override SurfaceFlinger cannot connect to HIDL
366 // services that are not listed in the manifests. Considered
367 // deriving the setting from the set service name, but it
368 // would be brittle if the name that's not 'default' is used
369 // for production purposes later on.
370 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
371 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800372}
373
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800374void SurfaceFlinger::onFirstRef()
375{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800376 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800377}
378
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700379SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380
Dan Stozac7014012014-02-14 15:03:43 -0800381void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800382{
383 // the window manager died on us. prepare its eulogy.
384
Andy McFadden13a082e2012-08-24 10:16:42 -0700385 // restore initial conditions (default device unblank, etc)
386 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800387
388 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700389 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800390}
391
Robert Carr1db73f62016-12-21 12:58:51 -0800392static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700393 status_t err = client->initCheck();
394 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800395 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800396 }
Robert Carr1db73f62016-12-21 12:58:51 -0800397 return nullptr;
398}
399
400sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
401 return initClient(new Client(this));
402}
403
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700404sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
405 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700406{
407 class DisplayToken : public BBinder {
408 sp<SurfaceFlinger> flinger;
409 virtual ~DisplayToken() {
410 // no more references, this display must be terminated
411 Mutex::Autolock _l(flinger->mStateLock);
412 flinger->mCurrentState.displays.removeItem(this);
413 flinger->setTransactionFlags(eDisplayTransactionNeeded);
414 }
415 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700416 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700417 : flinger(flinger) {
418 }
419 };
420
421 sp<BBinder> token = new DisplayToken(this);
422
423 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700424 // Display ID is assigned when virtual display is allocated by HWC.
425 DisplayDeviceState state;
426 state.isSecure = secure;
427 state.displayName = displayName;
428 mCurrentState.displays.add(token, state);
429 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700430 return token;
431}
432
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700433void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700434 Mutex::Autolock _l(mStateLock);
435
Dominik Laskowski075d3172018-05-24 15:50:06 -0700436 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
437 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700438 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700439 return;
440 }
441
Dominik Laskowski075d3172018-05-24 15:50:06 -0700442 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
443 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700444 ALOGE("destroyDisplay called for non-virtual display");
445 return;
446 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700447 mInterceptor->saveDisplayDeletion(state.sequenceId);
448 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700449 setTransactionFlags(eDisplayTransactionNeeded);
450}
451
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800452std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
453 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700454
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800455 const auto internalDisplayId = getInternalDisplayIdLocked();
456 if (!internalDisplayId) {
457 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700458 }
459
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800460 std::vector<PhysicalDisplayId> displayIds;
461 displayIds.reserve(mPhysicalDisplayTokens.size());
462 displayIds.push_back(internalDisplayId->value);
463
464 for (const auto& [id, token] : mPhysicalDisplayTokens) {
465 if (id != *internalDisplayId) {
466 displayIds.push_back(id.value);
467 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700468 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700469
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800470 return displayIds;
471}
472
473sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
474 Mutex::Autolock lock(mStateLock);
475 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700476}
477
Ady Abraham37965d42018-11-01 13:43:32 -0700478status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
479 if (!outGetColorManagement) {
480 return BAD_VALUE;
481 }
482 *outGetColorManagement = useColorManagement;
483 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700484}
485
Lloyd Pique441d5042018-10-18 16:49:51 -0700486HWComposer& SurfaceFlinger::getHwComposer() const {
487 return mCompositionEngine->getHwComposer();
488}
489
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700490renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
491 return mCompositionEngine->getRenderEngine();
492}
493
Lloyd Pique70d91362018-10-18 16:02:55 -0700494compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
495 return *mCompositionEngine.get();
496}
497
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800498void SurfaceFlinger::bootFinished()
499{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700500 if (mStartPropertySetThread->join() != NO_ERROR) {
501 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800502 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800503 const nsecs_t now = systemTime();
504 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000505 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700506
Mikael Pessa90092f42019-08-26 17:22:04 -0700507 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000508 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700509
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700510 // wait patiently for the window manager death
511 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700512 mWindowManager = defaultServiceManager()->getService(name);
513 if (mWindowManager != 0) {
514 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700515 }
Robert Carr720e5062018-07-30 17:45:14 -0700516 sp<IBinder> input(defaultServiceManager()->getService(
517 String16("inputflinger")));
518 if (input == nullptr) {
519 ALOGE("Failed to link to input service");
520 } else {
521 mInputFlinger = interface_cast<IInputFlinger>(input);
522 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700523
Steven Thomas050b2c82017-03-06 11:45:16 -0800524 if (mVrFlinger) {
525 mVrFlinger->OnBootFinished();
526 }
527
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700528 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700529 // formerly we would just kill the process, but we now ask it to exit so it
530 // can choose where to stop the animation.
531 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700532
533 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
534 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
535 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700536
Ana Krulecbd6654b2019-02-15 15:18:15 -0800537 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800538 readPersistentProperties();
539 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800540
Ady Abraham8a82ba62020-01-17 12:43:17 -0800541 if (property_get_bool("sf.debug.show_refresh_rate_overlay", false)) {
542 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
543 mRefreshRateOverlay->changeRefreshRate(mRefreshRateConfigs->getCurrentRefreshRate());
544 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800545 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800546}
547
Dan Stoza436ccf32018-06-21 12:10:12 -0700548uint32_t SurfaceFlinger::getNewTexture() {
549 {
550 std::lock_guard lock(mTexturePoolMutex);
551 if (!mTexturePool.empty()) {
552 uint32_t name = mTexturePool.back();
553 mTexturePool.pop_back();
554 ATRACE_INT("TexturePoolSize", mTexturePool.size());
555 return name;
556 }
557
558 // The pool was too small, so increase it for the future
559 ++mTexturePoolSize;
560 }
561
562 // The pool was empty, so we need to get a new texture name directly using a
563 // blocking call to the main thread
564 uint32_t name = 0;
565 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
566 return name;
567}
568
Mathias Agopian3f844832013-08-07 21:24:32 -0700569void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700570 std::lock_guard lock(mTexturePoolMutex);
571 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
572 // to actually delete this or not based on mTexturePoolSize
573 mTexturePool.push_back(texture);
574 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700575}
576
Wei Wangf9b05ee2017-07-19 20:59:39 -0700577// Do not call property_set on main thread which will be blocked by init
578// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700579void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700580 ALOGI( "SurfaceFlinger's main thread ready to run. "
581 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700582 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800583
Steven Thomasb02664d2017-07-26 18:48:28 -0700584 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700585 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800586 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700587 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
588 renderengine::RenderEngineCreationArgs::Builder()
589 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
590 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
591 .setUseColorManagerment(useColorManagement)
592 .setEnableProtectedContext(enable_protected_contents(false))
593 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800594 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700595 .setContextPriority(useContextPriority
596 ? renderengine::RenderEngine::ContextPriority::HIGH
597 : renderengine::RenderEngine::ContextPriority::MEDIUM)
598 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800599 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700600
601 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
602 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700603 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
604 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800605 // Process any initial hotplug and resulting display changes.
606 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700607 const auto display = getDefaultDisplayDeviceLocked();
608 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700609 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700610 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800611
Steven Thomas050b2c82017-03-06 11:45:16 -0800612 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700613 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700614 // This callback is called from the vr flinger dispatch thread. We
615 // need to call signalTransaction(), which requires holding
616 // mStateLock when we're not on the main thread. Acquiring
617 // mStateLock from the vr flinger dispatch thread might trigger a
618 // deadlock in surface flinger (see b/66916578), so post a message
619 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700620 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700621 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
622 mVrFlingerRequestsDisplay = requestDisplay;
623 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700624 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800625 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700626 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
627 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700628 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700629 .value_or(0),
630 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800631 if (!mVrFlinger) {
632 ALOGE("Failed to start vrflinger");
633 }
634 }
635
Mathias Agopian92a979a2012-08-02 18:32:23 -0700636 // initialize our drawing state
637 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700638
Andy McFadden13a082e2012-08-24 10:16:42 -0700639 // set initial conditions (e.g. unblank default device)
640 initializeDisplays();
641
Steven Thomas137d4bc2019-07-25 16:55:14 -0700642 char primeShaderCache[PROPERTY_VALUE_MAX];
643 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
644 if (atoi(primeShaderCache)) {
645 getRenderEngine().primeCache();
646 }
Dan Stoza4e637772016-07-28 13:31:51 -0700647
Wei Wangf9b05ee2017-07-19 20:59:39 -0700648 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700649
650 const bool presentFenceReliable =
651 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
652 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700653
654 if (mStartPropertySetThread->Start() != NO_ERROR) {
655 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800656 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800657
Dan Stoza9e56aa02015-11-02 13:00:03 -0800658 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700659}
660
Romain Guy11d63f42017-07-20 12:47:14 -0700661void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700662 Mutex::Autolock _l(mStateLock);
663
Romain Guy11d63f42017-07-20 12:47:14 -0700664 char value[PROPERTY_VALUE_MAX];
665
666 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800667 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700668 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800669 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100670
671 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700672 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800673
674 property_get("persist.sys.sf.color_mode", value, "0");
675 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700676}
677
Mathias Agopiana67e4182012-06-19 17:26:12 -0700678void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800679 // Start boot animation service by setting a property mailbox
680 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700681 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800682 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700683 if (mStartPropertySetThread->join() != NO_ERROR) {
684 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800685 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700686}
687
Mathias Agopian875d8e12013-06-07 15:35:48 -0700688size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700689 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700690}
691
Mathias Agopian875d8e12013-06-07 15:35:48 -0700692size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700693 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700694}
695
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800696// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800697
Jamie Gennis582270d2011-08-17 18:19:00 -0700698bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800699 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800700 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800701 return authenticateSurfaceTextureLocked(bufferProducer);
702}
703
704bool SurfaceFlinger::authenticateSurfaceTextureLocked(
705 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800706 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800707 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800708}
709
Brian Anderson6b376712017-04-04 10:51:39 -0700710status_t SurfaceFlinger::getSupportedFrameTimestamps(
711 std::vector<FrameEvent>* outSupported) const {
712 *outSupported = {
713 FrameEvent::REQUESTED_PRESENT,
714 FrameEvent::ACQUIRE,
715 FrameEvent::LATCH,
716 FrameEvent::FIRST_REFRESH_START,
717 FrameEvent::LAST_REFRESH_START,
718 FrameEvent::GPU_COMPOSITION_DONE,
719 FrameEvent::DEQUEUE_READY,
720 FrameEvent::RELEASE,
721 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700722 ConditionalLock _l(mStateLock,
723 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700724 if (!getHwComposer().hasCapability(
725 HWC2::Capability::PresentFenceIsNotReliable)) {
726 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
727 }
728 return NO_ERROR;
729}
730
Dominik Laskowski22488f62019-03-28 09:53:04 -0700731status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
732 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700733 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700734 return BAD_VALUE;
735 }
736
Dominik Laskowski22488f62019-03-28 09:53:04 -0700737 Mutex::Autolock lock(mStateLock);
738
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800739 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700740 if (!displayId) {
741 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700742 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700743
Mathias Agopian8b736f12012-08-13 17:54:26 -0700744 // TODO: Not sure if display density should handled by SF any longer
745 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700746 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700747 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700748 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800749 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700750 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700751 }
752 return density;
753 }
754 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700755 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700756 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700757 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700758 return getDensityFromProperty("ro.sf.lcd_density"); }
759 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700760
Dan Stoza7f7da322014-05-02 15:26:25 -0700761 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700762
Dominik Laskowski075d3172018-05-24 15:50:06 -0700763 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700764 DisplayInfo info = DisplayInfo();
765
Dan Stoza9e56aa02015-11-02 13:00:03 -0800766 float xdpi = hwConfig->getDpiX();
767 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700768
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700769 info.w = hwConfig->getWidth();
770 info.h = hwConfig->getHeight();
771 // Default display viewport to display width and height
772 info.viewportW = info.w;
773 info.viewportH = info.h;
774
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800775 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700776 // The density of the device is provided by a build property
777 float density = Density::getBuildDensity() / 160.0f;
778 if (density == 0) {
779 // the build doesn't provide a density -- this is wrong!
780 // use xdpi instead
781 ALOGE("ro.sf.lcd_density must be defined as a build property");
782 density = xdpi / 160.0f;
783 }
784 if (Density::getEmuDensity()) {
785 // if "qemu.sf.lcd_density" is specified, it overrides everything
786 xdpi = ydpi = density = Density::getEmuDensity();
787 density /= 160.0f;
788 }
789 info.density = density;
790
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700791 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowski718f9602019-11-09 20:01:35 -0800792 info.orientation = display->getOrientation();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700793
794 // This is for screenrecord
795 const Rect viewport = display->getViewport();
796 if (viewport.isValid()) {
797 info.viewportW = uint32_t(viewport.getWidth());
798 info.viewportH = uint32_t(viewport.getHeight());
799 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700800 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700801 } else {
802 // TODO: where should this value come from?
803 static const int TV_DENSITY = 213;
804 info.density = TV_DENSITY / 160.0f;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700805
806 const auto display = getDisplayDeviceLocked(displayToken);
807 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700808 }
809
Dan Stoza7f7da322014-05-02 15:26:25 -0700810 info.xdpi = xdpi;
811 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800812 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham2139f732019-11-13 18:56:40 -0800813
Ady Abraham9e16a482019-12-03 17:19:41 -0800814 const auto offset = mPhaseConfiguration->getOffsetsForRefreshRate(info.fps);
Ady Abraham796beb02019-04-11 15:23:07 -0700815 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800816
Andy McFadden91b2ca82014-06-13 14:04:23 -0700817 // This is how far in advance a buffer must be queued for
818 // presentation at a given time. If you want a buffer to appear
819 // on the screen at time N, you must submit the buffer before
820 // (N - presentationDeadline).
821 //
822 // Normally it's one full refresh period (to give SF a chance to
823 // latch the buffer), but this can be reduced by configuring a
824 // DispSync offset. Any additional delays introduced by the hardware
825 // composer or panel must be accounted for here.
826 //
827 // We add an additional 1ms to allow for processing time and
828 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700829 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700830
831 // All non-virtual displays are currently considered secure.
832 info.secure = true;
833
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800834 if (displayId == getInternalDisplayIdLocked() &&
Dominik Laskowski718f9602019-11-09 20:01:35 -0800835 (internalDisplayOrientation == ui::ROTATION_90 ||
836 internalDisplayOrientation == ui::ROTATION_270)) {
Iris Chang7501ed62018-04-30 14:45:42 +0800837 std::swap(info.w, info.h);
838 }
839
Michael Wright28f24d02016-07-12 13:30:53 -0700840 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700841 }
842
Dan Stoza7f7da322014-05-02 15:26:25 -0700843 return NO_ERROR;
844}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700845
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700846status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
847 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700848 return BAD_VALUE;
849 }
850
Ana Krulecc2870422019-01-29 19:00:58 -0800851 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700852 return NO_ERROR;
853}
854
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700855int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
856 const auto display = getDisplayDevice(displayToken);
857 if (!display) {
858 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800859 return BAD_VALUE;
860 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700861
Steven Thomasc9098452019-09-30 17:15:05 -0700862 if (display->isPrimary()) {
863 std::lock_guard<std::mutex> lock(mActiveConfigLock);
864 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800865 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700866 }
Steven Thomasc9098452019-09-30 17:15:05 -0700867 }
Ady Abraham2139f732019-11-13 18:56:40 -0800868
869 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700870}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700871
Ady Abraham03b02dd2019-03-21 15:40:11 -0700872void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800873 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800874 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
875 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800876
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800877 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800878 // config twice. However event generation config might have changed so we need to update it
879 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800880 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700881 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
882 mDesiredActiveConfig = info;
883 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800884
885 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800886 // This will trigger HWC refresh without resetting the idle timer.
887 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700888 // Start receiving vsync samples now, so that we can detect a period
889 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800890 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700891 // As we called to set period, we will call to onRefreshRateChangeCompleted once
892 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700893 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800894
Ady Abraham9e16a482019-12-03 17:19:41 -0800895 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
896 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800897 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800898 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700899
900 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800901 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700902 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800903}
904
905status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
906 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800907
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100908 if (!displayToken) {
909 return BAD_VALUE;
910 }
Ady Abraham838de062019-02-04 10:24:03 -0800911
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100912 status_t result = NO_ERROR;
913
914 postMessageSync(new LambdaMessage([&]() {
915 const auto display = getDisplayDeviceLocked(displayToken);
916 if (!display) {
917 ALOGE("Attempt to set allowed display configs for invalid display token %p",
918 displayToken.get());
919 result = BAD_VALUE;
920 } else if (display->isVirtual()) {
921 ALOGW("Attempt to set allowed display configs for virtual display");
922 result = BAD_VALUE;
923 } else {
924 HwcConfigIndexType config(mode);
925 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
926 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
927 refreshRate.fps);
928 }
929 }));
930
931 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800932}
933
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800934void SurfaceFlinger::setActiveConfigInternal() {
935 ATRACE_CALL();
936
Dominik Laskowski22488f62019-03-28 09:53:04 -0700937 const auto display = getDefaultDisplayDeviceLocked();
938 if (!display) {
939 return;
940 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800941
Dominik Laskowski22488f62019-03-28 09:53:04 -0700942 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800943 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700944 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800945 display->setActiveConfig(mUpcomingActiveConfig.configId);
946
Ady Abraham2139f732019-11-13 18:56:40 -0800947 auto refreshRate =
948 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800949 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
950 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800951 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700952
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800953 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700954 const nsecs_t vsyncPeriod =
955 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
956 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800957 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700958 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800959 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800960}
961
Ady Abraham53852a52019-05-28 18:07:44 -0700962void SurfaceFlinger::desiredActiveConfigChangeDone() {
963 std::lock_guard<std::mutex> lock(mActiveConfigLock);
964 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
965 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700966
Kevin DuBois5988f482020-01-17 09:03:32 -0800967 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -0800968 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -0800969 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -0800970 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
971 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700972}
973
Dominik Laskowski22488f62019-03-28 09:53:04 -0700974bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800975 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800976 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -0800977 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700978 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800979 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700980 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800981 return true;
982 }
983
984 // We received the present fence from the HWC, so we assume it successfully updated
985 // the config, hence we update SF.
986 mCheckPendingFence = false;
987 setActiveConfigInternal();
988 }
989
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800990 // Store the local variable to release the lock.
991 ActiveConfigInfo desiredActiveConfig;
992 {
993 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800994 if (!mDesiredActiveConfigChanged) {
995 return false;
996 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800997 desiredActiveConfig = mDesiredActiveConfig;
998 }
999
Ady Abraham2139f732019-11-13 18:56:40 -08001000 auto refreshRate =
1001 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1002 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1003 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001004 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001005 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1006 // display is not valid or we are already in the requested mode
1007 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001008 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001009 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001010 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011
Ady Abraham838de062019-02-04 10:24:03 -08001012 // Desired active config was set, it is different than the config currently in use, however
1013 // allowed configs might have change by the time we process the refresh.
1014 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001015 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001016 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001017 return false;
1018 }
Alec Mouri7f015182019-07-11 13:56:22 -07001019
Ady Abrahamb838aed2019-02-12 15:30:16 -08001020 mUpcomingActiveConfig = desiredActiveConfig;
1021 const auto displayId = display->getId();
1022 LOG_ALWAYS_FATAL_IF(!displayId);
1023
Ady Abraham2139f732019-11-13 18:56:40 -08001024 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001025
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001026 // TODO(b/142753666) use constrains
1027 HWC2::VsyncPeriodChangeConstraints constraints;
1028 constraints.desiredTimeNanos = systemTime();
1029 constraints.seamlessRequired = false;
1030
1031 HWC2::VsyncPeriodChangeTimeline outTimeline;
1032 auto status =
1033 getHwComposer().setActiveConfigWithConstraints(*displayId,
1034 mUpcomingActiveConfig.configId.value(),
1035 constraints, &outTimeline);
1036 if (status != NO_ERROR) {
1037 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1038 return false;
1039 }
1040
1041 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1042 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001043 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001044 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001045}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001046
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001047status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1048 Vector<ColorMode>* outColorModes) {
1049 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001050 return BAD_VALUE;
1051 }
1052
Peiyong Lina52f0292018-03-14 17:26:31 -07001053 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001054 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001055 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001056 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1057
1058 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1059 if (!displayId) {
1060 return NAME_NOT_FOUND;
1061 }
1062
Dominik Laskowski075d3172018-05-24 15:50:06 -07001063 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001064 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001065 }
Michael Wright28f24d02016-07-12 13:30:53 -07001066 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001067
1068 // If it's built-in display and the configuration claims it's not wide color capable,
1069 // filter out all wide color modes. The typical reason why this happens is that the
1070 // hardware is not good enough to support GPU composition of wide color, and thus the
1071 // OEMs choose to disable this capability.
1072 if (isInternalDisplay && !hasWideColorDisplay) {
1073 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1074 isWideColorMode);
1075 } else {
1076 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1077 }
Michael Wright28f24d02016-07-12 13:30:53 -07001078
1079 return NO_ERROR;
1080}
1081
Daniel Solomon42d04562019-01-20 21:03:19 -08001082status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1083 ui::DisplayPrimaries &primaries) {
1084 if (!displayToken) {
1085 return BAD_VALUE;
1086 }
1087
1088 // Currently we only support this API for a single internal display.
1089 if (getInternalDisplayToken() != displayToken) {
1090 return BAD_VALUE;
1091 }
1092
1093 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1094 return NO_ERROR;
1095}
1096
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001097ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1098 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001099 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001100 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001101 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001102}
1103
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001105 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001106 Vector<ColorMode> modes;
1107 getDisplayColorModes(displayToken, &modes);
1108 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1109 if (mode < ColorMode::NATIVE || !exists) {
1110 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1111 decodeColorMode(mode).c_str(), mode, displayToken.get());
1112 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001113 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001114 const auto display = getDisplayDevice(displayToken);
1115 if (!display) {
1116 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1117 decodeColorMode(mode).c_str(), mode, displayToken.get());
1118 } else if (display->isVirtual()) {
1119 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1120 decodeColorMode(mode).c_str(), mode);
1121 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001122 display->getCompositionDisplay()->setColorProfile(
1123 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1124 RenderIntent::COLORIMETRIC,
1125 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001126 }
1127 }));
1128
Michael Wright28f24d02016-07-12 13:30:53 -07001129 return NO_ERROR;
1130}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001131
Galia Peycheva5492cb52019-10-30 14:13:16 +01001132status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1133 bool* outSupport) const {
1134 Mutex::Autolock _l(mStateLock);
1135
1136 if (!displayToken) {
1137 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1138 return BAD_VALUE;
1139 }
1140 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1141 if (!displayId) {
1142 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1143 displayToken.get());
1144 return NAME_NOT_FOUND;
1145 }
1146 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1147 HWC2::DisplayCapability::AutoLowLatencyMode);
1148 return NO_ERROR;
1149}
1150
1151void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1152 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1153}
1154
1155void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1156 if (!displayToken) {
1157 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1158 return;
1159 }
1160 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1161 if (!displayId) {
1162 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1163 displayToken.get());
1164 return;
1165 }
1166
1167 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1168}
1169
1170status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1171 bool* outSupport) const {
1172 Mutex::Autolock _l(mStateLock);
1173
1174 if (!displayToken) {
1175 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1176 return BAD_VALUE;
1177 }
1178 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1179 if (!displayId) {
1180 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1181 displayToken.get());
1182 return NAME_NOT_FOUND;
1183 }
1184
1185 std::vector<HWC2::ContentType> outSupportedContentTypes;
1186 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1187 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1188 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1189 return NO_ERROR;
1190}
1191
1192void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1193 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1194}
1195
1196void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1197 if (!displayToken) {
1198 ALOGE("setGameContentType() failed. Missing display token.");
1199 return;
1200 }
1201 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1202 if (!displayId) {
1203 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1204 displayToken.get());
1205 return;
1206 }
1207
1208 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1209 getHwComposer().setContentType(*displayId, type);
1210}
1211
Svetoslavd85084b2014-03-20 10:28:31 -07001212status_t SurfaceFlinger::clearAnimationFrameStats() {
1213 Mutex::Autolock _l(mStateLock);
1214 mAnimFrameTracker.clearStats();
1215 return NO_ERROR;
1216}
1217
1218status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1219 Mutex::Autolock _l(mStateLock);
1220 mAnimFrameTracker.getStats(outStats);
1221 return NO_ERROR;
1222}
1223
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001224status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1225 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001226 Mutex::Autolock _l(mStateLock);
1227
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001228 const auto display = getDisplayDeviceLocked(displayToken);
1229 if (!display) {
1230 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001231 return BAD_VALUE;
1232 }
1233
Peiyong Linfb069302018-04-25 14:34:31 -07001234 // At this point the DisplayDeivce should already be set up,
1235 // meaning the luminance information is already queried from
1236 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001237 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001238 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1239 capabilities.getDesiredMaxLuminance(),
1240 capabilities.getDesiredMaxAverageLuminance(),
1241 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001242
1243 return NO_ERROR;
1244}
1245
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001246status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1247 ui::PixelFormat* outFormat,
1248 ui::Dataspace* outDataspace,
1249 uint8_t* outComponentMask) const {
1250 if (!outFormat || !outDataspace || !outComponentMask) {
1251 return BAD_VALUE;
1252 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001253 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001254 if (!display || !display->getId()) {
1255 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1256 return BAD_VALUE;
1257 }
1258 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1259 outDataspace, outComponentMask);
1260}
1261
Kevin DuBois74e53772018-11-19 10:52:38 -08001262status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1263 bool enable, uint8_t componentMask,
1264 uint64_t maxFrames) const {
1265 const auto display = getDisplayDevice(displayToken);
1266 if (!display || !display->getId()) {
1267 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1268 return BAD_VALUE;
1269 }
1270
1271 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1272 componentMask, maxFrames);
1273}
1274
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001275status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1276 uint64_t maxFrames, uint64_t timestamp,
1277 DisplayedFrameStats* outStats) const {
1278 const auto display = getDisplayDevice(displayToken);
1279 if (!display || !display->getId()) {
1280 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1281 return BAD_VALUE;
1282 }
1283
1284 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1285 outStats);
1286}
1287
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001288status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1289 if (!outSupported) {
1290 return BAD_VALUE;
1291 }
1292 *outSupported = getRenderEngine().supportsProtectedContent();
1293 return NO_ERROR;
1294}
1295
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001296status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1297 bool* outIsWideColorDisplay) const {
1298 if (!displayToken || !outIsWideColorDisplay) {
1299 return BAD_VALUE;
1300 }
1301 Mutex::Autolock _l(mStateLock);
1302 const auto display = getDisplayDeviceLocked(displayToken);
1303 if (!display) {
1304 return BAD_VALUE;
1305 }
Peiyong Linff84a152019-05-17 18:36:19 -07001306
1307 // Use hasWideColorDisplay to override built-in display.
1308 const auto displayId = display->getId();
1309 if (displayId && displayId == getInternalDisplayIdLocked()) {
1310 *outIsWideColorDisplay = hasWideColorDisplay;
1311 return NO_ERROR;
1312 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001313 *outIsWideColorDisplay = display->hasWideColorGamut();
1314 return NO_ERROR;
1315}
1316
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001317status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001318 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001319 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001320
Dominik Laskowski6505f792019-09-18 11:10:05 -07001321 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1322 mEventQueue->setEventConnection(
1323 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001324 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001325 }));
1326
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001327 return NO_ERROR;
1328}
1329
1330status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001331 Mutex::Autolock lock(mStateLock);
1332 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001333}
1334
Lloyd Pique755e3192018-01-31 16:46:15 -08001335status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1336 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001337 // Try to acquire a lock for 1s, fail gracefully
1338 const status_t err = mStateLock.timedLock(s2ns(1));
1339 const bool locked = (err == NO_ERROR);
1340 if (!locked) {
1341 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1342 return TIMED_OUT;
1343 }
1344
1345 outLayers->clear();
1346 mCurrentState.traverseInZOrder([&](Layer* layer) {
1347 outLayers->push_back(layer->getLayerDebugInfo());
1348 });
1349
1350 mStateLock.unlock();
1351 return NO_ERROR;
1352}
1353
Peiyong Linc6780972018-10-28 15:24:08 -07001354status_t SurfaceFlinger::getCompositionPreference(
1355 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1356 Dataspace* outWideColorGamutDataspace,
1357 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001358 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001359 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001360 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001361 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001362 return NO_ERROR;
1363}
1364
Dan Stozaec460082018-12-17 15:35:09 -08001365status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1366 const sp<IBinder>& stopLayerHandle,
1367 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001368 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001369 return BAD_VALUE;
1370 }
1371 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001372 return NO_ERROR;
1373}
1374
Dan Stozaec460082018-12-17 15:35:09 -08001375status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001376 if (!listener) {
1377 return BAD_VALUE;
1378 }
Dan Stozaec460082018-12-17 15:35:09 -08001379 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001380 return NO_ERROR;
1381}
Dan Gittik57e63c52019-01-18 16:37:54 +00001382
1383status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1384 bool* outSupport) const {
1385 if (!displayToken || !outSupport) {
1386 return BAD_VALUE;
1387 }
1388 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1389 if (!displayId) {
1390 return NAME_NOT_FOUND;
1391 }
1392 *outSupport =
1393 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1394 return NO_ERROR;
1395}
1396
1397status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1398 float brightness) const {
1399 if (!displayToken) {
1400 return BAD_VALUE;
1401 }
1402 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1403 if (!displayId) {
1404 return NAME_NOT_FOUND;
1405 }
1406 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1407}
1408
Ady Abraham8532d012019-05-08 14:50:56 -07001409status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1410 PowerHint powerHint = static_cast<PowerHint>(hintId);
1411
1412 if (powerHint == PowerHint::INTERACTION) {
1413 mScheduler->notifyTouchEvent();
1414 }
1415
1416 return NO_ERROR;
1417}
1418
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001419// ----------------------------------------------------------------------------
1420
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001421sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001422 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001423 const auto& handle =
1424 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001425
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001426 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001427}
1428
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001429// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001430
1431void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001432 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001433}
1434
1435void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001436 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001437 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001438}
1439
1440void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001441 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001442 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001443}
1444
1445void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001446 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001447 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001448}
1449
1450status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001451 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001452 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001453}
1454
1455status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001456 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001457 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001458 if (res == NO_ERROR) {
1459 msg->wait();
1460 }
1461 return res;
1462}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001463
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001464void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001465 do {
1466 waitForEvent();
1467 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001468}
1469
Dominik Laskowski83b88212018-12-11 13:34:06 -08001470nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001471 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001472 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1473 return 0;
1474 }
1475
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001476 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001477}
1478
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001479void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001480 int64_t timestamp,
1481 std::optional<hwc2_vsync_period_t> /*vsyncPeriod*/) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001482 ATRACE_NAME("SF onVsync");
1483
Ady Abraham7159f572019-10-11 11:10:18 -07001484 // TODO(b/140201379): use vsyncPeriod in the new DispSync
1485
Steven Thomas3cfac282017-02-06 12:29:30 -08001486 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001487 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001488 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001489 return;
1490 }
1491
Dominik Laskowski075d3172018-05-24 15:50:06 -07001492 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001493 return;
1494 }
1495
Dominik Laskowski075d3172018-05-24 15:50:06 -07001496 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001497 // For now, we don't do anything with external display vsyncs.
1498 return;
1499 }
1500
Alec Mourif8e689c2019-05-20 18:32:22 -07001501 bool periodFlushed = false;
1502 mScheduler->addResyncSample(timestamp, &periodFlushed);
1503 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001504 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001505 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001506}
1507
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001508void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001509 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1510 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001511}
1512
Ady Abraham2139f732019-11-13 18:56:40 -08001513bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001514 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001515}
1516
Ady Abraham2139f732019-11-13 18:56:40 -08001517void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1518 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001519 const auto display = getDefaultDisplayDeviceLocked();
1520 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001521 return;
1522 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001523 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001524
Ana Krulec7d1d6832018-12-27 11:10:09 -08001525 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001526 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1527 ALOGV("Skipping config %d as it is not part of allowed configs",
1528 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001529 return;
1530 }
1531
Ady Abraham2139f732019-11-13 18:56:40 -08001532 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001533}
1534
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001535void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001536 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001537 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001538 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001539
Lloyd Piqueba04e622017-12-14 17:11:26 -08001540 // Ignore events that do not have the right sequenceId.
1541 if (sequenceId != getBE().mComposerSequenceId) {
1542 return;
1543 }
1544
Steven Thomasb02664d2017-07-26 18:48:28 -07001545 // Only lock if we're not on the main thread. This function is normally
1546 // called on a hwbinder thread, but for the primary display it's called on
1547 // the main thread with the state lock already held, so don't attempt to
1548 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001549 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001550
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001551 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001552
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001553 if (std::this_thread::get_id() == mMainThreadId) {
1554 // Process all pending hot plug events immediately if we are on the main thread.
1555 processDisplayHotplugEventsLocked();
1556 }
1557
Lloyd Piqueba04e622017-12-14 17:11:26 -08001558 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001559}
1560
Ady Abraham7159f572019-10-11 11:10:18 -07001561void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001562 int32_t sequenceId, hwc2_display_t /*display*/,
1563 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1564 Mutex::Autolock lock(mStateLock);
1565 if (sequenceId != getBE().mComposerSequenceId) {
1566 return;
1567 }
1568 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001569}
1570
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001571void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1572 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1573 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1574}
1575
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001576void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001577 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001578 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001579 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001580 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001581 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001582}
1583
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001584void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001585 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001586
1587 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1588 // display power state.
1589 postMessageAsync(new LambdaMessage(
1590 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1591}
1592
1593void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1594 ATRACE_CALL();
1595
Ady Abraham27c70212019-06-11 10:52:26 -07001596 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1597
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001598 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001599 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1600 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001601 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001602 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001603 }
Mathias Agopian86303202012-07-24 22:46:10 -07001604}
1605
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001606// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001607void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001608 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001609 // Clear the drawing state so that the logic inside of
1610 // handleTransactionLocked will fire. It will determine the delta between
1611 // mCurrentState and mDrawingState and re-apply all changes when we make the
1612 // transition.
1613 mDrawingState.displays.clear();
1614 mDisplays.clear();
1615}
1616
Steven Thomas050b2c82017-03-06 11:45:16 -08001617void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001618 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001619 if (!mVrFlinger)
1620 return;
1621 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001622 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001623 return;
1624 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001625
Lloyd Pique441d5042018-10-18 16:49:51 -07001626 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001627 ALOGE("Vr flinger is only supported for remote hardware composer"
1628 " service connections. Ignoring request to transition to vr"
1629 " flinger.");
1630 mVrFlingerRequestsDisplay = false;
1631 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001632 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001633
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001634 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001635
Steven Thomas0123ac62018-07-12 11:32:34 -07001636 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001637 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001638
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001639 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001640
1641 // Clear out all the output layers from the composition engine for all
1642 // displays before destroying the hardware composer interface. This ensures
1643 // any HWC layers are destroyed through that interface before it becomes
1644 // invalid.
1645 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001646 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001647 }
1648
Steven Thomas0123ac62018-07-12 11:32:34 -07001649 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1650 // called below. Clear the reference now so we don't accidentally use it
1651 // later.
1652 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001653
Steven Thomasb02664d2017-07-26 18:48:28 -07001654 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001655 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001656 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001657
Steven Thomasb02664d2017-07-26 18:48:28 -07001658 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001659 // Delete the current instance before creating the new one
1660 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1661 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1662 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1663 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001664
Lloyd Pique441d5042018-10-18 16:49:51 -07001665 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001666 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001667
1668 if (vrFlingerRequestsDisplay) {
1669 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001670 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001671
1672 mVisibleRegionsDirty = true;
1673 invalidateHwcGeometry();
1674
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001675 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001676 display = getDefaultDisplayDeviceLocked();
1677 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001678 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001679
Steven Thomasb02664d2017-07-26 18:48:28 -07001680 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001681 const nsecs_t vsyncPeriod = getVsyncPeriod();
1682 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001683
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001684 // The present fences returned from vr_hwc are not an accurate
1685 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001686 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001687
Steven Thomasb02664d2017-07-26 18:48:28 -07001688 // Use phase of 0 since phase is not known.
1689 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001690 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001691 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001692
Ana Krulecc2870422019-01-29 19:00:58 -08001693 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001694
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001695 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001696 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001697}
1698
Ady Abraham11579302019-09-19 12:35:58 -07001699bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1700 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001701 // We are storing the last 2 present fences. If sf's phase offset is to be
1702 // woken up before the actual vsync but targeting the next vsync, we need to check
1703 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001704 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1705 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001706
Ady Abraham11579302019-09-19 12:35:58 -07001707 if (fence == Fence::NO_FENCE) {
1708 return false;
1709 }
1710
1711 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1712 fence->wait(graceTimeMs);
1713 }
1714
1715 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001716}
1717
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001718void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001719 DisplayStatInfo stats;
1720 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001721 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001722 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001723 mExpectedPresentTime.store(
1724 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001725}
1726
Dominik Laskowski22488f62019-03-28 09:53:04 -07001727void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001728 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001729 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001730 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001731 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001732 // calculate the expected present time once and use the cached
1733 // value throughout this frame to make sure all layers are
1734 // seeing this same value.
1735 populateExpectedPresentTime();
1736
Ady Abraham11579302019-09-19 12:35:58 -07001737 // When Backpressure propagation is enabled we want to give a small grace period
1738 // for the present fence to fire instead of just giving up on this frame to handle cases
1739 // where present fence is just about to get signaled.
1740 const int graceTimeForPresentFenceMs =
1741 (mPropagateBackpressure &&
1742 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1743 ? 1
1744 : 0;
1745 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1746 previousFrameMissed(
1747 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001748 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1749 mHadDeviceComposition && frameMissed};
1750 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1751 mHadClientComposition && frameMissed};
1752
Alec Mouricc0fc602019-02-26 21:45:19 -08001753 if (frameMissed) {
1754 mFrameMissedCount++;
1755 mTimeStats->incrementMissedFrames();
1756 }
1757
Alec Mouri40189b02019-03-05 15:07:54 -08001758 if (hwcFrameMissed) {
1759 mHwcFrameMissedCount++;
1760 }
1761
1762 if (gpuFrameMissed) {
1763 mGpuFrameMissedCount++;
1764 }
1765
Ady Abrahamadb9a992019-09-19 21:21:55 +00001766 if (frameMissed && mPropagateBackpressure) {
1767 if ((hwcFrameMissed && !gpuFrameMissed) ||
1768 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001769 signalLayerUpdate();
1770 break;
1771 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001772 }
Dan Stoza50182882016-07-08 12:02:20 -07001773
Steven Thomas050b2c82017-03-06 11:45:16 -08001774 // Now that we're going to make it to the handleMessageTransaction()
1775 // call below it's safe to call updateVrFlinger(), which will
1776 // potentially trigger a display handoff.
1777 updateVrFlinger();
1778
Dan Stoza6b9454d2014-11-07 16:00:59 -08001779 bool refreshNeeded = handleMessageTransaction();
1780 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001781
Ana Krulecc84d09b2019-11-02 23:10:29 +01001782 // Layers need to get updated (in the previous line) before we can use them for
1783 // choosing the refresh rate.
Ady Abraham8a82ba62020-01-17 12:43:17 -08001784 // Hold mStateLock as chooseRefreshRateForContent promotes wp<Layer> to sp<Layer>
1785 // and may eventually call to ~Layer() if it holds the last reference
1786 {
1787 Mutex::Autolock _l(mStateLock);
1788 mScheduler->chooseRefreshRateForContent();
1789 }
1790
Ana Krulecc84d09b2019-11-02 23:10:29 +01001791 if (performSetActiveConfig()) {
1792 break;
1793 }
1794
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001795 updateCursorAsync();
1796 updateInputFlinger();
1797
Dan Stoza58784442014-12-02 16:58:17 -08001798 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001799 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001800 // Signal a refresh if a transaction modified the window state,
1801 // a new buffer was latched, or if HWC has requested a full
1802 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001803 if (mFrameStartTime <= 0) {
1804 // We should only use the time of the first invalidate
1805 // message that signals a refresh as the beginning of the
1806 // frame. Otherwise the real frame time will be
1807 // underestimated.
1808 mFrameStartTime = frameStart;
1809 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001810 signalRefresh();
1811 }
1812 break;
1813 }
1814 case MessageQueue::REFRESH: {
1815 handleMessageRefresh();
1816 break;
1817 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001818 }
1819}
1820
Dan Stoza6b9454d2014-11-07 16:00:59 -08001821bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001822 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001823 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001824
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001825 bool flushedATransaction = flushTransactionQueues();
1826
1827 bool runHandleTransaction = transactionFlags &&
1828 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1829
1830 if (runHandleTransaction) {
1831 handleTransaction(eTransactionMask);
1832 } else {
1833 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001834 }
1835
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001836 if (transactionFlushNeeded()) {
1837 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001838 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001839
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001840 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001841}
1842
Mathias Agopian4fec8732012-06-29 14:12:52 -07001843void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001844 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001845
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001846 mRefreshPending = false;
1847
Lloyd Piqueab039b52019-02-13 14:22:42 -08001848 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001849 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001850 for (const auto& [_, display] : mDisplays) {
1851 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1852 }
1853 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1854 auto compositionLayer = layer->getCompositionLayer();
1855 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1856 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001857 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1858 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1859 auto compositionLayer = layer->getCompositionLayer();
Adithya Srinivasan87c1b80e2019-11-21 11:43:06 -08001860 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001861 }
1862
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001863 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001864 refreshArgs.outputColorSetting = useColorManagement
1865 ? mDisplayColorSetting
1866 : compositionengine::OutputColorSetting::kUnmanaged;
1867 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1868 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001869
1870 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1871 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001872
1873 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1874 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1875 mDrawingState.colorMatrixChanged = false;
1876 }
1877
1878 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1879
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001880 if (mDebugRegion != 0) {
1881 refreshArgs.devOptFlashDirtyRegionsDelay =
1882 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1883 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001884
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001885 mGeometryInvalid = false;
1886
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001887 // Store the present time just before calling to the composition engine so we could notify
1888 // the scheduler.
1889 const auto presentTime = systemTime();
1890
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001891 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001892 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1893 // Reset the frame start time now that we've recorded this frame.
1894 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001895
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001896 mScheduler->onDisplayRefreshed(presentTime);
1897
David Sodmanfa9b2af2017-12-24 13:28:59 -08001898 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001899 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001900
Lloyd Pique66d68602019-02-13 14:23:31 -08001901 mHadClientComposition =
1902 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1903 auto& displayDevice = tokenDisplayPair.second;
Vishnu Nair9b079a22020-01-21 14:36:08 -08001904 return displayDevice->getCompositionDisplay()->getState().usesClientComposition &&
1905 !displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
Lloyd Pique66d68602019-02-13 14:23:31 -08001906 });
1907 mHadDeviceComposition =
1908 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1909 auto& displayDevice = tokenDisplayPair.second;
1910 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1911 });
Vishnu Nair9b079a22020-01-21 14:36:08 -08001912 mReusedClientComposition =
1913 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1914 auto& displayDevice = tokenDisplayPair.second;
1915 return displayDevice->getCompositionDisplay()->getState().reusedClientComposition;
1916 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001917
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001918 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001919
David Sodman7e4ae112018-02-09 15:02:28 -08001920 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001921 if (mVisibleRegionsDirty) {
1922 mVisibleRegionsDirty = false;
1923 if (mTracingEnabled) {
1924 mTracing.notify("visibleRegionsDirty");
1925 }
1926 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001927
1928 if (mCompositionEngine->needsAnotherUpdate()) {
1929 signalLayerUpdate();
1930 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001931}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001932
David Sodmanfa9b2af2017-12-24 13:28:59 -08001933
1934bool SurfaceFlinger::handleMessageInvalidate() {
1935 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001936 bool refreshNeeded = handlePageFlip();
1937
Vishnu Nair4351ad52019-02-11 14:13:02 -08001938 if (mVisibleRegionsDirty) {
1939 computeLayerBounds();
1940 }
1941
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001942 for (auto& layer : mLayersPendingRefresh) {
1943 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001944 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001945 invalidateLayerStack(layer, visibleReg);
1946 }
1947 mLayersPendingRefresh.clear();
1948 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001949}
1950
Ana Krulece588e312018-09-18 12:32:24 -07001951void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1952 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001953 // Update queue of past composite+present times and determine the
1954 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001955 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001956 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001957 while (!getBE().mCompositePresentTimes.empty()) {
1958 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001959 // Cached values should have been updated before calling this method,
1960 // which helps avoid duplicate syscalls.
1961 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1962 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1963 break;
1964 }
1965 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001966 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001967 }
1968
1969 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001970 while (getBE().mCompositePresentTimes.size() > 16) {
1971 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001972 }
1973
Ana Krulece588e312018-09-18 12:32:24 -07001974 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001975}
1976
Ana Krulece588e312018-09-18 12:32:24 -07001977void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1978 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001979 // Integer division and modulo round toward 0 not -inf, so we need to
1980 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08001981 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
1982 ? (stats.vsyncPeriod -
1983 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
1984 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001985
Ady Abraham9e16a482019-12-03 17:19:41 -08001986 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001987 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001988 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001989 }
1990
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001991 // Snap the latency to a value that removes scheduling jitter from the
1992 // composition and present times, which often have >1ms of jitter.
1993 // Reducing jitter is important if an app attempts to extrapolate
1994 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08001995 // Snapping also allows an app to precisely calculate
1996 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001997 nsecs_t bias = stats.vsyncPeriod / 2;
1998 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1999 nsecs_t snappedCompositeToPresentLatency =
2000 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002001
David Sodman99974d22017-11-28 12:04:33 -08002002 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07002003 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
2004 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08002005 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002006}
2007
David Sodman2b406362017-12-15 13:33:47 -08002008void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07002009{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002010 ATRACE_CALL();
2011 ALOGV("postComposition");
2012
Brian Anderson3546a3f2016-07-14 11:51:14 -07002013 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002014 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002015 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002016 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002017 }
2018
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002019 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002020 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002021
David Sodman73beded2017-11-15 11:56:06 -08002022 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002023 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002024 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002025 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002026 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2027 ->getRenderSurface()
2028 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002029 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002030 } else {
2031 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2032 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002033
David Sodman73beded2017-11-15 11:56:06 -08002034 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002035 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2036 mPreviousPresentFences[0] = displayDevice
2037 ? getHwComposer().getPresentFence(*displayDevice->getId())
2038 : Fence::NO_FENCE;
2039 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002040 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002041
Ana Krulece588e312018-09-18 12:32:24 -07002042 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002043 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002044
Lloyd Piqueab039b52019-02-13 14:22:42 -08002045 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2046 // be sampled a little later than when we started doing work for this frame,
2047 // but that should be okay since updateCompositorTiming has snapping logic.
2048 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2049 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002050 CompositorTiming compositorTiming;
2051 {
David Sodman99974d22017-11-28 12:04:33 -08002052 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2053 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002054 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002055
Edgar Arriaga844fa672020-01-16 14:21:42 -08002056 mDrawingState.traverse([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002057 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2058 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002059 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002060 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002061 }
Robert Carr2047fae2016-11-28 14:09:09 -08002062 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002063
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002064 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002065 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002066 }
2067
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002068 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002069 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2070 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002071 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002072 }
2073 }
2074
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002075 if (mAnimCompositionPending) {
2076 mAnimCompositionPending = false;
2077
Brian Anderson4e606e32017-03-16 15:34:57 -07002078 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002079 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002080 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002081 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002082 // The HWC doesn't support present fences, so use the refresh
2083 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002084 const nsecs_t presentTime =
2085 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002086 mAnimFrameTracker.setActualPresentTime(presentTime);
2087 }
2088 mAnimFrameTracker.advanceFrame();
2089 }
Dan Stozab90cf072015-03-05 11:05:59 -08002090
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002091 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002092 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002093 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002094 }
2095
Vishnu Nair9b079a22020-01-21 14:36:08 -08002096 if (mReusedClientComposition) {
2097 mTimeStats->incrementClientCompositionReusedFrames();
2098 }
2099
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002100 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002101
Lloyd Pique32cbe282018-10-19 13:09:22 -07002102 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2103 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002104 return;
2105 }
2106
2107 nsecs_t currentTime = systemTime();
2108 if (mHasPoweredOff) {
2109 mHasPoweredOff = false;
2110 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002111 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002112 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002113 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2114 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002115 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002116 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002117 }
David Sodman4a36e932017-11-07 14:29:47 -08002118 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002119 }
David Sodman4a36e932017-11-07 14:29:47 -08002120 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002121
2122 {
2123 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002124 if (mTexturePool.size() < mTexturePoolSize) {
2125 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002126 const size_t offset = mTexturePool.size();
2127 mTexturePool.resize(mTexturePoolSize);
2128 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2129 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002130 } else if (mTexturePool.size() > mTexturePoolSize) {
2131 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2132 const size_t offset = mTexturePoolSize;
2133 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2134 mTexturePool.resize(mTexturePoolSize);
2135 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002136 }
2137 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002138
Ady Abrahambe0f9482019-04-24 15:41:53 -07002139 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002140 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002141
Kevin DuBois413287f2019-02-25 08:46:47 -08002142 if (mLumaSampling && mRegionSamplingThread) {
2143 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002144 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002145
2146 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2147 // side-effect of getTotalSize(), so we check that again here
2148 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002149 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002150 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2151 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002152}
2153
Vishnu Nair4351ad52019-02-11 14:13:02 -08002154void SurfaceFlinger::computeLayerBounds() {
2155 for (const auto& pair : mDisplays) {
2156 const auto& displayDevice = pair.second;
2157 const auto display = displayDevice->getCompositionDisplay();
2158 for (const auto& layer : mDrawingState.layersSortedByZ) {
2159 // only consider the layers on the given layer stack
2160 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002161 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002162 }
2163
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002164 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2165 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002166 }
2167 }
2168}
2169
David Sodmanfa9b2af2017-12-24 13:28:59 -08002170void SurfaceFlinger::postFrame()
2171{
2172 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002173 const auto display = getDefaultDisplayDeviceLocked();
2174 if (display && getHwComposer().isConnected(*display->getId())) {
2175 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002176 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2177 logFrameStats();
2178 }
2179 }
2180}
2181
Mathias Agopian87baae12012-07-31 12:38:26 -07002182void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002183{
Mathias Agopian841cde52012-03-01 15:44:37 -08002184 ATRACE_CALL();
2185
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002186 // here we keep a copy of the drawing state (that is the state that's
2187 // going to be overwritten by handleTransactionLocked()) outside of
2188 // mStateLock so that the side-effects of the State assignment
2189 // don't happen with mStateLock held (which can cause deadlocks).
2190 State drawingState(mDrawingState);
2191
Mathias Agopianca4d3602011-05-19 15:38:14 -07002192 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002193 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002194
Mathias Agopianca4d3602011-05-19 15:38:14 -07002195 // Here we're guaranteed that some transaction flags are set
2196 // so we can call handleTransactionLocked() unconditionally.
2197 // We call getTransactionFlags(), which will also clear the flags,
2198 // with mStateLock held to guarantee that mCurrentState won't change
2199 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002200
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002201 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002202 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002203 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002204
Mathias Agopianca4d3602011-05-19 15:38:14 -07002205 mDebugInTransaction = 0;
2206 invalidateHwcGeometry();
2207 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002208}
2209
Lloyd Piqueba04e622017-12-14 17:11:26 -08002210void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2211 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002212 const std::optional<DisplayIdentificationInfo> info =
2213 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002214
Dominik Laskowski075d3172018-05-24 15:50:06 -07002215 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002216 continue;
2217 }
2218
Lloyd Piqueba04e622017-12-14 17:11:26 -08002219 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002220 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002221 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002222 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2223 initScheduler(info->id);
2224 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002225 mPhysicalDisplayTokens[info->id] = new BBinder();
2226 DisplayDeviceState state;
2227 state.displayId = info->id;
2228 state.isSecure = true; // All physical displays are currently considered secure.
2229 state.displayName = info->name;
2230 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2231 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002232 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002233 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002234 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002235
Dominik Laskowski075d3172018-05-24 15:50:06 -07002236 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2237 if (index >= 0) {
2238 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2239 mInterceptor->saveDisplayDeletion(state.sequenceId);
2240 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002241 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002242 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002243 }
2244
2245 processDisplayChangesLocked();
2246 }
2247
2248 mPendingHotplugEvents.clear();
2249}
2250
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002251void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002252 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2253 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002254}
2255
Lloyd Pique99d3da52018-01-22 17:48:03 -08002256sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002257 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002258 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002259 const sp<IGraphicBufferProducer>& producer) {
2260 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002261 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002262 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002263 creationArgs.isSecure = state.isSecure;
2264 creationArgs.displaySurface = dispSurface;
2265 creationArgs.hasWideColorGamut = false;
2266 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002267 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002268
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002269 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002270 creationArgs.isPrimary = isInternalDisplay;
2271
2272 if (useColorManagement && displayId) {
2273 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002274 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002275 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002276 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002277 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002278
Dominik Laskowski7e045462018-05-30 13:02:02 -07002279 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002280 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002281 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002282 }
tangrobin6753a022018-08-10 10:58:54 +08002283 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002284
Dominik Laskowski075d3172018-05-24 15:50:06 -07002285 if (displayId) {
2286 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002287 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002288 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002289 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002290
Lloyd Pique90c115d2018-09-18 21:39:42 -07002291 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002292 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002293 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002294
Lloyd Pique99d3da52018-01-22 17:48:03 -08002295 // Make sure that composition can never be stalled by a virtual display
2296 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002297 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002298 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002299 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2300 }
2301
Dominik Laskowski718f9602019-11-09 20:01:35 -08002302 creationArgs.physicalOrientation =
2303 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002304
Lloyd Pique99d3da52018-01-22 17:48:03 -08002305 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002306 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002307
Lloyd Pique90c115d2018-09-18 21:39:42 -07002308 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002309
2310 if (maxFrameBufferAcquiredBuffers >= 3) {
2311 nativeWindowSurface->preallocateBuffers();
2312 }
2313
2314 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002315 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002316 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002317 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002318 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002319 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002320 display->getCompositionDisplay()->setColorProfile(
2321 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2322 RenderIntent::COLORIMETRIC,
2323 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002324 if (!state.isVirtual()) {
2325 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002326 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2327 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002328 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002329
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002330 display->setLayerStack(state.layerStack);
2331 display->setProjection(state.orientation, state.viewport, state.frame);
2332 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002333
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002334 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002335}
2336
Lloyd Pique347200f2017-12-14 17:00:15 -08002337void SurfaceFlinger::processDisplayChangesLocked() {
2338 // here we take advantage of Vector's copy-on-write semantics to
2339 // improve performance by skipping the transaction entirely when
2340 // know that the lists are identical
2341 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2342 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2343 if (!curr.isIdenticalTo(draw)) {
2344 mVisibleRegionsDirty = true;
2345 const size_t cc = curr.size();
2346 size_t dc = draw.size();
2347
2348 // find the displays that were removed
2349 // (ie: in drawing state but not in current state)
2350 // also handle displays that changed
2351 // (ie: displays that are in both lists)
2352 for (size_t i = 0; i < dc;) {
2353 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2354 if (j < 0) {
2355 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002356 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002357 // Save display ID before disconnecting.
2358 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002359 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002360
2361 if (!display->isVirtual()) {
2362 LOG_ALWAYS_FATAL_IF(!displayId);
2363 dispatchDisplayHotplugEvent(displayId->value, false);
2364 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002365 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002366
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002367 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002368 } else {
2369 // this display is in both lists. see if something changed.
2370 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002371 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002372 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2373 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2374 if (state_binder != draw_binder) {
2375 // changing the surface is like destroying and
2376 // recreating the DisplayDevice, so we just remove it
2377 // from the drawing state, so that it get re-added
2378 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002379 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002380 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002381 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002382 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002383 mDrawingState.displays.removeItemsAt(i);
2384 dc--;
2385 // at this point we must loop to the next item
2386 continue;
2387 }
2388
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002389 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002390 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002391 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002392 }
2393 if ((state.orientation != draw[i].orientation) ||
2394 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002395 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002396 }
2397 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002398 display->setDisplaySize(state.width, state.height);
Ady Abraham8a82ba62020-01-17 12:43:17 -08002399 if (display->isPrimary()) {
2400 mScheduler->onPrimaryDisplayAreaChanged(state.width * state.height);
2401 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002402 }
2403 }
2404 }
2405 ++i;
2406 }
2407
2408 // find displays that were added
2409 // (ie: in current state but not in drawing state)
2410 for (size_t i = 0; i < cc; i++) {
2411 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2412 const DisplayDeviceState& state(curr[i]);
2413
Lloyd Pique542307f2018-10-19 13:24:08 -07002414 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002415 sp<IGraphicBufferProducer> producer;
2416 sp<IGraphicBufferProducer> bqProducer;
2417 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002418 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002419
Dominik Laskowski075d3172018-05-24 15:50:06 -07002420 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002421 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002422 // Virtual displays without a surface are dormant:
2423 // they have external state (layer stack, projection,
2424 // etc.) but no internal state (i.e. a DisplayDevice).
2425 if (state.surface != nullptr) {
2426 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002427 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002428 int width = 0;
2429 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2430 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2431 int height = 0;
2432 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2433 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2434 int intFormat = 0;
2435 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2436 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002437 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002438
Dominik Laskowski075d3172018-05-24 15:50:06 -07002439 displayId =
2440 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002441 }
2442
2443 // TODO: Plumb requested format back up to consumer
2444
2445 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002446 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002447 bqProducer, bqConsumer,
2448 state.displayName);
2449
2450 dispSurface = vds;
2451 producer = vds;
2452 }
2453 } else {
2454 ALOGE_IF(state.surface != nullptr,
2455 "adding a supported display, but rendering "
2456 "surface is provided (%p), ignoring it",
2457 state.surface.get());
2458
Dominik Laskowski075d3172018-05-24 15:50:06 -07002459 displayId = state.displayId;
2460 LOG_ALWAYS_FATAL_IF(!displayId);
2461 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002462 producer = bqProducer;
2463 }
2464
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002465 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002466 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002467 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002468 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002469 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002470 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002471 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002472 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002473 }
Ady Abraham8a82ba62020-01-17 12:43:17 -08002474
2475 const auto displayDevice = mDisplays[displayToken];
2476 if (displayDevice->isPrimary()) {
2477 mScheduler->onPrimaryDisplayAreaChanged(displayDevice->getWidth() *
2478 displayDevice->getHeight());
2479 }
Lloyd Pique347200f2017-12-14 17:00:15 -08002480 }
2481 }
2482 }
2483 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002484
2485 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002486}
2487
Mathias Agopian87baae12012-07-31 12:38:26 -07002488void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002489{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002490 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2491
Dan Stoza7dde5992015-05-22 09:51:44 -07002492 // Notify all layers of available frames
Edgar Arriaga844fa672020-01-16 14:21:42 -08002493 mCurrentState.traverse([expectedPresentTime](Layer* layer) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002494 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002495 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002496
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002497 /*
2498 * Traversal of the children
2499 * (perform the transaction for each of them if needed)
2500 */
2501
Marissa Wall06255332019-03-27 13:48:27 -07002502 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002503 mCurrentState.traverse([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002504 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002505 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002506
2507 const uint32_t flags = layer->doTransaction(0);
2508 if (flags & Layer::eVisibleRegion)
2509 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002510
2511 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002512 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002513 }
Robert Carr2047fae2016-11-28 14:09:09 -08002514 });
Marissa Wall06255332019-03-27 13:48:27 -07002515 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002516 }
2517
2518 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002519 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002520 */
2521
Mathias Agopiane57f2922012-08-09 16:29:12 -07002522 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002523 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002524 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002525 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002526
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002527 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002528 // The transform hint might have changed for some layers
2529 // (either because a display has changed, or because a layer
2530 // as changed).
2531 //
2532 // Walk through all the layers in currentLayers,
2533 // and update their transform hint.
2534 //
2535 // If a layer is visible only on a single display, then that
2536 // display is used to calculate the hint, otherwise we use the
2537 // default display.
2538 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002539 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002540 // the hint is set before we acquire a buffer from the surface texture.
2541 //
2542 // NOTE: layer transactions have taken place already, so we use their
2543 // drawing state. However, SurfaceFlinger's own transaction has not
2544 // happened yet, so we must use the current state layer list
2545 // (soon to become the drawing state list).
2546 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002547 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002548 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002549 bool first = true;
Edgar Arriaga844fa672020-01-16 14:21:42 -08002550 mCurrentState.traverse([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002551 // NOTE: we rely on the fact that layers are sorted by
2552 // layerStack first (so we don't have to traverse the list
2553 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002554 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002555 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002556 currentlayerStack = layerStack;
2557 // figure out if this layerstack is mirrored
2558 // (more than one display) if so, pick the default display,
2559 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002560 hintDisplay = nullptr;
2561 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002562 if (display->getCompositionDisplay()
2563 ->belongsInOutput(layer->getLayerStack(),
2564 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002565 if (hintDisplay) {
2566 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002567 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002568 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002569 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002570 }
2571 }
2572 }
2573 }
Chet Haase91d25932013-04-11 15:24:55 -07002574
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002575 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002576 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2577 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002578
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002579 // could be null when this layer is using a layerStack
2580 // that is not visible on any display. Also can occur at
2581 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002582 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002583 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002584
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002585 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002586 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002587 if (hintDisplay) {
2588 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002589 }
Robert Carr2047fae2016-11-28 14:09:09 -08002590
2591 first = false;
2592 });
Mathias Agopian84300952012-11-21 16:02:13 -08002593 }
2594
2595
Mathias Agopian3559b072012-08-15 13:46:03 -07002596 /*
2597 * Perform our own transaction if needed
2598 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002599
2600 if (mLayersAdded) {
2601 mLayersAdded = false;
2602 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002603 mVisibleRegionsDirty = true;
2604 }
2605
2606 // some layers might have been removed, so
2607 // we need to update the regions they're exposing.
2608 if (mLayersRemoved) {
2609 mLayersRemoved = false;
2610 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002611 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002612 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002613 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002614 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002615 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002616 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002617 }
Robert Carr2047fae2016-11-28 14:09:09 -08002618 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002619 }
2620
Vishnu Nairec0ab382019-02-13 15:32:56 -08002621 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002622 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002623}
2624
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002625void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002626 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002627 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002628 return;
2629 }
2630
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002631 if (mVisibleRegionsDirty || mInputInfoChanged) {
2632 mInputInfoChanged = false;
2633 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002634 } else if (mInputWindowCommands.syncInputWindows) {
2635 // If the caller requested to sync input windows, but there are no
2636 // changes to input windows, notify immediately.
2637 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002638 }
2639
Arthur Hung6cbb9752019-09-05 16:38:18 +08002640 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002641}
2642
2643void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002644 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002645
2646 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2647 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002648 // When calculating the screen bounds we ignore the transparent region since it may
2649 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002650 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002651 }
2652 });
chaviw291d88a2019-02-14 10:33:58 -08002653
2654 mInputFlinger->setInputWindows(inputHandles,
2655 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2656 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002657}
2658
Vishnu Nairec0ab382019-02-13 15:32:56 -08002659void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002660 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002661 mPendingInputWindowCommands.clear();
2662}
2663
Riley Andrews03414a12014-07-01 14:22:59 -07002664void SurfaceFlinger::updateCursorAsync()
2665{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002666 compositionengine::CompositionRefreshArgs refreshArgs;
2667 for (const auto& [_, display] : mDisplays) {
2668 if (display->getId()) {
2669 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002670 }
2671 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002672
2673 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002674}
2675
Ady Abraham2139f732019-11-13 18:56:40 -08002676void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
Ady Abraham8a82ba62020-01-17 12:43:17 -08002677 Scheduler::ConfigEvent event) NO_THREAD_SAFETY_ANALYSIS {
2678 // If this is called from the main thread mStateLock must be locked before
2679 // Currently the only way to call this function from the main thread is from
2680 // Sheduler::chooseRefreshRateForContent
2681
2682 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Ady Abraham2139f732019-11-13 18:56:40 -08002683 changeRefreshRateLocked(refreshRate, event);
2684}
2685
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002686void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2687 if (mScheduler) {
2688 // In practice it's not allowed to hotplug in/out the primary display once it's been
2689 // connected during startup, but some tests do it, so just warn and return.
2690 ALOGW("Can't re-init scheduler");
2691 return;
2692 }
2693
Ady Abraham2139f732019-11-13 18:56:40 -08002694 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002695 mRefreshRateConfigs =
Ana Krulec8c6f3f62020-01-23 15:48:01 -08002696 std::make_unique<scheduler::RefreshRateConfigs>(getHwComposer().getConfigs(
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002697 primaryDisplayId),
2698 currentConfig);
2699 mRefreshRateStats =
2700 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2701 currentConfig, HWC_POWER_MODE_OFF);
2702 mRefreshRateStats->setConfigMode(currentConfig);
2703
Ady Abraham9e16a482019-12-03 17:19:41 -08002704 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2705
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002706 // start the EventThread
2707 mScheduler =
2708 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002709 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002710 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002711 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002712 impl::EventThread::InterceptVSyncsCallback());
2713 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002714 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002715 [this](nsecs_t timestamp) {
2716 mInterceptor->saveVSyncEvent(timestamp);
2717 });
2718
2719 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2720 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002721 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002722
2723 mRegionSamplingThread =
2724 new RegionSamplingThread(*this, *mScheduler,
2725 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002726 // Dispatch a config change request for the primary display on scheduler
2727 // initialization, so that the EventThreads always contain a reference to a
2728 // prior configuration.
2729 //
2730 // This is a bit hacky, but this avoids a back-pointer into the main SF
2731 // classes from EventThread, and there should be no run-time binder cost
2732 // anyway since there are no connected apps at this point.
2733 const nsecs_t vsyncPeriod =
2734 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2735 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2736 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002737}
2738
Mathias Agopian4fec8732012-06-29 14:12:52 -07002739void SurfaceFlinger::commitTransaction()
2740{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002741 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002742
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002743 mTransactionPending = false;
2744 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002745 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002746}
2747
Lloyd Pique58e24a32019-08-01 15:50:14 -07002748void SurfaceFlinger::commitTransactionLocked() {
2749 if (!mLayersPendingRemoval.isEmpty()) {
2750 // Notify removed layers now that they can't be drawn from
2751 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002752 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002753
2754 // Ensure any buffers set to display on any children are released.
2755 if (l->isRemovedFromCurrentState()) {
2756 l->latchAndReleaseBuffer();
2757 }
2758
2759 // If the layer has been removed and has no parent, then it will not be reachable
2760 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2761 // ensure we can copy its current to drawing state.
2762 if (!l->getParent()) {
2763 mOffscreenLayers.emplace(l.get());
2764 }
2765 }
2766 mLayersPendingRemoval.clear();
2767 }
2768
2769 // If this transaction is part of a window animation then the next frame
2770 // we composite should be considered an animation as well.
2771 mAnimCompositionPending = mAnimTransactionPending;
2772
2773 mDrawingState = mCurrentState;
2774 // clear the "changed" flags in current state
2775 mCurrentState.colorMatrixChanged = false;
2776
Edgar Arriaga844fa672020-01-16 14:21:42 -08002777 mDrawingState.traverse([&](Layer* layer) {
Lloyd Pique58e24a32019-08-01 15:50:14 -07002778 layer->commitChildList();
2779
2780 // If the layer can be reached when traversing mDrawingState, then the layer is no
2781 // longer offscreen. Remove the layer from the offscreenLayer set.
2782 if (mOffscreenLayers.count(layer)) {
2783 mOffscreenLayers.erase(layer);
2784 }
2785 });
2786
2787 commitOffscreenLayers();
Edgar Arriaga844fa672020-01-16 14:21:42 -08002788 mDrawingState.traverse([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002789}
2790
Nataniel Borges2b796da2019-02-15 13:32:18 -08002791void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2792 if (mTracingEnabledChanged) {
2793 mTracingEnabled = mTracing.isEnabled();
2794 mTracingEnabledChanged = false;
2795 }
2796
2797 // Synchronize with Tracing thread
2798 std::unique_lock<std::mutex> lock;
2799 if (mTracingEnabled) {
2800 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2801 }
2802
2803 lockedOperation();
2804
2805 // Synchronize with Tracing thread
2806 if (mTracingEnabled) {
2807 lock.unlock();
2808 }
2809}
2810
chaviw74d90ad2019-04-26 14:45:26 -07002811void SurfaceFlinger::commitOffscreenLayers() {
2812 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002813 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [](Layer* layer) {
chaviw74d90ad2019-04-26 14:45:26 -07002814 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2815 if (!trFlags) return;
2816
2817 layer->doTransaction(0);
2818 layer->commitChildList();
2819 });
2820 }
2821}
2822
Chia-I Wuab0c3192017-08-01 11:29:00 -07002823void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002824 for (const auto& [token, displayDevice] : mDisplays) {
2825 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002826 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002827 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002828 }
2829 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002830}
2831
Dan Stoza6b9454d2014-11-07 16:00:59 -08002832bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002833{
Ady Abraham09bd3922019-04-08 10:44:56 -07002834 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002835 ALOGV("handlePageFlip");
2836
Brian Andersond6927fb2016-07-23 23:37:30 -07002837 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002838
Mathias Agopian4fec8732012-06-29 14:12:52 -07002839 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002840 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002841 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002842
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002843 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2844
Eric Penner51c59cd2014-07-28 19:51:58 -07002845 // Store the set of layers that need updates. This set must not change as
2846 // buffers are being latched, as this could result in a deadlock.
2847 // Example: Two producers share the same command stream and:
2848 // 1.) Layer 0 is latched
2849 // 2.) Layer 0 gets a new frame
2850 // 2.) Layer 1 gets a new frame
2851 // 3.) Layer 1 is latched.
2852 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2853 // second frame. But layer 0's second frame could be waiting on display.
Edgar Arriaga844fa672020-01-16 14:21:42 -08002854 mDrawingState.traverse([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002855 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002856 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002857 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002858 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002859 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002860 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002861 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002862 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002863 } else {
2864 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002865 }
Robert Carr2047fae2016-11-28 14:09:09 -08002866 });
2867
chaviw49a108c2019-08-12 11:23:06 -07002868 // The client can continue submitting buffers for offscreen layers, but they will not
2869 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2870 // layers to ensure dequeueBuffer doesn't block indefinitely.
2871 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08002872 offscreenLayer->traverse(LayerVector::StateSet::Drawing,
chaviw49a108c2019-08-12 11:23:06 -07002873 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2874 }
2875
Lloyd Piquef2c79392018-12-20 16:23:33 -08002876 if (!mLayersWithQueuedFrames.empty()) {
2877 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2878 // writes to Layer current state. See also b/119481871
2879 Mutex::Autolock lock(mStateLock);
2880
2881 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002882 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002883 mLayersPendingRefresh.push_back(layer);
2884 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002885 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002886 if (layer->isBufferLatched()) {
2887 newDataLatched = true;
2888 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002889 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002890 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002891
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002892 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002893
2894 // If we will need to wake up at some time in the future to deal with a
2895 // queued frame that shouldn't be displayed during this vsync period, wake
2896 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002897 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002898 signalLayerUpdate();
2899 }
2900
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002901 // enter boot animation on first buffer latch
2902 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2903 ALOGI("Enter boot animation");
2904 mBootStage = BootStage::BOOTANIMATION;
2905 }
2906
Edgar Arriaga844fa672020-01-16 14:21:42 -08002907 mDrawingState.traverse([&](Layer* layer) { layer->updateCloneBufferInfo(); });
chaviw74b03172019-08-19 11:09:03 -07002908
Dan Stoza6b9454d2014-11-07 16:00:59 -08002909 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002910 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002911}
2912
Mathias Agopianad456f92011-01-13 17:53:01 -08002913void SurfaceFlinger::invalidateHwcGeometry()
2914{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002915 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002916}
2917
Robert Carrc0df3122019-04-11 13:18:21 -07002918status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2919 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2920 const sp<IBinder>& parentHandle,
2921 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002922 // add this layer to the current state list
2923 {
2924 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002925 sp<Layer> parent;
2926 if (parentHandle != nullptr) {
2927 parent = fromHandle(parentHandle);
2928 if (parent == nullptr) {
2929 return NAME_NOT_FOUND;
2930 }
2931 } else {
2932 parent = parentLayer;
2933 }
2934
Robert Carr1f0a16a2016-10-24 16:27:39 -07002935 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002936 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002937 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002938 return NO_MEMORY;
2939 }
Robert Carrc0df3122019-04-11 13:18:21 -07002940
2941 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2942
Robert Carrb89ea9d2018-12-10 13:01:14 -08002943 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002944 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002945 } else if (parent == nullptr) {
2946 lbc->onRemovedFromCurrentState();
2947 } else if (parent->isRemovedFromCurrentState()) {
2948 parent->addChild(lbc);
2949 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002950 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002951 parent->addChild(lbc);
2952 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002953
Yiwei Zhang243b3782018-05-15 17:40:04 -07002954 if (gbc != nullptr) {
2955 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2956 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2957 mMaxGraphicBufferProducerListSize,
2958 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2959 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002960 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002961 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002962 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002963 }
2964
Mathias Agopian96f08192010-06-02 23:28:45 -07002965 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002966 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002967
Dan Stoza7d89d062015-04-30 13:29:25 -07002968 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002969}
2970
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002971uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002972 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002973}
2974
Mathias Agopian3f844832013-08-07 21:24:32 -07002975uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002976 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002977}
2978
Mathias Agopian3f844832013-08-07 21:24:32 -07002979uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002980 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002981}
2982
2983uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002984 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002985 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002986 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002987 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002988 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002989 }
2990 return old;
2991}
2992
Marissa Wall713b63f2018-10-17 15:42:43 -07002993bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002994 // to prevent onHandleDestroyed from being called while the lock is held,
2995 // we must keep a copy of the transactions (specifically the composer
2996 // states) around outside the scope of the lock
2997 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002998 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002999 {
3000 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003001
Valerie Haufce31b82019-04-30 16:41:14 -07003002 auto it = mTransactionQueues.begin();
3003 while (it != mTransactionQueues.end()) {
3004 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07003005
Valerie Haufce31b82019-04-30 16:41:14 -07003006 while (!transactionQueue.empty()) {
3007 const auto& transaction = transactionQueue.front();
3008 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003009 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07003010 transaction.states)) {
3011 setTransactionFlags(eTransactionFlushNeeded);
3012 break;
3013 }
3014 transactions.push_back(transaction);
3015 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
3016 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003017 transaction.buffer, transaction.postTime,
3018 transaction.privileged, transaction.hasListenerCallbacks,
3019 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07003020 transactionQueue.pop();
3021 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003022 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003023
Valerie Haufce31b82019-04-30 16:41:14 -07003024 if (transactionQueue.empty()) {
3025 it = mTransactionQueues.erase(it);
3026 mTransactionCV.broadcast();
3027 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003028 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003029 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003030 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003031 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003032 return flushedATransaction;
3033}
3034
3035bool SurfaceFlinger::transactionFlushNeeded() {
3036 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003037}
3038
chaviwca27f252018-02-06 16:46:39 -08003039
Marissa Wall17b4e452018-12-26 16:32:34 -08003040bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003041 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003042 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003043 if (!useCachedExpectedPresentTime)
3044 populateExpectedPresentTime();
3045
3046 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003047 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3048 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3049 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3050 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3051 return false;
3052 }
3053
Marissa Wall713b63f2018-10-17 15:42:43 -07003054 for (const ComposerState& state : states) {
3055 const layer_state_t& s = state.state;
3056 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3057 continue;
3058 }
3059 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003060 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003061 }
3062 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003063 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003064}
3065
Valerie Hau9dab9732019-08-20 09:29:25 -07003066void SurfaceFlinger::setTransactionState(
3067 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3068 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3069 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3070 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003071 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003072
Valerie Haubc6ddb12019-03-08 11:10:15 -08003073 const int64_t postTime = systemTime();
3074
Robert Carr14167e02019-02-13 13:50:55 -08003075 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3076
Mathias Agopian698c0872011-06-28 19:09:31 -07003077 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003078
Marissa Wall713b63f2018-10-17 15:42:43 -07003079 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003080 auto itr = mTransactionQueues.find(applyToken);
3081 // if this is an animation frame, wait until prior animation frame has
3082 // been applied by SF
3083 if (flags & eAnimation) {
3084 while (itr != mTransactionQueues.end()) {
3085 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3086 if (CC_UNLIKELY(err != NO_ERROR)) {
3087 ALOGW_IF(err == TIMED_OUT,
3088 "setTransactionState timed out "
3089 "waiting for animation frame to apply");
3090 break;
3091 }
3092 itr = mTransactionQueues.find(applyToken);
3093 }
3094 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003095
3096 // Expected present time is computed and cached on invalidate, so it may be stale.
3097 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3098 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003099 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003100 uncacheBuffer, postTime, privileged,
3101 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003102 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003103 return;
3104 }
3105
Valerie Haubc6ddb12019-03-08 11:10:15 -08003106 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003107 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3108 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003109}
3110
Valerie Hau9dab9732019-08-20 09:29:25 -07003111void SurfaceFlinger::applyTransactionState(
3112 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3113 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3114 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3115 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3116 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003117 uint32_t transactionFlags = 0;
3118
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003119 if (flags & eAnimation) {
3120 // For window updates that are part of an animation we must wait for
3121 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003122 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003123 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003124 if (CC_UNLIKELY(err != NO_ERROR)) {
3125 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003126 // caller after a few seconds.
3127 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3128 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003129 mAnimTransactionPending = false;
3130 break;
3131 }
3132 }
3133 }
3134
chaviwca27f252018-02-06 16:46:39 -08003135 for (const DisplayState& display : displays) {
3136 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003137 }
3138
Valerie Hau9dab9732019-08-20 09:29:25 -07003139 // start and end registration for listeners w/ no surface so they can get their callback. Note
3140 // that listeners with SurfaceControls will start registration during setClientStateLocked
3141 // below.
3142 for (const auto& listener : listenerCallbacks) {
3143 mTransactionCompletedThread.startRegistration(listener);
3144 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003145 }
3146
Valerie Hau9dab9732019-08-20 09:29:25 -07003147 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003148 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003149 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003150 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3151 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003152 }
3153
Valerie Hau9dab9732019-08-20 09:29:25 -07003154 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003155 mTransactionCompletedThread.endRegistration(listenerCallback);
3156 }
3157
Marissa Walle2ffb422018-10-12 11:33:52 -07003158 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003159 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003160 mTransactionCompletedThread.sendCallbacks();
3161 }
3162 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003163
chaviw273171b2018-12-26 11:46:30 -08003164 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3165
Marissa Wall947d34e2019-03-29 14:03:53 -07003166 if (uncacheBuffer.isValid()) {
3167 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003168 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003169 }
3170
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003171 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3172 // anyway. This can be used as a flush mechanism for previous async transactions.
3173 // Empty animation transaction can be used to simulate back-pressure, so also force a
3174 // transaction for empty animation transactions.
3175 if (transactionFlags == 0 &&
3176 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003177 transactionFlags = eTransactionNeeded;
3178 }
3179
Marissa Wall06255332019-03-27 13:48:27 -07003180 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3181 // so we don't have to wake up again next frame to preform an uneeded traversal.
3182 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3183 transactionFlags = transactionFlags & (~eTraversalNeeded);
3184 mTraversalNeededMainThread = true;
3185 }
3186
Mathias Agopian386aa982011-11-07 21:58:03 -08003187 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003188 if (mInterceptor->isEnabled()) {
3189 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003190 }
Irvel468051e2016-06-13 16:44:44 -07003191
Mathias Agopian386aa982011-11-07 21:58:03 -08003192 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003193 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3194 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003195 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003196
3197 // if this is a synchronous transaction, wait for it to take effect
3198 // before returning.
3199 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003200 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003201 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003202 if (flags & eAnimation) {
3203 mAnimTransactionPending = true;
3204 }
chaviw4fe36852019-04-15 16:25:49 -07003205 if (mPendingInputWindowCommands.syncInputWindows) {
3206 mPendingSyncInputWindows = true;
3207 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003208
3209 // applyTransactionState can be called by either the main SF thread or by
3210 // another process through setTransactionState. While a given process may wish
3211 // to wait on synchronous transactions, the main SF thread should never
3212 // be blocked. Therefore, we only wait if isMainThread is false.
3213 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003214 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3215 if (CC_UNLIKELY(err != NO_ERROR)) {
3216 // just in case something goes wrong in SF, return to the
3217 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003218 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3219 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003220 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003221 break;
3222 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003223 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003224 }
3225}
3226
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003227uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3228 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3229 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003230
Mathias Agopiane57f2922012-08-09 16:29:12 -07003231 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003232 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3233
3234 const uint32_t what = s.what;
3235 if (what & DisplayState::eSurfaceChanged) {
3236 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3237 state.surface = s.surface;
3238 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003239 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003240 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003241 if (what & DisplayState::eLayerStackChanged) {
3242 if (state.layerStack != s.layerStack) {
3243 state.layerStack = s.layerStack;
3244 flags |= eDisplayTransactionNeeded;
3245 }
3246 }
3247 if (what & DisplayState::eDisplayProjectionChanged) {
3248 if (state.orientation != s.orientation) {
3249 state.orientation = s.orientation;
3250 flags |= eDisplayTransactionNeeded;
3251 }
3252 if (state.frame != s.frame) {
3253 state.frame = s.frame;
3254 flags |= eDisplayTransactionNeeded;
3255 }
3256 if (state.viewport != s.viewport) {
3257 state.viewport = s.viewport;
3258 flags |= eDisplayTransactionNeeded;
3259 }
3260 }
3261 if (what & DisplayState::eDisplaySizeChanged) {
3262 if (state.width != s.width) {
3263 state.width = s.width;
3264 flags |= eDisplayTransactionNeeded;
3265 }
3266 if (state.height != s.height) {
3267 state.height = s.height;
3268 flags |= eDisplayTransactionNeeded;
3269 }
3270 }
3271
Mathias Agopiane57f2922012-08-09 16:29:12 -07003272 return flags;
3273}
3274
Robert Carr14167e02019-02-13 13:50:55 -08003275bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003276 IPCThreadState* ipc = IPCThreadState::self();
3277 const int pid = ipc->getCallingPid();
3278 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003279 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003280 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003281 return false;
3282 }
3283 return true;
3284}
3285
Marissa Wall3dad52d2019-03-22 14:03:19 -07003286uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003287 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3288 bool privileged,
3289 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003290 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003291
Valerie Hau9dab9732019-08-20 09:29:25 -07003292 for (auto& listener : s.listeners) {
3293 // note that startRegistration will not re-register if the listener has
3294 // already be registered for a prior surface control
3295 mTransactionCompletedThread.startRegistration(listener);
3296 listenerCallbacks.insert(listener);
3297 }
3298
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003299 sp<Layer> layer = nullptr;
3300 if (s.surface) {
3301 layer = fromHandle(s.surface);
3302 } else {
3303 // The client may provide us a null handle. Treat it as if the layer was removed.
3304 ALOGW("Attempt to set client state with a null layer handle");
3305 }
chaviw8b3871a2017-11-01 17:41:01 -07003306 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003307 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003308 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003309 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003310 }
chaviw8b3871a2017-11-01 17:41:01 -07003311 return 0;
3312 }
3313
chaviw8b3871a2017-11-01 17:41:01 -07003314 uint32_t flags = 0;
3315
Garfield Tan8a3083e2018-12-03 13:21:07 -08003316 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003317
3318 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3319 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003320 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003321 layer->pushPendingState();
3322 }
3323
chaviw8b3871a2017-11-01 17:41:01 -07003324 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003325 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003326 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003327 }
chaviw8b3871a2017-11-01 17:41:01 -07003328 }
3329 if (what & layer_state_t::eLayerChanged) {
3330 // NOTE: index needs to be calculated before we update the state
3331 const auto& p = layer->getParent();
3332 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003333 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003334 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003335 mCurrentState.layersSortedByZ.removeAt(idx);
3336 mCurrentState.layersSortedByZ.add(layer);
3337 // we need traversal (state changed)
3338 // AND transaction (list changed)
3339 flags |= eTransactionNeeded|eTraversalNeeded;
3340 }
chaviw8b3871a2017-11-01 17:41:01 -07003341 } else {
3342 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003343 flags |= eTransactionNeeded|eTraversalNeeded;
3344 }
3345 }
chaviw8b3871a2017-11-01 17:41:01 -07003346 }
3347 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003348 // NOTE: index needs to be calculated before we update the state
3349 const auto& p = layer->getParent();
3350 if (p == nullptr) {
3351 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3352 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3353 mCurrentState.layersSortedByZ.removeAt(idx);
3354 mCurrentState.layersSortedByZ.add(layer);
3355 // we need traversal (state changed)
3356 // AND transaction (list changed)
3357 flags |= eTransactionNeeded|eTraversalNeeded;
3358 }
3359 } else {
3360 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3361 flags |= eTransactionNeeded|eTraversalNeeded;
3362 }
chaviw8b3871a2017-11-01 17:41:01 -07003363 }
3364 }
3365 if (what & layer_state_t::eSizeChanged) {
3366 if (layer->setSize(s.w, s.h)) {
3367 flags |= eTraversalNeeded;
3368 }
3369 }
3370 if (what & layer_state_t::eAlphaChanged) {
3371 if (layer->setAlpha(s.alpha))
3372 flags |= eTraversalNeeded;
3373 }
3374 if (what & layer_state_t::eColorChanged) {
3375 if (layer->setColor(s.color))
3376 flags |= eTraversalNeeded;
3377 }
Peiyong Lind3788632018-09-18 16:01:31 -07003378 if (what & layer_state_t::eColorTransformChanged) {
3379 if (layer->setColorTransform(s.colorTransform)) {
3380 flags |= eTraversalNeeded;
3381 }
3382 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003383 if (what & layer_state_t::eBackgroundColorChanged) {
3384 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3385 flags |= eTraversalNeeded;
3386 }
3387 }
chaviw8b3871a2017-11-01 17:41:01 -07003388 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003389 // TODO: b/109894387
3390 //
3391 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3392 // rotation. To see the problem observe that if we have a square parent, and a child
3393 // of the same size, then we rotate the child 45 degrees around it's center, the child
3394 // must now be cropped to a non rectangular 8 sided region.
3395 //
3396 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3397 // private API, and the WindowManager only uses rotation in one case, which is on a top
3398 // level layer in which cropping is not an issue.
3399 //
3400 // However given that abuse of rotation matrices could lead to surfaces extending outside
3401 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3402 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3403 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003404 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003405 flags |= eTraversalNeeded;
3406 }
3407 if (what & layer_state_t::eTransparentRegionChanged) {
3408 if (layer->setTransparentRegionHint(s.transparentRegion))
3409 flags |= eTraversalNeeded;
3410 }
3411 if (what & layer_state_t::eFlagsChanged) {
3412 if (layer->setFlags(s.flags, s.mask))
3413 flags |= eTraversalNeeded;
3414 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003415 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003416 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003417 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003418 if (what & layer_state_t::eCornerRadiusChanged) {
3419 if (layer->setCornerRadius(s.cornerRadius))
3420 flags |= eTraversalNeeded;
3421 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003422 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3423 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3424 }
chaviw8b3871a2017-11-01 17:41:01 -07003425 if (what & layer_state_t::eLayerStackChanged) {
3426 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3427 // We only allow setting layer stacks for top level layers,
3428 // everything else inherits layer stack from its parent.
3429 if (layer->hasParent()) {
3430 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003431 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003432 } else if (idx < 0) {
3433 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003434 "that also does not appear in the top level layer list. Something"
3435 " has gone wrong.",
3436 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003437 } else if (layer->setLayerStack(s.layerStack)) {
3438 mCurrentState.layersSortedByZ.removeAt(idx);
3439 mCurrentState.layersSortedByZ.add(layer);
3440 // we need traversal (state changed)
3441 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003442 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003443 }
3444 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003445 if (what & layer_state_t::eDeferTransaction_legacy) {
3446 if (s.barrierHandle_legacy != nullptr) {
3447 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3448 } else if (s.barrierGbp_legacy != nullptr) {
3449 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003450 if (authenticateSurfaceTextureLocked(gbp)) {
3451 const auto& otherLayer =
3452 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003453 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003454 } else {
3455 ALOGE("Attempt to defer transaction to to an"
3456 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003457 }
3458 }
chaviw8b3871a2017-11-01 17:41:01 -07003459 // We don't trigger a traversal here because if no other state is
3460 // changed, we don't want this to cause any more work
3461 }
chaviw8b3871a2017-11-01 17:41:01 -07003462 if (what & layer_state_t::eReparentChildren) {
3463 if (layer->reparentChildren(s.reparentHandle)) {
3464 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003465 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003466 }
chaviw8b3871a2017-11-01 17:41:01 -07003467 if (what & layer_state_t::eDetachChildren) {
3468 layer->detachChildren();
3469 }
3470 if (what & layer_state_t::eOverrideScalingModeChanged) {
3471 layer->setOverrideScalingMode(s.overrideScalingMode);
3472 // We don't trigger a traversal here because if no other state is
3473 // changed, we don't want this to cause any more work
3474 }
Marissa Wall61c58622018-07-18 10:12:20 -07003475 if (what & layer_state_t::eTransformChanged) {
3476 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3477 }
3478 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3479 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3480 flags |= eTraversalNeeded;
3481 }
3482 if (what & layer_state_t::eCropChanged) {
3483 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3484 }
Marissa Wall861616d2018-10-22 12:52:23 -07003485 if (what & layer_state_t::eFrameChanged) {
3486 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3487 }
Marissa Wall61c58622018-07-18 10:12:20 -07003488 if (what & layer_state_t::eAcquireFenceChanged) {
3489 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3490 }
3491 if (what & layer_state_t::eDataspaceChanged) {
3492 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3493 }
3494 if (what & layer_state_t::eHdrMetadataChanged) {
3495 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3496 }
3497 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3498 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3499 }
3500 if (what & layer_state_t::eApiChanged) {
3501 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3502 }
3503 if (what & layer_state_t::eSidebandStreamChanged) {
3504 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3505 }
Robert Carr720e5062018-07-30 17:45:14 -07003506 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003507 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003508 layer->setInputInfo(s.inputInfo);
3509 flags |= eTraversalNeeded;
3510 } else {
3511 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3512 }
Robert Carr720e5062018-07-30 17:45:14 -07003513 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003514 if (what & layer_state_t::eMetadataChanged) {
3515 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3516 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003517 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3518 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3519 flags |= eTraversalNeeded;
3520 }
3521 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003522 if (what & layer_state_t::eShadowRadiusChanged) {
3523 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3524 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003525 if (what & layer_state_t::eFrameRateSelectionPriority) {
3526 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3527 flags |= eTraversalNeeded;
3528 }
3529 }
Steven Thomas3172e202020-01-06 19:25:30 -08003530 if (what & layer_state_t::eFrameRateChanged) {
3531 if (layer->setFrameRate(s.frameRate)) flags |= eTraversalNeeded;
3532 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003533 // This has to happen after we reparent children because when we reparent to null we remove
3534 // child layers from current state and remove its relative z. If the children are reparented in
3535 // the same transaction, then we have to make sure we reparent the children first so we do not
3536 // lose its relative z order.
3537 if (what & layer_state_t::eReparent) {
3538 bool hadParent = layer->hasParent();
3539 if (layer->reparent(s.parentHandleForChild)) {
3540 if (!hadParent) {
3541 mCurrentState.layersSortedByZ.remove(layer);
3542 }
3543 flags |= eTransactionNeeded | eTraversalNeeded;
3544 }
3545 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003546 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003547 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3548 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003549 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3550 }
3551 }
Marissa Wall78b72202019-03-15 14:58:34 -07003552 bool bufferChanged = what & layer_state_t::eBufferChanged;
3553 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3554 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003555 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003556 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003557 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3558 if (success) {
3559 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3560 success = ClientCache::getInstance()
3561 .registerErasedRecipient(s.cachedBuffer,
3562 wp<ClientCache::ErasedRecipient>(this));
3563 if (!success) {
3564 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3565 }
3566 }
Marissa Wall78b72202019-03-15 14:58:34 -07003567 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003568 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003569 } else if (bufferChanged) {
3570 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003571 }
Marissa Wall78b72202019-03-15 14:58:34 -07003572 if (buffer) {
Valerie Haubf784642020-01-29 07:25:23 -08003573 if (layer->setBuffer(buffer, s.acquireFence, postTime, desiredPresentTime,
3574 s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003575 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003576 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003577 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003578 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3579 // Do not put anything that updates layer state or modifies flags after
3580 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003581 return flags;
3582}
3583
chaviw273171b2018-12-26 11:46:30 -08003584uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3585 uint32_t flags = 0;
3586 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3587 flags |= eTraversalNeeded;
3588 }
3589
chaviwa911b102019-02-14 10:18:33 -08003590 if (inputWindowCommands.syncInputWindows) {
3591 flags |= eTraversalNeeded;
3592 }
3593
Vishnu Nairec0ab382019-02-13 15:32:56 -08003594 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003595 return flags;
3596}
3597
chaviwfe94a222019-08-21 13:52:59 -07003598status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3599 sp<IBinder>* outHandle) {
3600 if (!mirrorFromHandle) {
3601 return NAME_NOT_FOUND;
3602 }
3603
3604 sp<Layer> mirrorLayer;
3605 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003606 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003607
3608 {
3609 Mutex::Autolock _l(mStateLock);
3610 mirrorFrom = fromHandle(mirrorFromHandle);
3611 if (!mirrorFrom) {
3612 return NAME_NOT_FOUND;
3613 }
3614
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003615 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3616 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003617 if (result != NO_ERROR) {
3618 return result;
3619 }
3620
3621 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3622 }
3623
3624 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3625}
3626
Marissa Wall2d814fb2019-04-09 18:52:57 +00003627status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3628 uint32_t h, PixelFormat format, uint32_t flags,
3629 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003630 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003631 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3632 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003633 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003634 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003635 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003636 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003637 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003638
Robert Carrc0df3122019-04-11 13:18:21 -07003639 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3640 "Expected only one of parentLayer or parentHandle to be non-null. "
3641 "Programmer error?");
3642
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003643 status_t result = NO_ERROR;
3644
3645 sp<Layer> layer;
3646
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003647 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003648
Evan Roskya1f1e152019-01-24 16:17:46 -08003649 bool primaryDisplayOnly = false;
3650
3651 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3652 // TODO b/64227542
3653 if (metadata.has(METADATA_WINDOW_TYPE)) {
3654 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3655 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003656 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003657 primaryDisplayOnly = true;
3658 }
3659 }
3660
Mathias Agopian3165cc22012-08-08 19:42:09 -07003661 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003662 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003663 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3664 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003665
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003666 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003667 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003668 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003669 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003670 break;
chaviw13fdc492017-06-27 12:40:18 -07003671 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003672 // check if buffer size is set for color layer.
3673 if (w > 0 || h > 0) {
3674 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3675 int(w), int(h));
3676 return BAD_VALUE;
3677 }
3678
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003679 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3680 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003681 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003682 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003683 // check if buffer size is set for container layer.
3684 if (w > 0 || h > 0) {
3685 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3686 int(w), int(h));
3687 return BAD_VALUE;
3688 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003689 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3690 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003691 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003692 default:
3693 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003694 break;
3695 }
3696
Dan Stoza7d89d062015-04-30 13:29:25 -07003697 if (result != NO_ERROR) {
3698 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003699 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003700
Evan Roskya1f1e152019-01-24 16:17:46 -08003701 if (primaryDisplayOnly) {
3702 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003703 }
3704
Robert Carrb89ea9d2018-12-10 13:01:14 -08003705 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003706 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3707 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003708 if (result != NO_ERROR) {
3709 return result;
3710 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003711 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003712
3713 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003714 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003715}
3716
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003717std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3718 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003719
3720 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003721 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003722
Dan Stoza436ccf32018-06-21 12:10:12 -07003723 // Grab the state lock since we're accessing mCurrentState
3724 Mutex::Autolock lock(mStateLock);
3725
Cody Northropbc755282017-03-31 12:00:08 -06003726 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003727 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003728 while (matchFound) {
3729 matchFound = false;
Edgar Arriaga844fa672020-01-16 14:21:42 -08003730 mCurrentState.traverse([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003731 if (layer->getName() == uniqueName) {
3732 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003733 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003734 }
3735 });
3736 }
3737
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003738 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003739 return uniqueName;
3740}
3741
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003742status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003743 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003744 LayerMetadata metadata, PixelFormat& format,
3745 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003746 sp<IGraphicBufferProducer>* gbp,
3747 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003748 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003749 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003750 case PIXEL_FORMAT_TRANSPARENT:
3751 case PIXEL_FORMAT_TRANSLUCENT:
3752 format = PIXEL_FORMAT_RGBA_8888;
3753 break;
3754 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003755 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003756 break;
3757 }
3758
chaviwb4c6e582019-08-16 14:35:07 -07003759 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003760 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003761 args.textureName = getNewTexture();
3762 {
3763 // Grab the SF state lock during this since it's the only safe way to access
3764 // RenderEngine when creating a BufferLayerConsumer
3765 // TODO: Check if this lock is still needed here
3766 Mutex::Autolock lock(mStateLock);
3767 layer = getFactory().createBufferQueueLayer(args);
3768 }
3769
Marissa Wallfd668622018-05-10 10:21:13 -07003770 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003771 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003772 *handle = layer->getHandle();
3773 *gbp = layer->getProducer();
3774 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003775 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003776
Marissa Wallfd668622018-05-10 10:21:13 -07003777 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003778 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003779}
3780
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003781status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003782 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003783 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003784 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003785 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003786 args.displayDevice = getDefaultDisplayDevice();
3787 args.textureName = getNewTexture();
3788 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003789 if (outTransformHint) {
3790 *outTransformHint = layer->getTransformHint();
3791 }
Marissa Wall61c58622018-07-18 10:12:20 -07003792 *handle = layer->getHandle();
3793 *outLayer = layer;
3794
3795 return NO_ERROR;
3796}
3797
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003798status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003799 uint32_t h, uint32_t flags, LayerMetadata metadata,
3800 sp<IBinder>* handle, sp<Layer>* outLayer) {
3801 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003802 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003803 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003804 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003805}
3806
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003807status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003808 uint32_t w, uint32_t h, uint32_t flags,
3809 LayerMetadata metadata, sp<IBinder>* handle,
3810 sp<Layer>* outLayer) {
3811 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003812 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003813 *handle = (*outLayer)->getHandle();
3814 return NO_ERROR;
3815}
3816
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003817void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003818 mLayersPendingRemoval.add(layer);
3819 mLayersRemoved = true;
3820 setTransactionFlags(eTransactionNeeded);
3821}
3822
Robert Carr695d5282018-12-18 15:27:58 -08003823void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003824{
Robert Carr2e102c92018-10-23 12:11:15 -07003825 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003826 // If a layer has a parent, we allow it to out-live it's handle
3827 // with the idea that the parent holds a reference and will eventually
3828 // be cleaned up. However no one cleans up the top-level so we do so
3829 // here.
3830 if (layer->getParent() == nullptr) {
3831 mCurrentState.layersSortedByZ.remove(layer);
3832 }
3833 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003834
3835 auto it = mLayersByLocalBinderToken.begin();
3836 while (it != mLayersByLocalBinderToken.end()) {
3837 if (it->second == layer) {
3838 it = mLayersByLocalBinderToken.erase(it);
3839 } else {
3840 it++;
3841 }
3842 }
3843
Robert Carr695d5282018-12-18 15:27:58 -08003844 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003845}
3846
Mathias Agopianb60314a2012-04-10 22:09:54 -07003847// ---------------------------------------------------------------------------
3848
Andy McFadden13a082e2012-08-24 10:16:42 -07003849void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003850 const auto display = getDefaultDisplayDeviceLocked();
3851 if (!display) return;
3852
3853 const sp<IBinder> token = display->getDisplayToken().promote();
3854 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003855
Jesse Hall01e29052013-02-19 16:13:35 -08003856 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003857 Vector<ComposerState> state;
3858 Vector<DisplayState> displays;
3859 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003860 d.what = DisplayState::eDisplayProjectionChanged |
3861 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003862 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003863 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003864 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003865 d.frame.makeInvalid();
3866 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003867 d.width = 0;
3868 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003869 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003870 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3871 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003872
Dominik Laskowskie9774092018-12-11 10:04:24 -08003873 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003874
Dominik Laskowski83b88212018-12-11 13:34:06 -08003875 const nsecs_t vsyncPeriod = getVsyncPeriod();
3876 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003877
Brian Andersond0010582017-03-07 13:20:31 -08003878 // Use phase of 0 since phase is not known.
3879 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003880 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003881 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003882}
3883
3884void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003885 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003886 postMessageAsync(
3887 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003888}
3889
Ady Abraham27c70212019-06-11 10:52:26 -07003890void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3891 if (mHWCVsyncState != enabled) {
3892 getHwComposer().setVsyncEnabled(displayId, enabled);
3893 mHWCVsyncState = enabled;
3894 }
3895}
3896
Dominik Laskowskie9774092018-12-11 10:04:24 -08003897void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003898 if (display->isVirtual()) {
3899 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003900 return;
3901 }
3902
Dominik Laskowski075d3172018-05-24 15:50:06 -07003903 const auto displayId = display->getId();
3904 LOG_ALWAYS_FATAL_IF(!displayId);
3905
Dominik Laskowski34157762018-10-31 13:07:19 -07003906 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003907
3908 int currentMode = display->getPowerMode();
3909 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003910 return;
3911 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003912
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003913 display->setPowerMode(mode);
3914
Lloyd Pique4dccc412018-01-22 17:21:36 -08003915 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003916 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003917 }
3918
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003919 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003920 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003921 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003922 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003923 mScheduler->onScreenAcquired(mAppConnectionHandle);
3924 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003925 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003926
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003927 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003928 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003929 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003930
3931 struct sched_param param = {0};
3932 param.sched_priority = 1;
3933 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3934 ALOGW("Couldn't set SCHED_FIFO on display on");
3935 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003936 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003937 // Turn off the display
3938 struct sched_param param = {0};
3939 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3940 ALOGW("Couldn't set SCHED_OTHER on display off");
3941 }
3942
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003943 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003944 mScheduler->disableHardwareVsync(true);
3945 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003946 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003947
Ady Abraham27c70212019-06-11 10:52:26 -07003948 // Make sure HWVsync is disabled before turning off the display
3949 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3950
Dominik Laskowski075d3172018-05-24 15:50:06 -07003951 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003952 mVisibleRegionsDirty = true;
3953 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003954 } else if (mode == HWC_POWER_MODE_DOZE ||
3955 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003956 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003957 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003958 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003959 mScheduler->onScreenAcquired(mAppConnectionHandle);
3960 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003961 }
3962 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3963 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003964 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003965 mScheduler->disableHardwareVsync(true);
3966 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003967 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003968 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003969 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003970 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003971 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003972 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003973
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003974 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003975 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003976 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003977 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003978 }
3979
Dominik Laskowski34157762018-10-31 13:07:19 -07003980 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003981}
3982
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003983void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003984 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003985 const auto display = getDisplayDevice(displayToken);
3986 if (!display) {
3987 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3988 displayToken.get());
3989 } else if (display->isVirtual()) {
3990 ALOGW("Attempt to set power mode %d for virtual display", mode);
3991 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003992 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003993 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003994 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003995}
3996
3997// ---------------------------------------------------------------------------
3998
Dominik Laskowskic2867142019-01-21 11:33:38 -08003999status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
4000 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004001 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07004002
Mathias Agopianbd115332013-04-18 16:41:04 -07004003 IPCThreadState* ipc = IPCThreadState::self();
4004 const int pid = ipc->getCallingPid();
4005 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07004006
Mathias Agopianbd115332013-04-18 16:41:04 -07004007 if ((uid != AID_SHELL) &&
4008 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004009 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
4010 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004011 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08004012 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07004013 // (this would indicate SF is stuck, but we want to be able to
4014 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08004015 status_t err = mStateLock.timedLock(s2ns(1));
4016 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07004017 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004018 StringAppendF(&result,
4019 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
4020 "(no locks held)\n",
4021 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07004022 }
4023
Dominik Laskowskic2867142019-01-21 11:33:38 -08004024 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004025 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07004026 {"--dispsync"s,
4027 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004028 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004029 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
4030 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4031 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4032 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4033 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4034 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004035 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004036 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4037 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004038
Dominik Laskowskic2867142019-01-21 11:33:38 -08004039 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004040
Dominik Laskowski46470112019-08-02 13:13:11 -07004041 const auto it = dumpers.find(flag);
4042 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004043 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004044 } else if (!asProto) {
4045 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004046 }
4047
Mathias Agopian9795c422009-08-26 16:36:26 -07004048 if (locked) {
4049 mStateLock.unlock();
4050 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004051
Dominik Laskowski46470112019-08-02 13:13:11 -07004052 if (it == dumpers.end()) {
4053 const LayersProto layersProto = dumpProtoFromMainThread();
4054 if (asProto) {
4055 result.append(layersProto.SerializeAsString());
4056 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004057 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004058 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4059 result.append(LayerProtoParser::layerTreeToString(layerTree));
4060 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004061 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004062 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004063 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004064 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004065 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004066 return NO_ERROR;
4067}
4068
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004069status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4070 if (asProto && mTracing.isEnabled()) {
4071 mTracing.writeToFileAsync();
4072 }
4073
4074 return doDump(fd, DumpArgs(), asProto);
4075}
4076
Dominik Laskowskic2867142019-01-21 11:33:38 -08004077void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004078 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004079 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004080}
4081
Dominik Laskowskic2867142019-01-21 11:33:38 -08004082void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004083 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004084
Dominik Laskowskic2867142019-01-21 11:33:38 -08004085 if (args.size() > 1) {
4086 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004087 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004088 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004089 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004090 }
Robert Carr2047fae2016-11-28 14:09:09 -08004091 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004092 } else {
4093 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004094 }
4095}
4096
Dominik Laskowskic2867142019-01-21 11:33:38 -08004097void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004098 const bool clearAll = args.size() < 2;
4099 const auto name = clearAll ? String8() : String8(args[1]);
4100
Edgar Arriaga844fa672020-01-16 14:21:42 -08004101 mCurrentState.traverse([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004102 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004103 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004104 }
Robert Carr2047fae2016-11-28 14:09:09 -08004105 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004106
Svetoslavd85084b2014-03-20 10:28:31 -07004107 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004108}
4109
Dominik Laskowskic2867142019-01-21 11:33:38 -08004110void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4111 mTimeStats->parseArgs(asProto, args, result);
4112}
4113
Jamie Gennis6547ff42013-07-16 20:12:42 -07004114// This should only be called from the main thread. Otherwise it would need
4115// the lock and should use mCurrentState rather than mDrawingState.
4116void SurfaceFlinger::logFrameStats() {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004117 mDrawingState.traverse([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004118 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004119 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004120
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004121 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004122}
4123
Yiwei Zhang5434a782018-12-05 18:06:32 -08004124void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004125 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004126
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004127 if (isLayerTripleBufferingDisabled())
4128 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004129
Yiwei Zhang5434a782018-12-05 18:06:32 -08004130 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4131 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4132 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4133 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4134 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4135 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004136 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004137}
4138
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004139void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004140 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004141
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004142 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004143 result.append("\n");
4144
Ady Abraham9e16a482019-12-03 17:19:41 -08004145 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004146 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004147 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004148 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004149
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004150 HwcConfigIndexType defaultConfig;
4151 float minFps, maxFps;
4152 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004153 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004154 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004155 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004156 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004157 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4158 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004159
Ana Krulecc2870422019-01-29 19:00:58 -08004160 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004161}
4162
Yiwei Zhang5434a782018-12-05 18:06:32 -08004163void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4164 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004165 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4166 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004167 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004168 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004169 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004170 }
David Sodman4a36e932017-11-07 14:29:47 -08004171 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004172 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004173 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004174 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4175 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004176}
4177
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004178void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4179 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004180 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4181 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004182 for (const auto& segment : history) {
4183 if (!segment.usedThirdBuffer) {
4184 stats.twoBufferTime += segment.totalTime;
4185 }
4186 if (segment.occupancyAverage < 1.0f) {
4187 stats.doubleBufferedTime += segment.totalTime;
4188 } else if (segment.occupancyAverage < 2.0f) {
4189 stats.tripleBufferedTime += segment.totalTime;
4190 }
4191 ++stats.numSegments;
4192 stats.totalTime += segment.totalTime;
4193 }
4194}
4195
Yiwei Zhang5434a782018-12-05 18:06:32 -08004196void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4197 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004198
4199 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4200 const size_t count = currentLayers.size();
4201 for (size_t i=0 ; i<count ; i++) {
4202 currentLayers[i]->dumpFrameEvents(result);
4203 }
4204}
4205
Yiwei Zhang5434a782018-12-05 18:06:32 -08004206void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004207 result.append("Buffering stats:\n");
4208 result.append(" [Layer name] <Active time> <Two buffer> "
4209 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004210 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004211 typedef std::tuple<std::string, float, float, float> BufferTuple;
4212 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004213 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004214 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004215 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004216 if (stats.numSegments == 0) {
4217 continue;
4218 }
4219 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4220 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4221 stats.totalTime;
4222 float doubleBufferRatio = static_cast<float>(
4223 stats.doubleBufferedTime) / stats.totalTime;
4224 float tripleBufferRatio = static_cast<float>(
4225 stats.tripleBufferedTime) / stats.totalTime;
4226 sorted.insert({activeTime, {name, twoBufferRatio,
4227 doubleBufferRatio, tripleBufferRatio}});
4228 }
4229 for (const auto& sortedPair : sorted) {
4230 float activeTime = sortedPair.first;
4231 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004232 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4233 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004234 }
4235 result.append("\n");
4236}
4237
Yiwei Zhang5434a782018-12-05 18:06:32 -08004238void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004239 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004240 const auto displayId = display->getId();
4241 if (!displayId) {
4242 continue;
4243 }
4244 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004245 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004246 continue;
4247 }
4248
Yiwei Zhang5434a782018-12-05 18:06:32 -08004249 StringAppendF(&result,
4250 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4251 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004252 uint8_t port;
4253 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004254 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004255 result.append("no identification data\n");
4256 continue;
4257 }
4258
4259 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004260 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004261 continue;
4262 }
4263
4264 const auto edid = parseEdid(data);
4265 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004266 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004267 continue;
4268 }
4269
Yiwei Zhang5434a782018-12-05 18:06:32 -08004270 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004271 result.append(edid->displayName.data(), edid->displayName.length());
4272 result.append("\"\n");
4273 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004274}
4275
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004276void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4277 std::string& result) const {
4278 hwc2_display_t hwcDisplayId;
4279 uint8_t port;
4280 DisplayIdentificationData data;
4281
4282 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4283 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4284 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4285 }
4286}
4287
Yiwei Zhang5434a782018-12-05 18:06:32 -08004288void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004289 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004290 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4291 StringAppendF(&result, "DisplayColorSetting: %s\n",
4292 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004293
4294 // TODO: print out if wide-color mode is active or not
4295
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004296 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004297 const auto displayId = display->getId();
4298 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004299 continue;
4300 }
4301
Yiwei Zhang5434a782018-12-05 18:06:32 -08004302 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004303 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004304 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004305 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004306 }
4307
Lloyd Pique32cbe282018-10-19 13:09:22 -07004308 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004309 StringAppendF(&result, " Current color mode: %s (%d)\n",
4310 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004311 }
4312 result.append("\n");
4313}
4314
Vishnu Nair8406fd72019-07-30 11:29:31 -07004315LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004316 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004317 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4318 layer->writeToProto(layersProto, traceFlags);
4319 }
chaviw1d044282017-09-27 12:19:28 -07004320 return layersProto;
4321}
4322
Vishnu Nair0f085c62019-08-30 08:49:12 -07004323void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4324 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4325 // it.
4326 LayerProto* rootProto = layersProto.add_layers();
4327 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4328 rootProto->set_id(offscreenRootLayerId);
4329 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004330 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004331
4332 for (Layer* offscreenLayer : mOffscreenLayers) {
4333 // Add layer as child of the fake root
4334 rootProto->add_children(offscreenLayer->sequence);
4335
4336 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004337 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004338 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004339 }
4340}
4341
Vishnu Nair8406fd72019-07-30 11:29:31 -07004342LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4343 LayersProto layersProto;
4344 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4345 return layersProto;
4346}
4347
Vishnu Nair0f085c62019-08-30 08:49:12 -07004348void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4349 result.append("Offscreen Layers:\n");
4350 postMessageSync(new LambdaMessage([&]() {
4351 for (Layer* offscreenLayer : mOffscreenLayers) {
Edgar Arriaga844fa672020-01-16 14:21:42 -08004352 offscreenLayer->traverse(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004353 layer->dumpCallingUidPid(result);
4354 });
4355 }
4356 }));
4357}
4358
Dominik Laskowskic2867142019-01-21 11:33:38 -08004359void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4360 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004361 Colorizer colorizer(colorize);
4362
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004363 // figure out if we're stuck somewhere
4364 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004365 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004366 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4367
4368 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004369 * Dump library configuration.
4370 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004371
4372 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004373 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004374 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004375 appendSfConfigString(result);
4376 appendUiConfigString(result);
4377 appendGuiConfigString(result);
4378 result.append("\n");
4379
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004380 result.append("\nDisplay identification data:\n");
4381 dumpDisplayIdentificationData(result);
4382
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004383 result.append("\nWide-Color information:\n");
4384 dumpWideColorInfo(result);
4385
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004386 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004387 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004388 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004389 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004390 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004391
Andy McFadden41d67d72014-04-25 16:58:34 -07004392 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004393 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004394 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004395 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004396 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004397
Dan Stozab90cf072015-03-05 11:05:59 -08004398 dumpStaticScreenStats(result);
4399 result.append("\n");
4400
Alec Mouri40189b02019-03-05 15:07:54 -08004401 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4402 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4403 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004404
Dan Stozae77c7662016-05-13 11:37:28 -07004405 dumpBufferingStats(result);
4406
Andy McFadden4803b742012-09-24 19:07:20 -07004407 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004408 * Dump the visible layer list
4409 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004410 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004411 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004412 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4413 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004414 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004415
Chia-I Wu2f884132018-09-13 15:17:58 -07004416 {
Lloyd Pique207def92019-02-28 16:09:52 -08004417 StringAppendF(&result, "Composition layers\n");
4418 mDrawingState.traverseInZOrder([&](Layer* layer) {
4419 auto compositionLayer = layer->getCompositionLayer();
4420 if (compositionLayer) compositionLayer->dump(result);
4421 });
4422 }
4423
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004424 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004425 * Dump Display state
4426 */
4427
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004428 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004429 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004430 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004431 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004432 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004433 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004434 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004435
4436 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004437 * Dump CompositionEngine state
4438 */
4439
4440 mCompositionEngine->dump(result);
4441
4442 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004443 * Dump SurfaceFlinger global state
4444 */
4445
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004446 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004447 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004448 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004449
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004450 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004451
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004452 DebugEGLImageTracker::getInstance()->dump(result);
4453
Dominik Laskowski075d3172018-05-24 15:50:06 -07004454 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004455 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4456 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004457 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4458 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004459 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004460 StringAppendF(&result,
4461 " transaction-flags : %08x\n"
4462 " gpu_to_cpu_unsupported : %d\n",
4463 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004464
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004465 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004466 displayId && getHwComposer().isConnected(*displayId)) {
4467 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004468 StringAppendF(&result,
4469 " refresh-rate : %f fps\n"
4470 " x-dpi : %f\n"
4471 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004472 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4473 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004474 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004475
Yiwei Zhang5434a782018-12-05 18:06:32 -08004476 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004477
Dan Stozae22aec72016-08-01 13:20:59 -07004478 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004479 * Tracing state
4480 */
4481 mTracing.dump(result);
4482 result.append("\n");
4483
4484 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004485 * HWC layer minidump
4486 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004487 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004488 const auto displayId = display->getId();
4489 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004490 continue;
4491 }
4492
Yiwei Zhang5434a782018-12-05 18:06:32 -08004493 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004494 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004495 const sp<DisplayDevice> displayDevice = display;
4496 mCurrentState.traverseInZOrder(
4497 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004498 result.append("\n");
4499 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004500
4501 /*
4502 * Dump HWComposer state
4503 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004504 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004505 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004506 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004507 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004508 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004509 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004510
4511 /*
4512 * Dump gralloc state
4513 */
4514 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4515 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004516
4517 /*
4518 * Dump VrFlinger state if in use.
4519 */
4520 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4521 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004522 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004523 result.append("\n");
4524 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004525
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004526 result.append(mTimeStats->miniDump());
4527 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004528}
4529
Chia-I Wu28f320b2018-05-03 11:02:56 -07004530void SurfaceFlinger::updateColorMatrixLocked() {
4531 mat4 colorMatrix;
4532 if (mGlobalSaturationFactor != 1.0f) {
4533 // Rec.709 luma coefficients
4534 float3 luminance{0.213f, 0.715f, 0.072f};
4535 luminance *= 1.0f - mGlobalSaturationFactor;
4536 mat4 saturationMatrix = mat4(
4537 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4538 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4539 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4540 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4541 );
4542 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4543 } else {
4544 colorMatrix = mClientColorMatrix * mDaltonizer();
4545 }
4546
4547 if (mCurrentState.colorMatrix != colorMatrix) {
4548 mCurrentState.colorMatrix = colorMatrix;
4549 mCurrentState.colorMatrixChanged = true;
4550 setTransactionFlags(eTransactionNeeded);
4551 }
4552}
4553
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004554status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004555#pragma clang diagnostic push
4556#pragma clang diagnostic error "-Wswitch-enum"
4557 switch (static_cast<ISurfaceComposerTag>(code)) {
4558 // These methods should at minimum make sure that the client requested
4559 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004560 case BOOT_FINISHED:
4561 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004562 case CREATE_DISPLAY:
4563 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004564 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004565 case GET_ANIMATION_FRAME_STATS:
4566 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004567 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004568 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004569 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004570 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4571 case SET_AUTO_LOW_LATENCY_MODE:
4572 case GET_GAME_CONTENT_TYPE_SUPPORT:
4573 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004574 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004575 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004576 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004577 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004578 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004579 case NOTIFY_POWER_HINT:
4580 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004581 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4582 IPCThreadState* ipc = IPCThreadState::self();
4583 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4584 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004585 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004586 }
Robert Carr1db73f62016-12-21 12:58:51 -08004587 return OK;
4588 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004589 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004590 IPCThreadState* ipc = IPCThreadState::self();
4591 const int pid = ipc->getCallingPid();
4592 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004593 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4594 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004595 return PERMISSION_DENIED;
4596 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004597 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004598 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004599 // Used by apps to hook Choreographer to SurfaceFlinger.
4600 case CREATE_DISPLAY_EVENT_CONNECTION:
4601 // The following calls are currently used by clients that do not
4602 // request necessary permissions. However, they do not expose any secret
4603 // information, so it is OK to pass them.
4604 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004605 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004606 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004607 case GET_PHYSICAL_DISPLAY_IDS:
4608 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004609 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004610 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004611 case GET_DISPLAY_CONFIGS:
4612 case GET_DISPLAY_STATS:
4613 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4614 // Calling setTransactionState is safe, because you need to have been
4615 // granted a reference to Client* and Handle* to do anything with it.
4616 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004617 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004618 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004619 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004620 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004621 case IS_WIDE_COLOR_DISPLAY:
4622 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4623 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004624 return OK;
4625 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004626 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004627 case CAPTURE_SCREEN:
4628 case ADD_REGION_SAMPLING_LISTENER:
4629 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004630 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004631 IPCThreadState* ipc = IPCThreadState::self();
4632 const int pid = ipc->getCallingPid();
4633 const int uid = ipc->getCallingUid();
4634 if ((uid != AID_GRAPHICS) &&
4635 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4636 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4637 return PERMISSION_DENIED;
4638 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004639 return OK;
4640 }
4641 // The following codes are deprecated and should never be allowed to access SF.
4642 case CONNECT_DISPLAY_UNUSED:
4643 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4644 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4645 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004646 }
chaviw93df2ea2019-04-30 16:45:12 -07004647 case CAPTURE_SCREEN_BY_ID: {
4648 IPCThreadState* ipc = IPCThreadState::self();
4649 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004650 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004651 return OK;
4652 }
4653 return PERMISSION_DENIED;
4654 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004655 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004656
4657 // These codes are used for the IBinder protocol to either interrogate the recipient
4658 // side of the transaction for its canonical interface descriptor or to dump its state.
4659 // We let them pass by default.
4660 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4661 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4662 code == IBinder::SYSPROPS_TRANSACTION) {
4663 return OK;
4664 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004665 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004666 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004667 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004668 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4669 return OK;
4670 }
4671 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4672 return PERMISSION_DENIED;
4673#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004674}
4675
Ana Krulec13be8ad2018-08-21 02:43:56 +00004676status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4677 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004678 status_t credentialCheck = CheckTransactCodeCredentials(code);
4679 if (credentialCheck != OK) {
4680 return credentialCheck;
4681 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004682
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004683 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4684 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004685 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004686 IPCThreadState* ipc = IPCThreadState::self();
4687 const int uid = ipc->getCallingUid();
4688 if (CC_UNLIKELY(uid != AID_SYSTEM
4689 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004690 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004691 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004692 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004693 return PERMISSION_DENIED;
4694 }
4695 int n;
4696 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004697 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004698 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004699 return NO_ERROR;
4700 case 1002: // SHOW_UPDATES
4701 n = data.readInt32();
4702 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004703 invalidateHwcGeometry();
4704 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004705 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004706 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004707 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004708 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004709 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004710 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004711 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004712 setTransactionFlags(
4713 eTransactionNeeded|
4714 eDisplayTransactionNeeded|
4715 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004716 return NO_ERROR;
4717 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004718 case 1006:{ // send empty update
4719 signalRefresh();
4720 return NO_ERROR;
4721 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004722 case 1008: // toggle use of hw composer
4723 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004724 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004725 invalidateHwcGeometry();
4726 repaintEverything();
4727 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004728 case 1009: // toggle use of transform hint
4729 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004730 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004731 invalidateHwcGeometry();
4732 repaintEverything();
4733 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004734 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004735 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004736 reply->writeInt32(0);
4737 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004738 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004739 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004740 return NO_ERROR;
4741 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004742 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004743 if (!display) {
4744 return NAME_NOT_FOUND;
4745 }
4746
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004747 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004748 return NO_ERROR;
4749 }
4750 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004751 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004752 // daltonize
4753 n = data.readInt32();
4754 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004755 case 1:
4756 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4757 break;
4758 case 2:
4759 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4760 break;
4761 case 3:
4762 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4763 break;
4764 default:
4765 mDaltonizer.setType(ColorBlindnessType::None);
4766 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004767 }
4768 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004769 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004770 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004771 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004772 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004773
4774 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004775 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004776 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004777 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004778 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004779 // apply a color matrix
4780 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004781 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004782 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004783 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004784 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004785 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004786 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004787 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004788 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004789 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004790 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004791
4792 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4793 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004794 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004795 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4796 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4797 }
4798
Chia-I Wu28f320b2018-05-03 11:02:56 -07004799 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004800 return NO_ERROR;
4801 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004802 case 1016: { // Unused.
4803 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004804 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004805 case 1017: {
4806 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004807 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004808 return NO_ERROR;
4809 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004810 case 1018: { // Modify Choreographer's phase offset
4811 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004812 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004813 return NO_ERROR;
4814 }
4815 case 1019: { // Modify SurfaceFlinger's phase offset
4816 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004817 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004818 return NO_ERROR;
4819 }
Irvel468051e2016-06-13 16:44:44 -07004820 case 1020: { // Layer updates interceptor
4821 n = data.readInt32();
4822 if (n) {
4823 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004824 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004825 }
4826 else{
4827 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004828 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004829 }
4830 return NO_ERROR;
4831 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004832 case 1021: { // Disable HWC virtual displays
4833 n = data.readInt32();
4834 mUseHwcVirtualDisplays = !n;
4835 return NO_ERROR;
4836 }
Romain Guy0147a172017-06-01 13:53:56 -07004837 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004838 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004839 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004840
Chia-I Wu28f320b2018-05-03 11:02:56 -07004841 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004842 return NO_ERROR;
4843 }
Romain Guy54f154a2017-10-24 21:40:32 +01004844 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004845 int32_t colorMode;
4846
Chia-I Wu0d711262018-05-21 15:19:35 -07004847 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004848 if (data.readInt32(&colorMode) == NO_ERROR) {
4849 mForceColorMode = static_cast<ColorMode>(colorMode);
4850 }
Romain Guy54f154a2017-10-24 21:40:32 +01004851 invalidateHwcGeometry();
4852 repaintEverything();
4853 return NO_ERROR;
4854 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004855 // Deprecate, use 1030 to check whether the device is color managed.
4856 case 1024: {
4857 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004858 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004859 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004860 n = data.readInt32();
4861 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004862 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004863 Mutex::Autolock lock(mStateLock);
4864 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004865 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004866 reply->writeInt32(NO_ERROR);
4867 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004868 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004869 bool writeFile = false;
4870 {
4871 Mutex::Autolock lock(mStateLock);
4872 mTracingEnabledChanged = true;
4873 writeFile = mTracing.disable();
4874 }
4875
4876 if (writeFile) {
4877 reply->writeInt32(mTracing.writeToFile());
4878 } else {
4879 reply->writeInt32(NO_ERROR);
4880 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004881 }
4882 return NO_ERROR;
4883 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004884 case 1026: { // Get layer tracing status
4885 reply->writeBool(mTracing.isEnabled());
4886 return NO_ERROR;
4887 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004888 // Is a DisplayColorSetting supported?
4889 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004890 const auto display = getDefaultDisplayDevice();
4891 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004892 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004893 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004894
4895 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4896 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004897 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004898 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004899 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004900 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004901 reply->writeBool(true);
4902 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004903 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004904 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004905 break;
4906 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004907 reply->writeBool(
4908 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004909 break;
4910 }
4911 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004912 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004913 // Is VrFlinger active?
4914 case 1028: {
4915 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004916 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004917 return NO_ERROR;
4918 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004919 // Set buffer size for SF tracing (value in KB)
4920 case 1029: {
4921 n = data.readInt32();
4922 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4923 ALOGW("Invalid buffer size: %d KB", n);
4924 reply->writeInt32(BAD_VALUE);
4925 return BAD_VALUE;
4926 }
4927
4928 ALOGD("Updating trace buffer to %d KB", n);
4929 mTracing.setBufferSize(n * 1024);
4930 reply->writeInt32(NO_ERROR);
4931 return NO_ERROR;
4932 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004933 // Is device color managed?
4934 case 1030: {
4935 reply->writeBool(useColorManagement);
4936 return NO_ERROR;
4937 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004938 // Override default composition data space
4939 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4940 // && adb shell stop zygote && adb shell start zygote
4941 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4942 // adb shell stop zygote && adb shell start zygote
4943 case 1031: {
4944 Mutex::Autolock _l(mStateLock);
4945 n = data.readInt32();
4946 if (n) {
4947 n = data.readInt32();
4948 if (n) {
4949 Dataspace dataspace = static_cast<Dataspace>(n);
4950 if (!validateCompositionDataspace(dataspace)) {
4951 return BAD_VALUE;
4952 }
4953 mDefaultCompositionDataspace = dataspace;
4954 }
4955 n = data.readInt32();
4956 if (n) {
4957 Dataspace dataspace = static_cast<Dataspace>(n);
4958 if (!validateCompositionDataspace(dataspace)) {
4959 return BAD_VALUE;
4960 }
4961 mWideColorGamutCompositionDataspace = dataspace;
4962 }
4963 } else {
4964 // restore composition data space.
4965 mDefaultCompositionDataspace = defaultCompositionDataspace;
4966 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4967 }
4968 return NO_ERROR;
4969 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004970 // Set trace flags
4971 case 1033: {
4972 n = data.readUint32();
4973 ALOGD("Updating trace flags to 0x%x", n);
4974 mTracing.setTraceFlags(n);
4975 reply->writeInt32(NO_ERROR);
4976 return NO_ERROR;
4977 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004978 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004979 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004980 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004981 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08004982 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
4983 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08004984 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004985 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004986 } else {
4987 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004988 }
4989 return NO_ERROR;
4990 }
Ady Abraham34392f72019-04-10 11:29:27 -07004991 case 1035: {
4992 n = data.readInt32();
4993 mDebugDisplayConfigSetByBackdoor = false;
4994 if (n >= 0) {
4995 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004996 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07004997 if (result != NO_ERROR) {
4998 return result;
4999 }
5000 mDebugDisplayConfigSetByBackdoor = true;
5001 }
5002 return NO_ERROR;
5003 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08005004 }
5005 }
5006 return err;
5007}
5008
Steven Thomas6d8110b2017-08-31 18:24:21 -07005009void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07005010 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07005011 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07005012}
5013
Ana Krulec7d1d6832018-12-27 11:10:09 -08005014void SurfaceFlinger::repaintEverythingForHWC() {
5015 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07005016 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08005017}
5018
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005019// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
5020class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005021public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005022 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5023 ~WindowDisconnector() {
5024 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005025 }
5026
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005027private:
5028 ANativeWindow* mWindow;
5029 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005030};
5031
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005032status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005033 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005034 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5035 const Rect& sourceCrop, uint32_t reqWidth,
5036 uint32_t reqHeight, bool useIdentityTransform,
5037 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005038 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005039
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005040 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005041
Dominik Laskowski718f9602019-11-09 20:01:35 -08005042 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5043 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5044 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5045 renderAreaRotation = ui::Transform::ROT_0;
5046 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005047
Chia-I Wu20261cb2018-08-23 12:55:44 -07005048 sp<DisplayDevice> display;
5049 {
5050 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005051
Chia-I Wu20261cb2018-08-23 12:55:44 -07005052 display = getDisplayDeviceLocked(displayToken);
5053 if (!display) return BAD_VALUE;
5054
Chia-I Wucb023152018-08-28 12:57:23 -07005055 // set the requested width/height to the logical display viewport size
5056 // by default
5057 if (reqWidth == 0 || reqHeight == 0) {
5058 reqWidth = uint32_t(display->getViewport().width());
5059 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005060 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005061 }
5062
Peiyong Lin0e003c92018-09-17 11:09:51 -07005063 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005064 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005065
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005066 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5067 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005068 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005069 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005070}
5071
chaviw93df2ea2019-04-30 16:45:12 -07005072static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5073 switch (colorMode) {
5074 case ColorMode::DISPLAY_P3:
5075 case ColorMode::BT2100_PQ:
5076 case ColorMode::BT2100_HLG:
5077 case ColorMode::DISPLAY_BT2020:
5078 return Dataspace::DISPLAY_P3;
5079 default:
5080 return Dataspace::V0_SRGB;
5081 }
5082}
5083
5084const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5085 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5086 if (displayToken) {
5087 return getDisplayDeviceLocked(displayToken);
5088 }
5089 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5090 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005091 return getDisplayByLayerStack(displayOrLayerStack);
5092}
5093
5094const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005095 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005096 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005097 return display;
5098 }
5099 }
5100 return nullptr;
5101}
5102
5103status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5104 sp<GraphicBuffer>* outBuffer) {
5105 sp<DisplayDevice> display;
5106 uint32_t width;
5107 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005108 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005109 {
5110 Mutex::Autolock _l(mStateLock);
5111 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5112 if (!display) {
5113 return BAD_VALUE;
5114 }
5115
5116 width = uint32_t(display->getViewport().width());
5117 height = uint32_t(display->getViewport().height());
5118
Dominik Laskowski718f9602019-11-09 20:01:35 -08005119 const auto orientation = display->getOrientation();
5120 captureOrientation = ui::Transform::toRotationFlags(orientation);
5121
5122 switch (captureOrientation) {
5123 case ui::Transform::ROT_90:
5124 captureOrientation = ui::Transform::ROT_270;
5125 break;
5126
5127 case ui::Transform::ROT_270:
5128 captureOrientation = ui::Transform::ROT_90;
5129 break;
5130
5131 case ui::Transform::ROT_INVALID:
5132 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5133 captureOrientation = ui::Transform::ROT_0;
5134 break;
5135
5136 default:
5137 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005138 }
chaviw93df2ea2019-04-30 16:45:12 -07005139 *outDataspace =
5140 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5141 }
5142
5143 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5144 false /* captureSecureLayers */);
5145
5146 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5147 std::placeholders::_1);
5148 bool ignored = false;
5149 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5150 false /* useIdentityTransform */,
5151 ignored /* outCapturedSecureLayers */);
5152}
5153
Robert Carr866455f2019-04-02 16:28:26 -07005154status_t SurfaceFlinger::captureLayers(
5155 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5156 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5157 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5158 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005159 ATRACE_CALL();
5160
5161 class LayerRenderArea : public RenderArea {
5162 public:
Robert Carr578038f2018-03-09 12:25:24 -08005163 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005164 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005165 bool childrenOnly, const Rect& displayViewport)
5166 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005167 mLayer(layer),
5168 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005169 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005170 mFlinger(flinger),
5171 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005172 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005173 Rect getBounds() const override {
5174 const Layer::State& layerState(mLayer->getDrawingState());
5175 return mLayer->getBufferSize(layerState);
5176 }
Marissa Wall61c58622018-07-18 10:12:20 -07005177 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005178 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005179 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005180 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005181 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005182 }
chaviwa76b2712017-09-20 12:02:26 -07005183 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005184 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005185 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005186 Rect getSourceCrop() const override {
5187 if (mCrop.isEmpty()) {
5188 return getBounds();
5189 } else {
5190 return mCrop;
5191 }
5192 }
Robert Carr578038f2018-03-09 12:25:24 -08005193 class ReparentForDrawing {
5194 public:
5195 const sp<Layer>& oldParent;
5196 const sp<Layer>& newParent;
5197
Vishnu Nair4351ad52019-02-11 14:13:02 -08005198 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5199 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005200 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005201 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005202 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5203 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005204 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005205 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005206 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005207 };
5208
5209 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005210 const Rect sourceCrop = getSourceCrop();
5211 // no need to check rotation because there is none
5212 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5213 sourceCrop.height() != getReqHeight();
5214
Robert Carr578038f2018-03-09 12:25:24 -08005215 if (!mChildrenOnly) {
5216 mTransform = mLayer->getTransform().inverse();
5217 drawLayers();
5218 } else {
5219 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005220 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5221 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005222 // In the "childrenOnly" case we reparent the children to a screenshot
5223 // layer which has no properties set and which does not draw.
5224 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005225 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5226 "Screenshot Parent"s, w, h, 0,
5227 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005228
Vishnu Nair4351ad52019-02-11 14:13:02 -08005229 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005230 drawLayers();
5231 }
5232 }
chaviwa76b2712017-09-20 12:02:26 -07005233
chaviwa76b2712017-09-20 12:02:26 -07005234 private:
chaviw7206d492017-11-10 16:16:12 -08005235 const sp<Layer> mLayer;
5236 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005237
Peiyong Linefefaac2018-08-17 12:27:51 -07005238 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005239 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005240
5241 SurfaceFlinger* mFlinger;
5242 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005243 };
5244
Robert Carrc0df3122019-04-11 13:18:21 -07005245 int reqWidth = 0;
5246 int reqHeight = 0;
5247 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005248 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005249 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005250 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005251 {
5252 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005253
Robert Carrc0df3122019-04-11 13:18:21 -07005254 parent = fromHandle(layerHandleBinder);
5255 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5256 ALOGE("captureLayers called with an invalid or removed parent");
5257 return NAME_NOT_FOUND;
5258 }
5259
5260 const int uid = IPCThreadState::self()->getCallingUid();
5261 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5262 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5263 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5264 return PERMISSION_DENIED;
5265 }
5266
Vishnu Nairefc42e22019-12-03 17:36:12 -08005267 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005268 if (sourceCrop.width() <= 0) {
5269 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005270 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005271 }
5272
5273 if (sourceCrop.height() <= 0) {
5274 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005275 crop.bottom = parentSourceBounds.getHeight();
5276 }
5277
5278 if (crop.isEmpty() || frameScale <= 0.0f) {
5279 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5280 // crop was not specified, or an invalid frame scale was provided.
5281 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005282 }
5283 reqWidth = crop.width() * frameScale;
5284 reqHeight = crop.height() * frameScale;
5285
5286 for (const auto& handle : excludeHandles) {
5287 sp<Layer> excludeLayer = fromHandle(handle);
5288 if (excludeLayer != nullptr) {
5289 excludeLayers.emplace(excludeLayer);
5290 } else {
5291 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5292 return NAME_NOT_FOUND;
5293 }
5294 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005295
5296 auto display = getDisplayByLayerStack(parent->getLayerStack());
5297 if (!display) {
5298 return BAD_VALUE;
5299 }
5300
5301 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005302 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005303
Chia-I Wu20261cb2018-08-23 12:55:44 -07005304 // really small crop or frameScale
5305 if (reqWidth <= 0) {
5306 reqWidth = 1;
5307 }
5308 if (reqHeight <= 0) {
5309 reqHeight = 1;
5310 }
5311
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005312 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5313 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005314 auto traverseLayers = [parent, childrenOnly,
5315 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005316 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5317 if (!layer->isVisible()) {
5318 return;
Robert Carr578038f2018-03-09 12:25:24 -08005319 } else if (childrenOnly && layer == parent.get()) {
5320 return;
chaviwa76b2712017-09-20 12:02:26 -07005321 }
Robert Carr866455f2019-04-02 16:28:26 -07005322
5323 sp<Layer> p = layer;
5324 while (p != nullptr) {
5325 if (excludeLayers.count(p) != 0) {
5326 return;
5327 }
5328 p = p->getParent();
5329 }
5330
chaviwa76b2712017-09-20 12:02:26 -07005331 visitor(layer);
5332 });
5333 };
Robert Carr108b2c72019-04-02 16:32:58 -07005334
5335 bool outCapturedSecureLayers = false;
5336 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5337 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005338}
5339
5340status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5341 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005342 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005343 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005344 bool useIdentityTransform,
5345 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005346 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005347
Peiyong Lin0e003c92018-09-17 11:09:51 -07005348 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005349 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5350 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005351 *outBuffer =
5352 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5353 static_cast<android_pixel_format>(reqPixelFormat), 1,
5354 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005355
Robert Carr108b2c72019-04-02 16:32:58 -07005356 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5357 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005358}
5359
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005360status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5361 TraverseLayersFunction traverseLayers,
5362 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005363 bool useIdentityTransform,
5364 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005365 // This mutex protects syncFd and captureResult for communication of the return values from the
5366 // main thread back to this Binder thread
5367 std::mutex captureMutex;
5368 std::condition_variable captureCondition;
5369 std::unique_lock<std::mutex> captureLock(captureMutex);
5370 int syncFd = -1;
5371 std::optional<status_t> captureResult;
5372
Robert Carr03480e22018-01-04 16:02:06 -08005373 const int uid = IPCThreadState::self()->getCallingUid();
5374 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5375
Dominik Laskowski8c001672018-05-30 16:52:06 -07005376 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005377 // If there is a refresh pending, bug out early and tell the binder thread to try again
5378 // after the refresh.
5379 if (mRefreshPending) {
5380 ATRACE_NAME("Skipping screenshot for now");
5381 std::unique_lock<std::mutex> captureLock(captureMutex);
5382 captureResult = std::make_optional<status_t>(EAGAIN);
5383 captureCondition.notify_one();
5384 return;
5385 }
5386
5387 status_t result = NO_ERROR;
5388 int fd = -1;
5389 {
5390 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005391 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005392 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005393 useIdentityTransform, forSystem, &fd,
5394 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005395 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005396 }
5397
5398 {
5399 std::unique_lock<std::mutex> captureLock(captureMutex);
5400 syncFd = fd;
5401 captureResult = std::make_optional<status_t>(result);
5402 captureCondition.notify_one();
5403 }
5404 });
5405
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005406 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005407 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005408 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005409 while (*captureResult == EAGAIN) {
5410 captureResult.reset();
5411 result = postMessageAsync(message);
5412 if (result != NO_ERROR) {
5413 return result;
5414 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005415 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005416 }
5417 result = *captureResult;
5418 }
5419
5420 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005421 sync_wait(syncFd, -1);
5422 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005423 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005424
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005425 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005426}
5427
chaviwa76b2712017-09-20 12:02:26 -07005428void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005429 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005430 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5431 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005432 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005433
chaviwa76b2712017-09-20 12:02:26 -07005434 const auto reqWidth = renderArea.getReqWidth();
5435 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005436 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005437 const auto transform = renderArea.getTransform();
5438 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005439 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005440
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005441 renderengine::DisplaySettings clientCompositionDisplay;
Vishnu Nair9b079a22020-01-21 14:36:08 -08005442 std::vector<compositionengine::LayerFE::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005443
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005444 // assume that bounds are never offset, and that they are the same as the
5445 // buffer bounds.
5446 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005447 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005448 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005449
5450 // Now take into account the rotation flag. We append a transform that
5451 // rotates the layer stack about the origin, then translate by buffer
5452 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005453 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005454 int displacementX = 0;
5455 int displacementY = 0;
5456 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5457 switch (rotation) {
5458 case ui::Transform::ROT_90:
5459 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005460 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005461 break;
5462 case ui::Transform::ROT_180:
5463 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005464 displacementY = renderArea.getBounds().getWidth();
5465 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005466 break;
5467 case ui::Transform::ROT_270:
5468 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005469 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005470 break;
5471 default:
5472 break;
5473 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005474
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005475 // We need to transform the clipping window into the right spot.
5476 // First, rotate the clipping rectangle by the rotation hint to get the
5477 // right orientation
5478 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5479 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5480 const vec4 rotClipTL = rotMatrix * clipTL;
5481 const vec4 rotClipBR = rotMatrix * clipBR;
5482 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5483 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5484 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5485 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5486
5487 // Now reposition the clipping rectangle with the displacement vector
5488 // computed above.
5489 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005490 clientCompositionDisplay.clip =
5491 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5492 newClipRight + displacementX, newClipBottom + displacementY);
5493
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005494 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005495 clientCompositionDisplay.globalTransform =
5496 clipTransform * clientCompositionDisplay.globalTransform;
5497
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005498 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5499 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005500
chaviw50da5042018-04-09 13:49:37 -07005501 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005502
Vishnu Nair9b079a22020-01-21 14:36:08 -08005503 compositionengine::LayerFE::LayerSettings fillLayer;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005504 fillLayer.source.buffer.buffer = nullptr;
5505 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5506 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5507 fillLayer.alpha = half(alpha);
5508 clientCompositionLayers.push_back(fillLayer);
5509
5510 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005511 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005512 const bool supportProtectedContent = false;
5513 Region clip(renderArea.getBounds());
5514 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5515 clip,
5516 useIdentityTransform,
5517 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5518 renderArea.isSecure(),
5519 supportProtectedContent,
5520 clearRegion,
5521 };
5522 auto result = layer->prepareClientComposition(targetSettings);
5523 if (result) {
Vishnu Nair9b079a22020-01-21 14:36:08 -08005524 std::optional<compositionengine::LayerFE::LayerSettings> shadowLayer =
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005525 layer->prepareShadowClientComposition(*result, displayViewport,
5526 clientCompositionDisplay.outputDataspace);
5527 if (shadowLayer) {
5528 clientCompositionLayers.push_back(*shadowLayer);
5529 }
Lloyd Piquef16688f2019-02-19 17:47:57 -08005530 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005531 }
chaviwa76b2712017-09-20 12:02:26 -07005532 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005533
Vishnu Nair9b079a22020-01-21 14:36:08 -08005534 std::vector<const renderengine::LayerSettings*> clientCompositionLayerPointers;
5535 clientCompositionLayers.reserve(clientCompositionLayers.size());
5536 std::transform(clientCompositionLayers.begin(), clientCompositionLayers.end(),
5537 std::back_inserter(clientCompositionLayerPointers),
5538 [](compositionengine::LayerFE::LayerSettings& settings)
5539 -> renderengine::LayerSettings* { return &settings; });
5540
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005541 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005542 // Use an empty fence for the buffer fence, since we just created the buffer so
5543 // there is no need for synchronization with the GPU.
5544 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005545 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005546 getRenderEngine().useProtectedContext(false);
Vishnu Nair9b079a22020-01-21 14:36:08 -08005547 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayerPointers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005548 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005549
5550 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005551}
5552
chaviwa76b2712017-09-20 12:02:26 -07005553status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5554 TraverseLayersFunction traverseLayers,
5555 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005556 bool useIdentityTransform, bool forSystem,
5557 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005558 ATRACE_CALL();
5559
chaviwa76b2712017-09-20 12:02:26 -07005560 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005561 outCapturedSecureLayers =
5562 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005563 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005564
Robert Carr03480e22018-01-04 16:02:06 -08005565 // We allow the system server to take screenshots of secure layers for
5566 // use in situations like the Screen-rotation animation and place
5567 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005568 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005569 ALOGW("FB is protected: PERMISSION_DENIED");
5570 return PERMISSION_DENIED;
5571 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005572 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005573 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005574}
5575
chaviw95ef3c42019-02-14 10:55:09 -08005576void SurfaceFlinger::setInputWindowsFinished() {
5577 Mutex::Autolock _l(mStateLock);
5578
5579 mPendingSyncInputWindows = false;
5580 mTransactionCV.broadcast();
5581}
chaviw5f21a5e2019-02-14 10:00:34 -08005582
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005583// ---------------------------------------------------------------------------
5584
Edgar Arriaga844fa672020-01-16 14:21:42 -08005585void SurfaceFlinger::State::traverse(const LayerVector::Visitor& visitor) const {
5586 layersSortedByZ.traverse(visitor);
5587}
5588
Dan Stoza412903f2017-04-27 13:42:17 -07005589void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5590 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005591}
5592
Dan Stoza412903f2017-04-27 13:42:17 -07005593void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5594 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005595}
5596
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005597void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005598 const LayerVector::Visitor& visitor) {
5599 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005600 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005601 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005602 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005603 continue;
5604 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005605 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005606 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005607 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005608 return;
5609 }
chaviwa76b2712017-09-20 12:02:26 -07005610 if (!layer->isVisible()) {
5611 return;
5612 }
5613 visitor(layer);
5614 });
5615 }
5616}
5617
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005618status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5619 HwcConfigIndexType defaultConfig,
5620 float minRefreshRate,
5621 float maxRefreshRate) {
5622 Mutex::Autolock lock(mStateLock);
5623
Dominik Laskowski22488f62019-03-28 09:53:04 -07005624 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005625 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5626 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5627 // it should go thru setDesiredActiveConfig, similar to primary display.
5628 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5629 const auto displayId = display->getId();
5630 LOG_ALWAYS_FATAL_IF(!displayId);
5631
5632 HWC2::VsyncPeriodChangeConstraints constraints;
5633 constraints.desiredTimeNanos = systemTime();
5634 constraints.seamlessRequired = false;
5635
5636 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005637 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5638 constraints, &timeline) < 0) {
5639 return BAD_VALUE;
5640 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005641 if (timeline.refreshRequired) {
5642 repaintEverythingForHWC();
5643 }
5644
Ady Abrahamdfa37362020-01-21 18:02:39 -08005645 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005646 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005647 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5648 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005649 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005650 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005651 }
5652
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005653 if (mDebugDisplayConfigSetByBackdoor) {
5654 // ignore this request as config is overridden by backdoor
5655 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005656 }
5657
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005658 bool policyChanged;
5659 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5660 &policyChanged) < 0) {
5661 return BAD_VALUE;
5662 }
5663 if (!policyChanged) {
5664 return NO_ERROR;
5665 }
5666
5667 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5668 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005669
5670 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5671 // that listeners that care about a change in allowed configs can get the notification.
5672 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005673 const nsecs_t vsyncPeriod =
5674 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005675 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005676 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005677
Ana Krulec8c6f3f62020-01-23 15:48:01 -08005678 auto configId = mScheduler->getPreferredConfigId();
5679 auto preferredRefreshRate = configId
5680 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5681 // NOTE: Choose the default config ID, if Scheduler doesn't have one in mind.
5682 : mRefreshRateConfigs->getRefreshRateFromConfigId(defaultConfig);
5683 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5684 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5685
5686 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5687 ALOGV("switching to Scheduler preferred config %d", preferredRefreshRate.configId.value());
5688 setDesiredActiveConfig({preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
Ady Abraham2139f732019-11-13 18:56:40 -08005689 } else {
Ana Krulec8c6f3f62020-01-23 15:48:01 -08005690 LOG_ALWAYS_FATAL("Desired config not allowed: %d", preferredRefreshRate.configId.value());
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005691 }
5692
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005693 return NO_ERROR;
5694}
5695
Ana Krulec0782b882019-10-15 17:34:54 -07005696status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005697 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005698 float maxRefreshRate) {
5699 ATRACE_CALL();
5700
5701 if (!displayToken) {
5702 return BAD_VALUE;
5703 }
5704
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005705 status_t result = NO_ERROR;
5706
Ana Krulec234bb162019-11-10 22:55:55 +01005707 postMessageSync(new LambdaMessage([&]() {
5708 const auto display = getDisplayDeviceLocked(displayToken);
5709 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005710 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005711 ALOGE("Attempt to set desired display configs for invalid display token %p",
5712 displayToken.get());
5713 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005714 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005715 ALOGW("Attempt to set desired display configs for virtual display");
5716 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005717 result =
5718 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5719 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005720 }
5721 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005722
5723 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005724}
5725
5726status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005727 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005728 float* outMinRefreshRate,
5729 float* outMaxRefreshRate) {
5730 ATRACE_CALL();
5731
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005732 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005733 return BAD_VALUE;
5734 }
5735
5736 Mutex::Autolock lock(mStateLock);
5737 const auto display = getDisplayDeviceLocked(displayToken);
5738 if (!display) {
5739 return NAME_NOT_FOUND;
5740 }
5741
5742 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005743 HwcConfigIndexType defaultConfig;
5744 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5745 *outDefaultConfig = defaultConfig.value();
5746 return NO_ERROR;
5747 } else if (display->isVirtual()) {
5748 return BAD_VALUE;
5749 } else {
5750 const auto displayId = display->getId();
5751 if (!displayId) {
5752 return BAD_VALUE;
5753 }
5754 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5755 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5756 *outMinRefreshRate = 1e9f / vsyncPeriod;
5757 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5758 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005759 }
Ana Krulec0782b882019-10-15 17:34:54 -07005760}
5761
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005762void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005763 mFlinger->setInputWindowsFinished();
5764}
5765
Robert Carrc0df3122019-04-11 13:18:21 -07005766sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005767 BBinder* b = nullptr;
5768 if (handle) {
5769 b = handle->localBinder();
5770 }
Robert Carrc0df3122019-04-11 13:18:21 -07005771 if (b == nullptr) {
5772 return nullptr;
5773 }
5774 auto it = mLayersByLocalBinderToken.find(b);
5775 if (it != mLayersByLocalBinderToken.end()) {
5776 return it->second.promote();
5777 }
5778 return nullptr;
5779}
5780
Dominik Laskowski75848362019-11-11 17:57:20 -08005781void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005782 mNumLayers++;
5783 mScheduler->registerLayer(layer);
5784}
5785
5786void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5787 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005788 removeFromOffscreenLayers(layer);
5789}
5790
5791// WARNING: ONLY CALL THIS FROM LAYER DTOR
5792// Here we add children in the current state to offscreen layers and remove the
5793// layer itself from the offscreen layer list. Since
5794// this is the dtor, it is safe to access the current state. This keeps us
5795// from dangling children layers such that they are not reachable from the
5796// Drawing state nor the offscreen layer list
5797// See b/141111965
5798void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5799 for (auto& child : layer->getCurrentChildren()) {
5800 mOffscreenLayers.emplace(child.get());
5801 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005802 mOffscreenLayers.erase(layer);
5803}
5804
Alec Mouri4545a8a2019-08-08 20:05:32 -07005805void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5806 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5807}
5808
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005809status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5810 float lightPosY, float lightPosZ,
5811 float lightRadius) {
5812 Mutex::Autolock _l(mStateLock);
5813 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5814 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5815 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5816 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5817 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5818
5819 // these values are overridden when calculating the shadow settings for a layer.
5820 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5821 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005822 return NO_ERROR;
5823}
5824
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005825} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005826
Mathias Agopian3f844832013-08-07 21:24:32 -07005827#if defined(__gl_h_)
5828#error "don't include gl/gl.h in this file"
5829#endif
5830
5831#if defined(__gl2_h_)
5832#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005833#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005834
5835// TODO(b/129481165): remove the #pragma below and fix conversion issues
5836#pragma clang diagnostic pop // ignored "-Wconversion"