blob: b9c95257bada6215aa02f5c7c9221469bdfa7fee [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
Romain Guy11d63f42017-07-20 12:47:14 -0700356 // We should be reading 'persist.sys.sf.color_saturation' here
357 // but since /data may be encrypted, we need to wait until after vold
358 // comes online to attempt to read the property. The property is
359 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800360
361 if (useTrebleTestingOverride()) {
362 // Without the override SurfaceFlinger cannot connect to HIDL
363 // services that are not listed in the manifests. Considered
364 // deriving the setting from the set service name, but it
365 // would be brittle if the name that's not 'default' is used
366 // for production purposes later on.
367 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
368 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800369}
370
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800371void SurfaceFlinger::onFirstRef()
372{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800373 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800374}
375
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700376SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800377
Dan Stozac7014012014-02-14 15:03:43 -0800378void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800379{
380 // the window manager died on us. prepare its eulogy.
381
Andy McFadden13a082e2012-08-24 10:16:42 -0700382 // restore initial conditions (default device unblank, etc)
383 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800384
385 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700386 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800387}
388
Robert Carr1db73f62016-12-21 12:58:51 -0800389static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700390 status_t err = client->initCheck();
391 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800392 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800393 }
Robert Carr1db73f62016-12-21 12:58:51 -0800394 return nullptr;
395}
396
397sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
398 return initClient(new Client(this));
399}
400
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700401sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
402 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700403{
404 class DisplayToken : public BBinder {
405 sp<SurfaceFlinger> flinger;
406 virtual ~DisplayToken() {
407 // no more references, this display must be terminated
408 Mutex::Autolock _l(flinger->mStateLock);
409 flinger->mCurrentState.displays.removeItem(this);
410 flinger->setTransactionFlags(eDisplayTransactionNeeded);
411 }
412 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700413 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700414 : flinger(flinger) {
415 }
416 };
417
418 sp<BBinder> token = new DisplayToken(this);
419
420 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700421 // Display ID is assigned when virtual display is allocated by HWC.
422 DisplayDeviceState state;
423 state.isSecure = secure;
424 state.displayName = displayName;
425 mCurrentState.displays.add(token, state);
426 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700427 return token;
428}
429
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700430void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700431 Mutex::Autolock _l(mStateLock);
432
Dominik Laskowski075d3172018-05-24 15:50:06 -0700433 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
434 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700435 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700436 return;
437 }
438
Dominik Laskowski075d3172018-05-24 15:50:06 -0700439 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
440 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700441 ALOGE("destroyDisplay called for non-virtual display");
442 return;
443 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700444 mInterceptor->saveDisplayDeletion(state.sequenceId);
445 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700446 setTransactionFlags(eDisplayTransactionNeeded);
447}
448
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800449std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
450 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700451
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800452 const auto internalDisplayId = getInternalDisplayIdLocked();
453 if (!internalDisplayId) {
454 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700455 }
456
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800457 std::vector<PhysicalDisplayId> displayIds;
458 displayIds.reserve(mPhysicalDisplayTokens.size());
459 displayIds.push_back(internalDisplayId->value);
460
461 for (const auto& [id, token] : mPhysicalDisplayTokens) {
462 if (id != *internalDisplayId) {
463 displayIds.push_back(id.value);
464 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700465 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700466
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800467 return displayIds;
468}
469
470sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
471 Mutex::Autolock lock(mStateLock);
472 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700473}
474
Ady Abraham37965d42018-11-01 13:43:32 -0700475status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
476 if (!outGetColorManagement) {
477 return BAD_VALUE;
478 }
479 *outGetColorManagement = useColorManagement;
480 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700481}
482
Lloyd Pique441d5042018-10-18 16:49:51 -0700483HWComposer& SurfaceFlinger::getHwComposer() const {
484 return mCompositionEngine->getHwComposer();
485}
486
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700487renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
488 return mCompositionEngine->getRenderEngine();
489}
490
Lloyd Pique70d91362018-10-18 16:02:55 -0700491compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
492 return *mCompositionEngine.get();
493}
494
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800495void SurfaceFlinger::bootFinished()
496{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700497 if (mStartPropertySetThread->join() != NO_ERROR) {
498 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800499 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800500 const nsecs_t now = systemTime();
501 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000502 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700503
Mikael Pessa90092f42019-08-26 17:22:04 -0700504 mFrameTracer->initialize();
Alec Mouri8e2f31b2020-01-16 22:04:35 +0000505 mTimeStats->onBootFinished();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700506
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700507 // wait patiently for the window manager death
508 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700509 mWindowManager = defaultServiceManager()->getService(name);
510 if (mWindowManager != 0) {
511 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700512 }
Robert Carr720e5062018-07-30 17:45:14 -0700513 sp<IBinder> input(defaultServiceManager()->getService(
514 String16("inputflinger")));
515 if (input == nullptr) {
516 ALOGE("Failed to link to input service");
517 } else {
518 mInputFlinger = interface_cast<IInputFlinger>(input);
519 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700520
Steven Thomas050b2c82017-03-06 11:45:16 -0800521 if (mVrFlinger) {
522 mVrFlinger->OnBootFinished();
523 }
524
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700525 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700526 // formerly we would just kill the process, but we now ask it to exit so it
527 // can choose where to stop the animation.
528 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700529
530 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
531 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
532 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700533
Ana Krulecbd6654b2019-02-15 15:18:15 -0800534 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800535 readPersistentProperties();
536 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800537
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700538 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
539 // set the refresh rate according to the policy
Ady Abraham2139f732019-11-13 18:56:40 -0800540 const auto& performanceRefreshRate = mRefreshRateConfigs->getMaxRefreshRateByPolicy();
541 changeRefreshRateLocked(performanceRefreshRate, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800542 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800543 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800544}
545
Dan Stoza436ccf32018-06-21 12:10:12 -0700546uint32_t SurfaceFlinger::getNewTexture() {
547 {
548 std::lock_guard lock(mTexturePoolMutex);
549 if (!mTexturePool.empty()) {
550 uint32_t name = mTexturePool.back();
551 mTexturePool.pop_back();
552 ATRACE_INT("TexturePoolSize", mTexturePool.size());
553 return name;
554 }
555
556 // The pool was too small, so increase it for the future
557 ++mTexturePoolSize;
558 }
559
560 // The pool was empty, so we need to get a new texture name directly using a
561 // blocking call to the main thread
562 uint32_t name = 0;
563 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
564 return name;
565}
566
Mathias Agopian3f844832013-08-07 21:24:32 -0700567void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700568 std::lock_guard lock(mTexturePoolMutex);
569 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
570 // to actually delete this or not based on mTexturePoolSize
571 mTexturePool.push_back(texture);
572 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700573}
574
Wei Wangf9b05ee2017-07-19 20:59:39 -0700575// Do not call property_set on main thread which will be blocked by init
576// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700577void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700578 ALOGI( "SurfaceFlinger's main thread ready to run. "
579 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700580 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800581
Steven Thomasb02664d2017-07-26 18:48:28 -0700582 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700583 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800584 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700585 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
586 renderengine::RenderEngineCreationArgs::Builder()
587 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
588 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
589 .setUseColorManagerment(useColorManagement)
590 .setEnableProtectedContext(enable_protected_contents(false))
591 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800592 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700593 .setContextPriority(useContextPriority
594 ? renderengine::RenderEngine::ContextPriority::HIGH
595 : renderengine::RenderEngine::ContextPriority::MEDIUM)
596 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800597 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700598
599 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
600 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700601 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
602 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800603 // Process any initial hotplug and resulting display changes.
604 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700605 const auto display = getDefaultDisplayDeviceLocked();
606 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700607 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700608 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800609
Steven Thomas050b2c82017-03-06 11:45:16 -0800610 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700611 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700612 // This callback is called from the vr flinger dispatch thread. We
613 // need to call signalTransaction(), which requires holding
614 // mStateLock when we're not on the main thread. Acquiring
615 // mStateLock from the vr flinger dispatch thread might trigger a
616 // deadlock in surface flinger (see b/66916578), so post a message
617 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700618 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700619 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
620 mVrFlingerRequestsDisplay = requestDisplay;
621 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700622 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800623 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700624 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
625 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700626 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700627 .value_or(0),
628 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800629 if (!mVrFlinger) {
630 ALOGE("Failed to start vrflinger");
631 }
632 }
633
Mathias Agopian92a979a2012-08-02 18:32:23 -0700634 // initialize our drawing state
635 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700636
Andy McFadden13a082e2012-08-24 10:16:42 -0700637 // set initial conditions (e.g. unblank default device)
638 initializeDisplays();
639
Steven Thomas137d4bc2019-07-25 16:55:14 -0700640 char primeShaderCache[PROPERTY_VALUE_MAX];
641 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
642 if (atoi(primeShaderCache)) {
643 getRenderEngine().primeCache();
644 }
Dan Stoza4e637772016-07-28 13:31:51 -0700645
Wei Wangf9b05ee2017-07-19 20:59:39 -0700646 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700647
648 const bool presentFenceReliable =
649 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
650 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700651
652 if (mStartPropertySetThread->Start() != NO_ERROR) {
653 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800654 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800655
Dan Stoza9e56aa02015-11-02 13:00:03 -0800656 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700657}
658
Romain Guy11d63f42017-07-20 12:47:14 -0700659void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700660 Mutex::Autolock _l(mStateLock);
661
Romain Guy11d63f42017-07-20 12:47:14 -0700662 char value[PROPERTY_VALUE_MAX];
663
664 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800665 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700666 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800667 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100668
669 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700670 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800671
672 property_get("persist.sys.sf.color_mode", value, "0");
673 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700674}
675
Mathias Agopiana67e4182012-06-19 17:26:12 -0700676void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800677 // Start boot animation service by setting a property mailbox
678 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700679 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800680 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700681 if (mStartPropertySetThread->join() != NO_ERROR) {
682 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800683 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700684}
685
Mathias Agopian875d8e12013-06-07 15:35:48 -0700686size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700687 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700688}
689
Mathias Agopian875d8e12013-06-07 15:35:48 -0700690size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700691 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700692}
693
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800694// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800695
Jamie Gennis582270d2011-08-17 18:19:00 -0700696bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800697 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800698 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800699 return authenticateSurfaceTextureLocked(bufferProducer);
700}
701
702bool SurfaceFlinger::authenticateSurfaceTextureLocked(
703 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800704 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800705 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800706}
707
Brian Anderson6b376712017-04-04 10:51:39 -0700708status_t SurfaceFlinger::getSupportedFrameTimestamps(
709 std::vector<FrameEvent>* outSupported) const {
710 *outSupported = {
711 FrameEvent::REQUESTED_PRESENT,
712 FrameEvent::ACQUIRE,
713 FrameEvent::LATCH,
714 FrameEvent::FIRST_REFRESH_START,
715 FrameEvent::LAST_REFRESH_START,
716 FrameEvent::GPU_COMPOSITION_DONE,
717 FrameEvent::DEQUEUE_READY,
718 FrameEvent::RELEASE,
719 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700720 ConditionalLock _l(mStateLock,
721 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700722 if (!getHwComposer().hasCapability(
723 HWC2::Capability::PresentFenceIsNotReliable)) {
724 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
725 }
726 return NO_ERROR;
727}
728
Dominik Laskowski22488f62019-03-28 09:53:04 -0700729status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
730 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700731 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700732 return BAD_VALUE;
733 }
734
Dominik Laskowski22488f62019-03-28 09:53:04 -0700735 Mutex::Autolock lock(mStateLock);
736
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800737 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700738 if (!displayId) {
739 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700740 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700741
Mathias Agopian8b736f12012-08-13 17:54:26 -0700742 // TODO: Not sure if display density should handled by SF any longer
743 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700744 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700745 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700746 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800747 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700748 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700749 }
750 return density;
751 }
752 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700753 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700754 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700755 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700756 return getDensityFromProperty("ro.sf.lcd_density"); }
757 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700758
Dan Stoza7f7da322014-05-02 15:26:25 -0700759 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700760
Dominik Laskowski075d3172018-05-24 15:50:06 -0700761 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700762 DisplayInfo info = DisplayInfo();
763
Dan Stoza9e56aa02015-11-02 13:00:03 -0800764 float xdpi = hwConfig->getDpiX();
765 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700766
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700767 info.w = hwConfig->getWidth();
768 info.h = hwConfig->getHeight();
769 // Default display viewport to display width and height
770 info.viewportW = info.w;
771 info.viewportH = info.h;
772
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800773 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700774 // The density of the device is provided by a build property
775 float density = Density::getBuildDensity() / 160.0f;
776 if (density == 0) {
777 // the build doesn't provide a density -- this is wrong!
778 // use xdpi instead
779 ALOGE("ro.sf.lcd_density must be defined as a build property");
780 density = xdpi / 160.0f;
781 }
782 if (Density::getEmuDensity()) {
783 // if "qemu.sf.lcd_density" is specified, it overrides everything
784 xdpi = ydpi = density = Density::getEmuDensity();
785 density /= 160.0f;
786 }
787 info.density = density;
788
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700789 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowski718f9602019-11-09 20:01:35 -0800790 info.orientation = display->getOrientation();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700791
792 // This is for screenrecord
793 const Rect viewport = display->getViewport();
794 if (viewport.isValid()) {
795 info.viewportW = uint32_t(viewport.getWidth());
796 info.viewportH = uint32_t(viewport.getHeight());
797 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700798 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700799 } else {
800 // TODO: where should this value come from?
801 static const int TV_DENSITY = 213;
802 info.density = TV_DENSITY / 160.0f;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700803
804 const auto display = getDisplayDeviceLocked(displayToken);
805 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700806 }
807
Dan Stoza7f7da322014-05-02 15:26:25 -0700808 info.xdpi = xdpi;
809 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800810 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham2139f732019-11-13 18:56:40 -0800811
Ady Abraham9e16a482019-12-03 17:19:41 -0800812 const auto offset = mPhaseConfiguration->getOffsetsForRefreshRate(info.fps);
Ady Abraham796beb02019-04-11 15:23:07 -0700813 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800814
Andy McFadden91b2ca82014-06-13 14:04:23 -0700815 // This is how far in advance a buffer must be queued for
816 // presentation at a given time. If you want a buffer to appear
817 // on the screen at time N, you must submit the buffer before
818 // (N - presentationDeadline).
819 //
820 // Normally it's one full refresh period (to give SF a chance to
821 // latch the buffer), but this can be reduced by configuring a
822 // DispSync offset. Any additional delays introduced by the hardware
823 // composer or panel must be accounted for here.
824 //
825 // We add an additional 1ms to allow for processing time and
826 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700827 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700828
829 // All non-virtual displays are currently considered secure.
830 info.secure = true;
831
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800832 if (displayId == getInternalDisplayIdLocked() &&
Dominik Laskowski718f9602019-11-09 20:01:35 -0800833 (internalDisplayOrientation == ui::ROTATION_90 ||
834 internalDisplayOrientation == ui::ROTATION_270)) {
Iris Chang7501ed62018-04-30 14:45:42 +0800835 std::swap(info.w, info.h);
836 }
837
Michael Wright28f24d02016-07-12 13:30:53 -0700838 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700839 }
840
Dan Stoza7f7da322014-05-02 15:26:25 -0700841 return NO_ERROR;
842}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700843
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700844status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
845 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700846 return BAD_VALUE;
847 }
848
Ana Krulecc2870422019-01-29 19:00:58 -0800849 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700850 return NO_ERROR;
851}
852
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700853int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
854 const auto display = getDisplayDevice(displayToken);
855 if (!display) {
856 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800857 return BAD_VALUE;
858 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700859
Steven Thomasc9098452019-09-30 17:15:05 -0700860 if (display->isPrimary()) {
861 std::lock_guard<std::mutex> lock(mActiveConfigLock);
862 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800863 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700864 }
Steven Thomasc9098452019-09-30 17:15:05 -0700865 }
Ady Abraham2139f732019-11-13 18:56:40 -0800866
867 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700868}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700869
Ady Abraham03b02dd2019-03-21 15:40:11 -0700870void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800871 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800872 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
873 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800874
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800875 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800876 // config twice. However event generation config might have changed so we need to update it
877 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800878 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700879 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
880 mDesiredActiveConfig = info;
881 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800882
883 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800884 // This will trigger HWC refresh without resetting the idle timer.
885 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700886 // Start receiving vsync samples now, so that we can detect a period
887 // switch.
Kevin DuBois5988f482020-01-17 09:03:32 -0800888 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham53852a52019-05-28 18:07:44 -0700889 // As we called to set period, we will call to onRefreshRateChangeCompleted once
890 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700891 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800892
Ady Abraham9e16a482019-12-03 17:19:41 -0800893 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
894 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800895 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800896 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700897
898 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800899 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700900 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800901}
902
903status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
904 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800905
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100906 if (!displayToken) {
907 return BAD_VALUE;
908 }
Ady Abraham838de062019-02-04 10:24:03 -0800909
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100910 status_t result = NO_ERROR;
911
912 postMessageSync(new LambdaMessage([&]() {
913 const auto display = getDisplayDeviceLocked(displayToken);
914 if (!display) {
915 ALOGE("Attempt to set allowed display configs for invalid display token %p",
916 displayToken.get());
917 result = BAD_VALUE;
918 } else if (display->isVirtual()) {
919 ALOGW("Attempt to set allowed display configs for virtual display");
920 result = BAD_VALUE;
921 } else {
922 HwcConfigIndexType config(mode);
923 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
924 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
925 refreshRate.fps);
926 }
927 }));
928
929 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800930}
931
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800932void SurfaceFlinger::setActiveConfigInternal() {
933 ATRACE_CALL();
934
Dominik Laskowski22488f62019-03-28 09:53:04 -0700935 const auto display = getDefaultDisplayDeviceLocked();
936 if (!display) {
937 return;
938 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800939
Dominik Laskowski22488f62019-03-28 09:53:04 -0700940 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800941 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700942 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800943 display->setActiveConfig(mUpcomingActiveConfig.configId);
944
Ady Abraham2139f732019-11-13 18:56:40 -0800945 auto refreshRate =
946 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800947 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
948 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800949 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700950
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800951 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700952 const nsecs_t vsyncPeriod =
953 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
954 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800955 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700956 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800957 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800958}
959
Ady Abraham53852a52019-05-28 18:07:44 -0700960void SurfaceFlinger::desiredActiveConfigChangeDone() {
961 std::lock_guard<std::mutex> lock(mActiveConfigLock);
962 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
963 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700964
Kevin DuBois5988f482020-01-17 09:03:32 -0800965 auto const refreshRate =
Ady Abraham2139f732019-11-13 18:56:40 -0800966 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Kevin DuBois5988f482020-01-17 09:03:32 -0800967 mScheduler->resyncToHardwareVsync(true, refreshRate.vsyncPeriod);
Ady Abraham9e16a482019-12-03 17:19:41 -0800968 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
969 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700970}
971
Dominik Laskowski22488f62019-03-28 09:53:04 -0700972bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800973 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800974 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -0800975 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700976 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800977 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700978 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800979 return true;
980 }
981
982 // We received the present fence from the HWC, so we assume it successfully updated
983 // the config, hence we update SF.
984 mCheckPendingFence = false;
985 setActiveConfigInternal();
986 }
987
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800988 // Store the local variable to release the lock.
989 ActiveConfigInfo desiredActiveConfig;
990 {
991 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800992 if (!mDesiredActiveConfigChanged) {
993 return false;
994 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800995 desiredActiveConfig = mDesiredActiveConfig;
996 }
997
Ady Abraham2139f732019-11-13 18:56:40 -0800998 auto refreshRate =
999 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1000 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1001 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001002 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001003 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1004 // display is not valid or we are already in the requested mode
1005 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001006 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001007 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001008 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001009
Ady Abraham838de062019-02-04 10:24:03 -08001010 // Desired active config was set, it is different than the config currently in use, however
1011 // allowed configs might have change by the time we process the refresh.
1012 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001013 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001014 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001015 return false;
1016 }
Alec Mouri7f015182019-07-11 13:56:22 -07001017
Ady Abrahamb838aed2019-02-12 15:30:16 -08001018 mUpcomingActiveConfig = desiredActiveConfig;
1019 const auto displayId = display->getId();
1020 LOG_ALWAYS_FATAL_IF(!displayId);
1021
Ady Abraham2139f732019-11-13 18:56:40 -08001022 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001023
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001024 // TODO(b/142753666) use constrains
1025 HWC2::VsyncPeriodChangeConstraints constraints;
1026 constraints.desiredTimeNanos = systemTime();
1027 constraints.seamlessRequired = false;
1028
1029 HWC2::VsyncPeriodChangeTimeline outTimeline;
1030 auto status =
1031 getHwComposer().setActiveConfigWithConstraints(*displayId,
1032 mUpcomingActiveConfig.configId.value(),
1033 constraints, &outTimeline);
1034 if (status != NO_ERROR) {
1035 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1036 return false;
1037 }
1038
1039 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1040 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001041 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001042 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001043}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001044
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001045status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1046 Vector<ColorMode>* outColorModes) {
1047 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001048 return BAD_VALUE;
1049 }
1050
Peiyong Lina52f0292018-03-14 17:26:31 -07001051 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001052 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001053 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001054 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1055
1056 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1057 if (!displayId) {
1058 return NAME_NOT_FOUND;
1059 }
1060
Dominik Laskowski075d3172018-05-24 15:50:06 -07001061 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001062 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001063 }
Michael Wright28f24d02016-07-12 13:30:53 -07001064 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001065
1066 // If it's built-in display and the configuration claims it's not wide color capable,
1067 // filter out all wide color modes. The typical reason why this happens is that the
1068 // hardware is not good enough to support GPU composition of wide color, and thus the
1069 // OEMs choose to disable this capability.
1070 if (isInternalDisplay && !hasWideColorDisplay) {
1071 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1072 isWideColorMode);
1073 } else {
1074 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1075 }
Michael Wright28f24d02016-07-12 13:30:53 -07001076
1077 return NO_ERROR;
1078}
1079
Daniel Solomon42d04562019-01-20 21:03:19 -08001080status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1081 ui::DisplayPrimaries &primaries) {
1082 if (!displayToken) {
1083 return BAD_VALUE;
1084 }
1085
1086 // Currently we only support this API for a single internal display.
1087 if (getInternalDisplayToken() != displayToken) {
1088 return BAD_VALUE;
1089 }
1090
1091 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1092 return NO_ERROR;
1093}
1094
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001095ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1096 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001097 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001098 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001099 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001100}
1101
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001102status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001103 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001104 Vector<ColorMode> modes;
1105 getDisplayColorModes(displayToken, &modes);
1106 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1107 if (mode < ColorMode::NATIVE || !exists) {
1108 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1109 decodeColorMode(mode).c_str(), mode, displayToken.get());
1110 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001111 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001112 const auto display = getDisplayDevice(displayToken);
1113 if (!display) {
1114 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1115 decodeColorMode(mode).c_str(), mode, displayToken.get());
1116 } else if (display->isVirtual()) {
1117 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1118 decodeColorMode(mode).c_str(), mode);
1119 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001120 display->getCompositionDisplay()->setColorProfile(
1121 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1122 RenderIntent::COLORIMETRIC,
1123 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001124 }
1125 }));
1126
Michael Wright28f24d02016-07-12 13:30:53 -07001127 return NO_ERROR;
1128}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001129
Galia Peycheva5492cb52019-10-30 14:13:16 +01001130status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1131 bool* outSupport) const {
1132 Mutex::Autolock _l(mStateLock);
1133
1134 if (!displayToken) {
1135 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1136 return BAD_VALUE;
1137 }
1138 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1139 if (!displayId) {
1140 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1141 displayToken.get());
1142 return NAME_NOT_FOUND;
1143 }
1144 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1145 HWC2::DisplayCapability::AutoLowLatencyMode);
1146 return NO_ERROR;
1147}
1148
1149void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1150 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1151}
1152
1153void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1154 if (!displayToken) {
1155 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1156 return;
1157 }
1158 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1159 if (!displayId) {
1160 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1161 displayToken.get());
1162 return;
1163 }
1164
1165 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1166}
1167
1168status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1169 bool* outSupport) const {
1170 Mutex::Autolock _l(mStateLock);
1171
1172 if (!displayToken) {
1173 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1174 return BAD_VALUE;
1175 }
1176 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1177 if (!displayId) {
1178 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1179 displayToken.get());
1180 return NAME_NOT_FOUND;
1181 }
1182
1183 std::vector<HWC2::ContentType> outSupportedContentTypes;
1184 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1185 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1186 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1187 return NO_ERROR;
1188}
1189
1190void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1191 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1192}
1193
1194void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1195 if (!displayToken) {
1196 ALOGE("setGameContentType() failed. Missing display token.");
1197 return;
1198 }
1199 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1200 if (!displayId) {
1201 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1202 displayToken.get());
1203 return;
1204 }
1205
1206 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1207 getHwComposer().setContentType(*displayId, type);
1208}
1209
Svetoslavd85084b2014-03-20 10:28:31 -07001210status_t SurfaceFlinger::clearAnimationFrameStats() {
1211 Mutex::Autolock _l(mStateLock);
1212 mAnimFrameTracker.clearStats();
1213 return NO_ERROR;
1214}
1215
1216status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1217 Mutex::Autolock _l(mStateLock);
1218 mAnimFrameTracker.getStats(outStats);
1219 return NO_ERROR;
1220}
1221
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001222status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1223 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001224 Mutex::Autolock _l(mStateLock);
1225
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001226 const auto display = getDisplayDeviceLocked(displayToken);
1227 if (!display) {
1228 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001229 return BAD_VALUE;
1230 }
1231
Peiyong Linfb069302018-04-25 14:34:31 -07001232 // At this point the DisplayDeivce should already be set up,
1233 // meaning the luminance information is already queried from
1234 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001235 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001236 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1237 capabilities.getDesiredMaxLuminance(),
1238 capabilities.getDesiredMaxAverageLuminance(),
1239 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001240
1241 return NO_ERROR;
1242}
1243
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001244status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1245 ui::PixelFormat* outFormat,
1246 ui::Dataspace* outDataspace,
1247 uint8_t* outComponentMask) const {
1248 if (!outFormat || !outDataspace || !outComponentMask) {
1249 return BAD_VALUE;
1250 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001251 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001252 if (!display || !display->getId()) {
1253 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1254 return BAD_VALUE;
1255 }
1256 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1257 outDataspace, outComponentMask);
1258}
1259
Kevin DuBois74e53772018-11-19 10:52:38 -08001260status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1261 bool enable, uint8_t componentMask,
1262 uint64_t maxFrames) const {
1263 const auto display = getDisplayDevice(displayToken);
1264 if (!display || !display->getId()) {
1265 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1266 return BAD_VALUE;
1267 }
1268
1269 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1270 componentMask, maxFrames);
1271}
1272
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001273status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1274 uint64_t maxFrames, uint64_t timestamp,
1275 DisplayedFrameStats* outStats) const {
1276 const auto display = getDisplayDevice(displayToken);
1277 if (!display || !display->getId()) {
1278 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1279 return BAD_VALUE;
1280 }
1281
1282 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1283 outStats);
1284}
1285
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001286status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1287 if (!outSupported) {
1288 return BAD_VALUE;
1289 }
1290 *outSupported = getRenderEngine().supportsProtectedContent();
1291 return NO_ERROR;
1292}
1293
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001294status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1295 bool* outIsWideColorDisplay) const {
1296 if (!displayToken || !outIsWideColorDisplay) {
1297 return BAD_VALUE;
1298 }
1299 Mutex::Autolock _l(mStateLock);
1300 const auto display = getDisplayDeviceLocked(displayToken);
1301 if (!display) {
1302 return BAD_VALUE;
1303 }
Peiyong Linff84a152019-05-17 18:36:19 -07001304
1305 // Use hasWideColorDisplay to override built-in display.
1306 const auto displayId = display->getId();
1307 if (displayId && displayId == getInternalDisplayIdLocked()) {
1308 *outIsWideColorDisplay = hasWideColorDisplay;
1309 return NO_ERROR;
1310 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001311 *outIsWideColorDisplay = display->hasWideColorGamut();
1312 return NO_ERROR;
1313}
1314
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001315status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001316 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001317 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001318
Dominik Laskowski6505f792019-09-18 11:10:05 -07001319 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1320 mEventQueue->setEventConnection(
1321 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001322 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001323 }));
1324
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001325 return NO_ERROR;
1326}
1327
1328status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001329 Mutex::Autolock lock(mStateLock);
1330 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001331}
1332
Lloyd Pique755e3192018-01-31 16:46:15 -08001333status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1334 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001335 // Try to acquire a lock for 1s, fail gracefully
1336 const status_t err = mStateLock.timedLock(s2ns(1));
1337 const bool locked = (err == NO_ERROR);
1338 if (!locked) {
1339 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1340 return TIMED_OUT;
1341 }
1342
1343 outLayers->clear();
1344 mCurrentState.traverseInZOrder([&](Layer* layer) {
1345 outLayers->push_back(layer->getLayerDebugInfo());
1346 });
1347
1348 mStateLock.unlock();
1349 return NO_ERROR;
1350}
1351
Peiyong Linc6780972018-10-28 15:24:08 -07001352status_t SurfaceFlinger::getCompositionPreference(
1353 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1354 Dataspace* outWideColorGamutDataspace,
1355 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001356 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001357 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001358 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001359 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001360 return NO_ERROR;
1361}
1362
Dan Stozaec460082018-12-17 15:35:09 -08001363status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1364 const sp<IBinder>& stopLayerHandle,
1365 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001366 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001367 return BAD_VALUE;
1368 }
1369 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001370 return NO_ERROR;
1371}
1372
Dan Stozaec460082018-12-17 15:35:09 -08001373status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001374 if (!listener) {
1375 return BAD_VALUE;
1376 }
Dan Stozaec460082018-12-17 15:35:09 -08001377 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001378 return NO_ERROR;
1379}
Dan Gittik57e63c52019-01-18 16:37:54 +00001380
1381status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1382 bool* outSupport) const {
1383 if (!displayToken || !outSupport) {
1384 return BAD_VALUE;
1385 }
1386 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1387 if (!displayId) {
1388 return NAME_NOT_FOUND;
1389 }
1390 *outSupport =
1391 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1392 return NO_ERROR;
1393}
1394
1395status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1396 float brightness) const {
1397 if (!displayToken) {
1398 return BAD_VALUE;
1399 }
1400 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1401 if (!displayId) {
1402 return NAME_NOT_FOUND;
1403 }
1404 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1405}
1406
Ady Abraham8532d012019-05-08 14:50:56 -07001407status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1408 PowerHint powerHint = static_cast<PowerHint>(hintId);
1409
1410 if (powerHint == PowerHint::INTERACTION) {
1411 mScheduler->notifyTouchEvent();
1412 }
1413
1414 return NO_ERROR;
1415}
1416
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001417// ----------------------------------------------------------------------------
1418
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001419sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001420 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001421 const auto& handle =
1422 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001423
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001424 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001425}
1426
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001427// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001428
1429void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001430 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001431}
1432
1433void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001434 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001435 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001436}
1437
1438void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001439 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001440 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001441}
1442
1443void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001444 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001445 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001446}
1447
1448status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001449 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001450 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001451}
1452
1453status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001454 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001455 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001456 if (res == NO_ERROR) {
1457 msg->wait();
1458 }
1459 return res;
1460}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001461
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001462void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001463 do {
1464 waitForEvent();
1465 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001466}
1467
Dominik Laskowski83b88212018-12-11 13:34:06 -08001468nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001469 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001470 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1471 return 0;
1472 }
1473
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001474 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001475}
1476
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001477void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001478 int64_t timestamp,
1479 std::optional<hwc2_vsync_period_t> /*vsyncPeriod*/) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001480 ATRACE_NAME("SF onVsync");
1481
Ady Abraham7159f572019-10-11 11:10:18 -07001482 // TODO(b/140201379): use vsyncPeriod in the new DispSync
1483
Steven Thomas3cfac282017-02-06 12:29:30 -08001484 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001485 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001486 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001487 return;
1488 }
1489
Dominik Laskowski075d3172018-05-24 15:50:06 -07001490 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001491 return;
1492 }
1493
Dominik Laskowski075d3172018-05-24 15:50:06 -07001494 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001495 // For now, we don't do anything with external display vsyncs.
1496 return;
1497 }
1498
Alec Mourif8e689c2019-05-20 18:32:22 -07001499 bool periodFlushed = false;
1500 mScheduler->addResyncSample(timestamp, &periodFlushed);
1501 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001502 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001503 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001504}
1505
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001506void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001507 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1508 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001509}
1510
Ady Abraham2139f732019-11-13 18:56:40 -08001511bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001512 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001513}
1514
Ady Abraham2139f732019-11-13 18:56:40 -08001515void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1516 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001517 const auto display = getDefaultDisplayDeviceLocked();
1518 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001519 return;
1520 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001521 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001522
Ana Krulec7d1d6832018-12-27 11:10:09 -08001523 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001524 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1525 ALOGV("Skipping config %d as it is not part of allowed configs",
1526 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001527 return;
1528 }
1529
Ady Abraham2139f732019-11-13 18:56:40 -08001530 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001531}
1532
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001533void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001534 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001535 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001536 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001537
Lloyd Piqueba04e622017-12-14 17:11:26 -08001538 // Ignore events that do not have the right sequenceId.
1539 if (sequenceId != getBE().mComposerSequenceId) {
1540 return;
1541 }
1542
Steven Thomasb02664d2017-07-26 18:48:28 -07001543 // Only lock if we're not on the main thread. This function is normally
1544 // called on a hwbinder thread, but for the primary display it's called on
1545 // the main thread with the state lock already held, so don't attempt to
1546 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001547 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001548
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001549 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001550
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001551 if (std::this_thread::get_id() == mMainThreadId) {
1552 // Process all pending hot plug events immediately if we are on the main thread.
1553 processDisplayHotplugEventsLocked();
1554 }
1555
Lloyd Piqueba04e622017-12-14 17:11:26 -08001556 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001557}
1558
Ady Abraham7159f572019-10-11 11:10:18 -07001559void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001560 int32_t sequenceId, hwc2_display_t /*display*/,
1561 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1562 Mutex::Autolock lock(mStateLock);
1563 if (sequenceId != getBE().mComposerSequenceId) {
1564 return;
1565 }
1566 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001567}
1568
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001569void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1570 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1571 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1572}
1573
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001574void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001575 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001576 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001577 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001578 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001579 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001580}
1581
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001582void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001583 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001584
1585 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1586 // display power state.
1587 postMessageAsync(new LambdaMessage(
1588 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1589}
1590
1591void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1592 ATRACE_CALL();
1593
Ady Abraham27c70212019-06-11 10:52:26 -07001594 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1595
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001596 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001597 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1598 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001599 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001600 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001601 }
Mathias Agopian86303202012-07-24 22:46:10 -07001602}
1603
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001604// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001605void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001606 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001607 // Clear the drawing state so that the logic inside of
1608 // handleTransactionLocked will fire. It will determine the delta between
1609 // mCurrentState and mDrawingState and re-apply all changes when we make the
1610 // transition.
1611 mDrawingState.displays.clear();
1612 mDisplays.clear();
1613}
1614
Steven Thomas050b2c82017-03-06 11:45:16 -08001615void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001616 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001617 if (!mVrFlinger)
1618 return;
1619 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001620 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001621 return;
1622 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001623
Lloyd Pique441d5042018-10-18 16:49:51 -07001624 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001625 ALOGE("Vr flinger is only supported for remote hardware composer"
1626 " service connections. Ignoring request to transition to vr"
1627 " flinger.");
1628 mVrFlingerRequestsDisplay = false;
1629 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001630 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001631
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001632 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001633
Steven Thomas0123ac62018-07-12 11:32:34 -07001634 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001635 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001636
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001637 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001638
1639 // Clear out all the output layers from the composition engine for all
1640 // displays before destroying the hardware composer interface. This ensures
1641 // any HWC layers are destroyed through that interface before it becomes
1642 // invalid.
1643 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001644 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001645 }
1646
Steven Thomas0123ac62018-07-12 11:32:34 -07001647 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1648 // called below. Clear the reference now so we don't accidentally use it
1649 // later.
1650 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001651
Steven Thomasb02664d2017-07-26 18:48:28 -07001652 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001653 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001654 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001655
Steven Thomasb02664d2017-07-26 18:48:28 -07001656 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001657 // Delete the current instance before creating the new one
1658 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1659 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1660 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1661 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001662
Lloyd Pique441d5042018-10-18 16:49:51 -07001663 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001664 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001665
1666 if (vrFlingerRequestsDisplay) {
1667 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001668 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001669
1670 mVisibleRegionsDirty = true;
1671 invalidateHwcGeometry();
1672
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001673 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001674 display = getDefaultDisplayDeviceLocked();
1675 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001676 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001677
Steven Thomasb02664d2017-07-26 18:48:28 -07001678 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001679 const nsecs_t vsyncPeriod = getVsyncPeriod();
1680 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001681
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001682 // The present fences returned from vr_hwc are not an accurate
1683 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001684 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001685
Steven Thomasb02664d2017-07-26 18:48:28 -07001686 // Use phase of 0 since phase is not known.
1687 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001688 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001689 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001690
Ana Krulecc2870422019-01-29 19:00:58 -08001691 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001692
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001693 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001694 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001695}
1696
Ady Abraham11579302019-09-19 12:35:58 -07001697bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1698 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001699 // We are storing the last 2 present fences. If sf's phase offset is to be
1700 // woken up before the actual vsync but targeting the next vsync, we need to check
1701 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001702 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1703 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001704
Ady Abraham11579302019-09-19 12:35:58 -07001705 if (fence == Fence::NO_FENCE) {
1706 return false;
1707 }
1708
1709 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1710 fence->wait(graceTimeMs);
1711 }
1712
1713 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001714}
1715
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001716void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001717 DisplayStatInfo stats;
1718 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001719 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001720 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001721 mExpectedPresentTime.store(
1722 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001723}
1724
Dominik Laskowski22488f62019-03-28 09:53:04 -07001725void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001726 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001727 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001728 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001729 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001730 // calculate the expected present time once and use the cached
1731 // value throughout this frame to make sure all layers are
1732 // seeing this same value.
1733 populateExpectedPresentTime();
1734
Ady Abraham11579302019-09-19 12:35:58 -07001735 // When Backpressure propagation is enabled we want to give a small grace period
1736 // for the present fence to fire instead of just giving up on this frame to handle cases
1737 // where present fence is just about to get signaled.
1738 const int graceTimeForPresentFenceMs =
1739 (mPropagateBackpressure &&
1740 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1741 ? 1
1742 : 0;
1743 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1744 previousFrameMissed(
1745 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001746 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1747 mHadDeviceComposition && frameMissed};
1748 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1749 mHadClientComposition && frameMissed};
1750
Alec Mouricc0fc602019-02-26 21:45:19 -08001751 if (frameMissed) {
1752 mFrameMissedCount++;
1753 mTimeStats->incrementMissedFrames();
1754 }
1755
Alec Mouri40189b02019-03-05 15:07:54 -08001756 if (hwcFrameMissed) {
1757 mHwcFrameMissedCount++;
1758 }
1759
1760 if (gpuFrameMissed) {
1761 mGpuFrameMissedCount++;
1762 }
1763
Ady Abrahamadb9a992019-09-19 21:21:55 +00001764 if (frameMissed && mPropagateBackpressure) {
1765 if ((hwcFrameMissed && !gpuFrameMissed) ||
1766 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001767 signalLayerUpdate();
1768 break;
1769 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001770 }
Dan Stoza50182882016-07-08 12:02:20 -07001771
Steven Thomas050b2c82017-03-06 11:45:16 -08001772 // Now that we're going to make it to the handleMessageTransaction()
1773 // call below it's safe to call updateVrFlinger(), which will
1774 // potentially trigger a display handoff.
1775 updateVrFlinger();
1776
Dan Stoza6b9454d2014-11-07 16:00:59 -08001777 bool refreshNeeded = handleMessageTransaction();
1778 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001779
Ana Krulecc84d09b2019-11-02 23:10:29 +01001780 // Layers need to get updated (in the previous line) before we can use them for
1781 // choosing the refresh rate.
1782 mScheduler->chooseRefreshRateForContent();
1783 if (performSetActiveConfig()) {
1784 break;
1785 }
1786
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001787 updateCursorAsync();
1788 updateInputFlinger();
1789
Dan Stoza58784442014-12-02 16:58:17 -08001790 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001791 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001792 // Signal a refresh if a transaction modified the window state,
1793 // a new buffer was latched, or if HWC has requested a full
1794 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001795 if (mFrameStartTime <= 0) {
1796 // We should only use the time of the first invalidate
1797 // message that signals a refresh as the beginning of the
1798 // frame. Otherwise the real frame time will be
1799 // underestimated.
1800 mFrameStartTime = frameStart;
1801 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001802 signalRefresh();
1803 }
1804 break;
1805 }
1806 case MessageQueue::REFRESH: {
1807 handleMessageRefresh();
1808 break;
1809 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001810 }
1811}
1812
Dan Stoza6b9454d2014-11-07 16:00:59 -08001813bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001814 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001815 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001816
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001817 bool flushedATransaction = flushTransactionQueues();
1818
1819 bool runHandleTransaction = transactionFlags &&
1820 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1821
1822 if (runHandleTransaction) {
1823 handleTransaction(eTransactionMask);
1824 } else {
1825 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001826 }
1827
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001828 if (transactionFlushNeeded()) {
1829 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001830 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001831
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001832 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001833}
1834
Mathias Agopian4fec8732012-06-29 14:12:52 -07001835void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001836 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001837
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001838 mRefreshPending = false;
1839
Lloyd Piqueab039b52019-02-13 14:22:42 -08001840 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001841 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001842 for (const auto& [_, display] : mDisplays) {
1843 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1844 }
1845 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1846 auto compositionLayer = layer->getCompositionLayer();
1847 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1848 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001849 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1850 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1851 auto compositionLayer = layer->getCompositionLayer();
Adithya Srinivasan87c1b80e2019-11-21 11:43:06 -08001852 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001853 }
1854
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001855 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001856 refreshArgs.outputColorSetting = useColorManagement
1857 ? mDisplayColorSetting
1858 : compositionengine::OutputColorSetting::kUnmanaged;
1859 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1860 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001861
1862 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1863 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001864
1865 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1866 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1867 mDrawingState.colorMatrixChanged = false;
1868 }
1869
1870 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1871
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001872 if (mDebugRegion != 0) {
1873 refreshArgs.devOptFlashDirtyRegionsDelay =
1874 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1875 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001876
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001877 mGeometryInvalid = false;
1878
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001879 // Store the present time just before calling to the composition engine so we could notify
1880 // the scheduler.
1881 const auto presentTime = systemTime();
1882
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001883 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001884 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1885 // Reset the frame start time now that we've recorded this frame.
1886 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001887
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001888 mScheduler->onDisplayRefreshed(presentTime);
1889
David Sodmanfa9b2af2017-12-24 13:28:59 -08001890 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001891 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001892
Lloyd Pique66d68602019-02-13 14:23:31 -08001893 mHadClientComposition =
1894 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1895 auto& displayDevice = tokenDisplayPair.second;
1896 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1897 });
1898 mHadDeviceComposition =
1899 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1900 auto& displayDevice = tokenDisplayPair.second;
1901 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1902 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001903
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001904 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001905
David Sodman7e4ae112018-02-09 15:02:28 -08001906 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001907 if (mVisibleRegionsDirty) {
1908 mVisibleRegionsDirty = false;
1909 if (mTracingEnabled) {
1910 mTracing.notify("visibleRegionsDirty");
1911 }
1912 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001913
1914 if (mCompositionEngine->needsAnotherUpdate()) {
1915 signalLayerUpdate();
1916 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001917}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001918
David Sodmanfa9b2af2017-12-24 13:28:59 -08001919
1920bool SurfaceFlinger::handleMessageInvalidate() {
1921 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001922 bool refreshNeeded = handlePageFlip();
1923
Vishnu Nair4351ad52019-02-11 14:13:02 -08001924 if (mVisibleRegionsDirty) {
1925 computeLayerBounds();
1926 }
1927
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001928 for (auto& layer : mLayersPendingRefresh) {
1929 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001930 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001931 invalidateLayerStack(layer, visibleReg);
1932 }
1933 mLayersPendingRefresh.clear();
1934 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001935}
1936
Ana Krulece588e312018-09-18 12:32:24 -07001937void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1938 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001939 // Update queue of past composite+present times and determine the
1940 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001941 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001942 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001943 while (!getBE().mCompositePresentTimes.empty()) {
1944 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001945 // Cached values should have been updated before calling this method,
1946 // which helps avoid duplicate syscalls.
1947 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1948 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1949 break;
1950 }
1951 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001952 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001953 }
1954
1955 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001956 while (getBE().mCompositePresentTimes.size() > 16) {
1957 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001958 }
1959
Ana Krulece588e312018-09-18 12:32:24 -07001960 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001961}
1962
Ana Krulece588e312018-09-18 12:32:24 -07001963void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1964 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001965 // Integer division and modulo round toward 0 not -inf, so we need to
1966 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08001967 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
1968 ? (stats.vsyncPeriod -
1969 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
1970 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001971
Ady Abraham9e16a482019-12-03 17:19:41 -08001972 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001973 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001974 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001975 }
1976
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001977 // Snap the latency to a value that removes scheduling jitter from the
1978 // composition and present times, which often have >1ms of jitter.
1979 // Reducing jitter is important if an app attempts to extrapolate
1980 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08001981 // Snapping also allows an app to precisely calculate
1982 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001983 nsecs_t bias = stats.vsyncPeriod / 2;
1984 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1985 nsecs_t snappedCompositeToPresentLatency =
1986 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001987
David Sodman99974d22017-11-28 12:04:33 -08001988 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001989 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1990 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001991 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001992}
1993
David Sodman2b406362017-12-15 13:33:47 -08001994void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001995{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001996 ATRACE_CALL();
1997 ALOGV("postComposition");
1998
Brian Anderson3546a3f2016-07-14 11:51:14 -07001999 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002000 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002001 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002002 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002003 }
2004
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002005 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002006 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002007
David Sodman73beded2017-11-15 11:56:06 -08002008 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002009 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002010 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002011 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002012 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2013 ->getRenderSurface()
2014 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002015 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002016 } else {
2017 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2018 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002019
David Sodman73beded2017-11-15 11:56:06 -08002020 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002021 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2022 mPreviousPresentFences[0] = displayDevice
2023 ? getHwComposer().getPresentFence(*displayDevice->getId())
2024 : Fence::NO_FENCE;
2025 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002026 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002027
Ana Krulece588e312018-09-18 12:32:24 -07002028 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002029 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002030
Lloyd Piqueab039b52019-02-13 14:22:42 -08002031 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2032 // be sampled a little later than when we started doing work for this frame,
2033 // but that should be okay since updateCompositorTiming has snapping logic.
2034 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2035 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002036 CompositorTiming compositorTiming;
2037 {
David Sodman99974d22017-11-28 12:04:33 -08002038 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2039 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002040 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002041
Robert Carr2047fae2016-11-28 14:09:09 -08002042 mDrawingState.traverseInZOrder([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002043 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2044 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002045 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002046 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002047 }
Robert Carr2047fae2016-11-28 14:09:09 -08002048 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002049
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002050 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002051 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002052 }
2053
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002054 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002055 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2056 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002057 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002058 }
2059 }
2060
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002061 if (mAnimCompositionPending) {
2062 mAnimCompositionPending = false;
2063
Brian Anderson4e606e32017-03-16 15:34:57 -07002064 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002065 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002066 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002067 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002068 // The HWC doesn't support present fences, so use the refresh
2069 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002070 const nsecs_t presentTime =
2071 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002072 mAnimFrameTracker.setActualPresentTime(presentTime);
2073 }
2074 mAnimFrameTracker.advanceFrame();
2075 }
Dan Stozab90cf072015-03-05 11:05:59 -08002076
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002077 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002078 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002079 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002080 }
2081
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002082 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002083
Lloyd Pique32cbe282018-10-19 13:09:22 -07002084 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2085 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002086 return;
2087 }
2088
2089 nsecs_t currentTime = systemTime();
2090 if (mHasPoweredOff) {
2091 mHasPoweredOff = false;
2092 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002093 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002094 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002095 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2096 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002097 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002098 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002099 }
David Sodman4a36e932017-11-07 14:29:47 -08002100 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002101 }
David Sodman4a36e932017-11-07 14:29:47 -08002102 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002103
2104 {
2105 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002106 if (mTexturePool.size() < mTexturePoolSize) {
2107 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002108 const size_t offset = mTexturePool.size();
2109 mTexturePool.resize(mTexturePoolSize);
2110 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2111 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002112 } else if (mTexturePool.size() > mTexturePoolSize) {
2113 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2114 const size_t offset = mTexturePoolSize;
2115 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2116 mTexturePool.resize(mTexturePoolSize);
2117 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002118 }
2119 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002120
Ady Abrahambe0f9482019-04-24 15:41:53 -07002121 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002122 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002123
Kevin DuBois413287f2019-02-25 08:46:47 -08002124 if (mLumaSampling && mRegionSamplingThread) {
2125 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002126 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002127
2128 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2129 // side-effect of getTotalSize(), so we check that again here
2130 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002131 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002132 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2133 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002134}
2135
Vishnu Nair4351ad52019-02-11 14:13:02 -08002136void SurfaceFlinger::computeLayerBounds() {
2137 for (const auto& pair : mDisplays) {
2138 const auto& displayDevice = pair.second;
2139 const auto display = displayDevice->getCompositionDisplay();
2140 for (const auto& layer : mDrawingState.layersSortedByZ) {
2141 // only consider the layers on the given layer stack
2142 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002143 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002144 }
2145
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002146 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2147 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002148 }
2149 }
2150}
2151
David Sodmanfa9b2af2017-12-24 13:28:59 -08002152void SurfaceFlinger::postFrame()
2153{
2154 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002155 const auto display = getDefaultDisplayDeviceLocked();
2156 if (display && getHwComposer().isConnected(*display->getId())) {
2157 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002158 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2159 logFrameStats();
2160 }
2161 }
2162}
2163
Mathias Agopian87baae12012-07-31 12:38:26 -07002164void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002165{
Mathias Agopian841cde52012-03-01 15:44:37 -08002166 ATRACE_CALL();
2167
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002168 // here we keep a copy of the drawing state (that is the state that's
2169 // going to be overwritten by handleTransactionLocked()) outside of
2170 // mStateLock so that the side-effects of the State assignment
2171 // don't happen with mStateLock held (which can cause deadlocks).
2172 State drawingState(mDrawingState);
2173
Mathias Agopianca4d3602011-05-19 15:38:14 -07002174 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002175 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002176
Mathias Agopianca4d3602011-05-19 15:38:14 -07002177 // Here we're guaranteed that some transaction flags are set
2178 // so we can call handleTransactionLocked() unconditionally.
2179 // We call getTransactionFlags(), which will also clear the flags,
2180 // with mStateLock held to guarantee that mCurrentState won't change
2181 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002182
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002183 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002184 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002185 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002186
Mathias Agopianca4d3602011-05-19 15:38:14 -07002187 mDebugInTransaction = 0;
2188 invalidateHwcGeometry();
2189 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002190}
2191
Lloyd Piqueba04e622017-12-14 17:11:26 -08002192void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2193 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002194 const std::optional<DisplayIdentificationInfo> info =
2195 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002196
Dominik Laskowski075d3172018-05-24 15:50:06 -07002197 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002198 continue;
2199 }
2200
Lloyd Piqueba04e622017-12-14 17:11:26 -08002201 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002202 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002203 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002204 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2205 initScheduler(info->id);
2206 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002207 mPhysicalDisplayTokens[info->id] = new BBinder();
2208 DisplayDeviceState state;
2209 state.displayId = info->id;
2210 state.isSecure = true; // All physical displays are currently considered secure.
2211 state.displayName = info->name;
2212 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2213 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002214 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002215 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002216 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002217
Dominik Laskowski075d3172018-05-24 15:50:06 -07002218 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2219 if (index >= 0) {
2220 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2221 mInterceptor->saveDisplayDeletion(state.sequenceId);
2222 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002223 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002224 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002225 }
2226
2227 processDisplayChangesLocked();
2228 }
2229
2230 mPendingHotplugEvents.clear();
2231}
2232
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002233void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002234 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2235 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002236}
2237
Lloyd Pique99d3da52018-01-22 17:48:03 -08002238sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002239 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002240 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002241 const sp<IGraphicBufferProducer>& producer) {
2242 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002243 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002244 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002245 creationArgs.isSecure = state.isSecure;
2246 creationArgs.displaySurface = dispSurface;
2247 creationArgs.hasWideColorGamut = false;
2248 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002249 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002250
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002251 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002252 creationArgs.isPrimary = isInternalDisplay;
2253
2254 if (useColorManagement && displayId) {
2255 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002256 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002257 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002258 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002259 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002260
Dominik Laskowski7e045462018-05-30 13:02:02 -07002261 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002262 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002263 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002264 }
tangrobin6753a022018-08-10 10:58:54 +08002265 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002266
Dominik Laskowski075d3172018-05-24 15:50:06 -07002267 if (displayId) {
2268 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002269 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002270 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002271 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002272
Lloyd Pique90c115d2018-09-18 21:39:42 -07002273 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002274 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002275 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002276
Lloyd Pique99d3da52018-01-22 17:48:03 -08002277 // Make sure that composition can never be stalled by a virtual display
2278 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002279 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002280 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002281 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2282 }
2283
Dominik Laskowski718f9602019-11-09 20:01:35 -08002284 creationArgs.physicalOrientation =
2285 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002286
Lloyd Pique99d3da52018-01-22 17:48:03 -08002287 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002288 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002289
Lloyd Pique90c115d2018-09-18 21:39:42 -07002290 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002291
2292 if (maxFrameBufferAcquiredBuffers >= 3) {
2293 nativeWindowSurface->preallocateBuffers();
2294 }
2295
2296 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002297 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002298 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002299 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002300 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002301 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002302 display->getCompositionDisplay()->setColorProfile(
2303 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2304 RenderIntent::COLORIMETRIC,
2305 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002306 if (!state.isVirtual()) {
2307 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002308 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2309 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002310 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002311
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002312 display->setLayerStack(state.layerStack);
2313 display->setProjection(state.orientation, state.viewport, state.frame);
2314 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002315
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002316 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002317}
2318
Lloyd Pique347200f2017-12-14 17:00:15 -08002319void SurfaceFlinger::processDisplayChangesLocked() {
2320 // here we take advantage of Vector's copy-on-write semantics to
2321 // improve performance by skipping the transaction entirely when
2322 // know that the lists are identical
2323 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2324 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2325 if (!curr.isIdenticalTo(draw)) {
2326 mVisibleRegionsDirty = true;
2327 const size_t cc = curr.size();
2328 size_t dc = draw.size();
2329
2330 // find the displays that were removed
2331 // (ie: in drawing state but not in current state)
2332 // also handle displays that changed
2333 // (ie: displays that are in both lists)
2334 for (size_t i = 0; i < dc;) {
2335 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2336 if (j < 0) {
2337 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002338 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002339 // Save display ID before disconnecting.
2340 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002341 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002342
2343 if (!display->isVirtual()) {
2344 LOG_ALWAYS_FATAL_IF(!displayId);
2345 dispatchDisplayHotplugEvent(displayId->value, false);
2346 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002347 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002348
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002349 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002350 } else {
2351 // this display is in both lists. see if something changed.
2352 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002353 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002354 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2355 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2356 if (state_binder != draw_binder) {
2357 // changing the surface is like destroying and
2358 // recreating the DisplayDevice, so we just remove it
2359 // from the drawing state, so that it get re-added
2360 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002361 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002362 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002363 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002364 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002365 mDrawingState.displays.removeItemsAt(i);
2366 dc--;
2367 // at this point we must loop to the next item
2368 continue;
2369 }
2370
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002371 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002372 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002373 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002374 }
2375 if ((state.orientation != draw[i].orientation) ||
2376 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002377 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002378 }
2379 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002380 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002381 }
2382 }
2383 }
2384 ++i;
2385 }
2386
2387 // find displays that were added
2388 // (ie: in current state but not in drawing state)
2389 for (size_t i = 0; i < cc; i++) {
2390 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2391 const DisplayDeviceState& state(curr[i]);
2392
Lloyd Pique542307f2018-10-19 13:24:08 -07002393 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002394 sp<IGraphicBufferProducer> producer;
2395 sp<IGraphicBufferProducer> bqProducer;
2396 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002397 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002398
Dominik Laskowski075d3172018-05-24 15:50:06 -07002399 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002400 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002401 // Virtual displays without a surface are dormant:
2402 // they have external state (layer stack, projection,
2403 // etc.) but no internal state (i.e. a DisplayDevice).
2404 if (state.surface != nullptr) {
2405 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002406 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002407 int width = 0;
2408 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2409 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2410 int height = 0;
2411 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2412 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2413 int intFormat = 0;
2414 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2415 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002416 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002417
Dominik Laskowski075d3172018-05-24 15:50:06 -07002418 displayId =
2419 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002420 }
2421
2422 // TODO: Plumb requested format back up to consumer
2423
2424 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002425 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002426 bqProducer, bqConsumer,
2427 state.displayName);
2428
2429 dispSurface = vds;
2430 producer = vds;
2431 }
2432 } else {
2433 ALOGE_IF(state.surface != nullptr,
2434 "adding a supported display, but rendering "
2435 "surface is provided (%p), ignoring it",
2436 state.surface.get());
2437
Dominik Laskowski075d3172018-05-24 15:50:06 -07002438 displayId = state.displayId;
2439 LOG_ALWAYS_FATAL_IF(!displayId);
2440 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002441 producer = bqProducer;
2442 }
2443
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002444 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002445 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002446 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002447 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002448 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002449 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002450 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002451 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002452 }
2453 }
2454 }
2455 }
2456 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002457
2458 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002459}
2460
Mathias Agopian87baae12012-07-31 12:38:26 -07002461void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002462{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002463 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2464
Dan Stoza7dde5992015-05-22 09:51:44 -07002465 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002466 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2467 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002468 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002469
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002470 /*
2471 * Traversal of the children
2472 * (perform the transaction for each of them if needed)
2473 */
2474
Marissa Wall06255332019-03-27 13:48:27 -07002475 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002476 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002477 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002478 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002479
2480 const uint32_t flags = layer->doTransaction(0);
2481 if (flags & Layer::eVisibleRegion)
2482 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002483
2484 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002485 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002486 }
Robert Carr2047fae2016-11-28 14:09:09 -08002487 });
Marissa Wall06255332019-03-27 13:48:27 -07002488 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002489 }
2490
2491 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002492 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002493 */
2494
Mathias Agopiane57f2922012-08-09 16:29:12 -07002495 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002496 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002497 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002498 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002499
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002500 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002501 // The transform hint might have changed for some layers
2502 // (either because a display has changed, or because a layer
2503 // as changed).
2504 //
2505 // Walk through all the layers in currentLayers,
2506 // and update their transform hint.
2507 //
2508 // If a layer is visible only on a single display, then that
2509 // display is used to calculate the hint, otherwise we use the
2510 // default display.
2511 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002512 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002513 // the hint is set before we acquire a buffer from the surface texture.
2514 //
2515 // NOTE: layer transactions have taken place already, so we use their
2516 // drawing state. However, SurfaceFlinger's own transaction has not
2517 // happened yet, so we must use the current state layer list
2518 // (soon to become the drawing state list).
2519 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002520 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002521 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002522 bool first = true;
2523 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002524 // NOTE: we rely on the fact that layers are sorted by
2525 // layerStack first (so we don't have to traverse the list
2526 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002527 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002528 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002529 currentlayerStack = layerStack;
2530 // figure out if this layerstack is mirrored
2531 // (more than one display) if so, pick the default display,
2532 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002533 hintDisplay = nullptr;
2534 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002535 if (display->getCompositionDisplay()
2536 ->belongsInOutput(layer->getLayerStack(),
2537 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002538 if (hintDisplay) {
2539 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002540 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002541 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002542 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002543 }
2544 }
2545 }
2546 }
Chet Haase91d25932013-04-11 15:24:55 -07002547
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002548 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002549 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2550 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002551
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002552 // could be null when this layer is using a layerStack
2553 // that is not visible on any display. Also can occur at
2554 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002555 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002556 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002557
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002558 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002559 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002560 if (hintDisplay) {
2561 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002562 }
Robert Carr2047fae2016-11-28 14:09:09 -08002563
2564 first = false;
2565 });
Mathias Agopian84300952012-11-21 16:02:13 -08002566 }
2567
2568
Mathias Agopian3559b072012-08-15 13:46:03 -07002569 /*
2570 * Perform our own transaction if needed
2571 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002572
2573 if (mLayersAdded) {
2574 mLayersAdded = false;
2575 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002576 mVisibleRegionsDirty = true;
2577 }
2578
2579 // some layers might have been removed, so
2580 // we need to update the regions they're exposing.
2581 if (mLayersRemoved) {
2582 mLayersRemoved = false;
2583 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002584 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002585 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002586 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002587 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002588 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002589 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002590 }
Robert Carr2047fae2016-11-28 14:09:09 -08002591 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002592 }
2593
Vishnu Nairec0ab382019-02-13 15:32:56 -08002594 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002596}
2597
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002598void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002599 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002600 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002601 return;
2602 }
2603
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002604 if (mVisibleRegionsDirty || mInputInfoChanged) {
2605 mInputInfoChanged = false;
2606 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002607 } else if (mInputWindowCommands.syncInputWindows) {
2608 // If the caller requested to sync input windows, but there are no
2609 // changes to input windows, notify immediately.
2610 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002611 }
2612
Arthur Hung6cbb9752019-09-05 16:38:18 +08002613 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002614}
2615
2616void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002617 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002618
2619 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2620 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002621 // When calculating the screen bounds we ignore the transparent region since it may
2622 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002623 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002624 }
2625 });
chaviw291d88a2019-02-14 10:33:58 -08002626
2627 mInputFlinger->setInputWindows(inputHandles,
2628 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2629 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002630}
2631
Vishnu Nairec0ab382019-02-13 15:32:56 -08002632void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002633 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002634 mPendingInputWindowCommands.clear();
2635}
2636
Riley Andrews03414a12014-07-01 14:22:59 -07002637void SurfaceFlinger::updateCursorAsync()
2638{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002639 compositionengine::CompositionRefreshArgs refreshArgs;
2640 for (const auto& [_, display] : mDisplays) {
2641 if (display->getId()) {
2642 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002643 }
2644 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002645
2646 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002647}
2648
Ady Abraham2139f732019-11-13 18:56:40 -08002649void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
2650 Scheduler::ConfigEvent event) {
2651 Mutex::Autolock lock(mStateLock);
2652 changeRefreshRateLocked(refreshRate, event);
2653}
2654
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002655void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2656 if (mScheduler) {
2657 // In practice it's not allowed to hotplug in/out the primary display once it's been
2658 // connected during startup, but some tests do it, so just warn and return.
2659 ALOGW("Can't re-init scheduler");
2660 return;
2661 }
2662
Ady Abraham2139f732019-11-13 18:56:40 -08002663 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002664 mRefreshRateConfigs =
2665 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2666 getHwComposer().getConfigs(
2667 primaryDisplayId),
2668 currentConfig);
2669 mRefreshRateStats =
2670 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2671 currentConfig, HWC_POWER_MODE_OFF);
2672 mRefreshRateStats->setConfigMode(currentConfig);
2673
Ady Abraham9e16a482019-12-03 17:19:41 -08002674 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2675
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002676 // start the EventThread
2677 mScheduler =
2678 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002679 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002680 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002681 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002682 impl::EventThread::InterceptVSyncsCallback());
2683 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002684 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002685 [this](nsecs_t timestamp) {
2686 mInterceptor->saveVSyncEvent(timestamp);
2687 });
2688
2689 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2690 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002691 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002692
2693 mRegionSamplingThread =
2694 new RegionSamplingThread(*this, *mScheduler,
2695 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002696 // Dispatch a config change request for the primary display on scheduler
2697 // initialization, so that the EventThreads always contain a reference to a
2698 // prior configuration.
2699 //
2700 // This is a bit hacky, but this avoids a back-pointer into the main SF
2701 // classes from EventThread, and there should be no run-time binder cost
2702 // anyway since there are no connected apps at this point.
2703 const nsecs_t vsyncPeriod =
2704 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2705 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2706 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002707}
2708
Mathias Agopian4fec8732012-06-29 14:12:52 -07002709void SurfaceFlinger::commitTransaction()
2710{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002711 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002712
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002713 mTransactionPending = false;
2714 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002715 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002716}
2717
Lloyd Pique58e24a32019-08-01 15:50:14 -07002718void SurfaceFlinger::commitTransactionLocked() {
2719 if (!mLayersPendingRemoval.isEmpty()) {
2720 // Notify removed layers now that they can't be drawn from
2721 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002722 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002723
2724 // Ensure any buffers set to display on any children are released.
2725 if (l->isRemovedFromCurrentState()) {
2726 l->latchAndReleaseBuffer();
2727 }
2728
2729 // If the layer has been removed and has no parent, then it will not be reachable
2730 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2731 // ensure we can copy its current to drawing state.
2732 if (!l->getParent()) {
2733 mOffscreenLayers.emplace(l.get());
2734 }
2735 }
2736 mLayersPendingRemoval.clear();
2737 }
2738
2739 // If this transaction is part of a window animation then the next frame
2740 // we composite should be considered an animation as well.
2741 mAnimCompositionPending = mAnimTransactionPending;
2742
2743 mDrawingState = mCurrentState;
2744 // clear the "changed" flags in current state
2745 mCurrentState.colorMatrixChanged = false;
2746
2747 mDrawingState.traverseInZOrder([&](Layer* layer) {
2748 layer->commitChildList();
2749
2750 // If the layer can be reached when traversing mDrawingState, then the layer is no
2751 // longer offscreen. Remove the layer from the offscreenLayer set.
2752 if (mOffscreenLayers.count(layer)) {
2753 mOffscreenLayers.erase(layer);
2754 }
2755 });
2756
2757 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002758 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002759}
2760
Nataniel Borges2b796da2019-02-15 13:32:18 -08002761void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2762 if (mTracingEnabledChanged) {
2763 mTracingEnabled = mTracing.isEnabled();
2764 mTracingEnabledChanged = false;
2765 }
2766
2767 // Synchronize with Tracing thread
2768 std::unique_lock<std::mutex> lock;
2769 if (mTracingEnabled) {
2770 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2771 }
2772
2773 lockedOperation();
2774
2775 // Synchronize with Tracing thread
2776 if (mTracingEnabled) {
2777 lock.unlock();
2778 }
2779}
2780
chaviw74d90ad2019-04-26 14:45:26 -07002781void SurfaceFlinger::commitOffscreenLayers() {
2782 for (Layer* offscreenLayer : mOffscreenLayers) {
2783 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2784 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2785 if (!trFlags) return;
2786
2787 layer->doTransaction(0);
2788 layer->commitChildList();
2789 });
2790 }
2791}
2792
Chia-I Wuab0c3192017-08-01 11:29:00 -07002793void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002794 for (const auto& [token, displayDevice] : mDisplays) {
2795 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002796 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002797 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002798 }
2799 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002800}
2801
Dan Stoza6b9454d2014-11-07 16:00:59 -08002802bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803{
Ady Abraham09bd3922019-04-08 10:44:56 -07002804 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002805 ALOGV("handlePageFlip");
2806
Brian Andersond6927fb2016-07-23 23:37:30 -07002807 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002808
Mathias Agopian4fec8732012-06-29 14:12:52 -07002809 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002810 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002811 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002812
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002813 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2814
Eric Penner51c59cd2014-07-28 19:51:58 -07002815 // Store the set of layers that need updates. This set must not change as
2816 // buffers are being latched, as this could result in a deadlock.
2817 // Example: Two producers share the same command stream and:
2818 // 1.) Layer 0 is latched
2819 // 2.) Layer 0 gets a new frame
2820 // 2.) Layer 1 gets a new frame
2821 // 3.) Layer 1 is latched.
2822 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2823 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002824 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002825 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002826 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002827 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002828 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002829 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002830 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002831 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002832 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002833 } else {
2834 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002835 }
Robert Carr2047fae2016-11-28 14:09:09 -08002836 });
2837
chaviw49a108c2019-08-12 11:23:06 -07002838 // The client can continue submitting buffers for offscreen layers, but they will not
2839 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2840 // layers to ensure dequeueBuffer doesn't block indefinitely.
2841 for (Layer* offscreenLayer : mOffscreenLayers) {
2842 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2843 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2844 }
2845
Lloyd Piquef2c79392018-12-20 16:23:33 -08002846 if (!mLayersWithQueuedFrames.empty()) {
2847 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2848 // writes to Layer current state. See also b/119481871
2849 Mutex::Autolock lock(mStateLock);
2850
2851 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002852 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002853 mLayersPendingRefresh.push_back(layer);
2854 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002855 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002856 if (layer->isBufferLatched()) {
2857 newDataLatched = true;
2858 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002859 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002860 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002861
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002862 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002863
2864 // If we will need to wake up at some time in the future to deal with a
2865 // queued frame that shouldn't be displayed during this vsync period, wake
2866 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002867 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002868 signalLayerUpdate();
2869 }
2870
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002871 // enter boot animation on first buffer latch
2872 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2873 ALOGI("Enter boot animation");
2874 mBootStage = BootStage::BOOTANIMATION;
2875 }
2876
chaviw74b03172019-08-19 11:09:03 -07002877 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2878
Dan Stoza6b9454d2014-11-07 16:00:59 -08002879 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002880 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002881}
2882
Mathias Agopianad456f92011-01-13 17:53:01 -08002883void SurfaceFlinger::invalidateHwcGeometry()
2884{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002885 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002886}
2887
Robert Carrc0df3122019-04-11 13:18:21 -07002888status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2889 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2890 const sp<IBinder>& parentHandle,
2891 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002892 // add this layer to the current state list
2893 {
2894 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002895 sp<Layer> parent;
2896 if (parentHandle != nullptr) {
2897 parent = fromHandle(parentHandle);
2898 if (parent == nullptr) {
2899 return NAME_NOT_FOUND;
2900 }
2901 } else {
2902 parent = parentLayer;
2903 }
2904
Robert Carr1f0a16a2016-10-24 16:27:39 -07002905 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002906 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002907 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002908 return NO_MEMORY;
2909 }
Robert Carrc0df3122019-04-11 13:18:21 -07002910
2911 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2912
Robert Carrb89ea9d2018-12-10 13:01:14 -08002913 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002914 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002915 } else if (parent == nullptr) {
2916 lbc->onRemovedFromCurrentState();
2917 } else if (parent->isRemovedFromCurrentState()) {
2918 parent->addChild(lbc);
2919 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002920 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002921 parent->addChild(lbc);
2922 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002923
Yiwei Zhang243b3782018-05-15 17:40:04 -07002924 if (gbc != nullptr) {
2925 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2926 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2927 mMaxGraphicBufferProducerListSize,
2928 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2929 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002930 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002931 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002932 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002933 }
2934
Mathias Agopian96f08192010-06-02 23:28:45 -07002935 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002936 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002937
Dan Stoza7d89d062015-04-30 13:29:25 -07002938 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002939}
2940
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002941uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002942 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002943}
2944
Mathias Agopian3f844832013-08-07 21:24:32 -07002945uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002946 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002947}
2948
Mathias Agopian3f844832013-08-07 21:24:32 -07002949uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002950 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002951}
2952
2953uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002954 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002955 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002956 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002957 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002958 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002959 }
2960 return old;
2961}
2962
Marissa Wall713b63f2018-10-17 15:42:43 -07002963bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002964 // to prevent onHandleDestroyed from being called while the lock is held,
2965 // we must keep a copy of the transactions (specifically the composer
2966 // states) around outside the scope of the lock
2967 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002968 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002969 {
2970 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002971
Valerie Haufce31b82019-04-30 16:41:14 -07002972 auto it = mTransactionQueues.begin();
2973 while (it != mTransactionQueues.end()) {
2974 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002975
Valerie Haufce31b82019-04-30 16:41:14 -07002976 while (!transactionQueue.empty()) {
2977 const auto& transaction = transactionQueue.front();
2978 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002979 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002980 transaction.states)) {
2981 setTransactionFlags(eTransactionFlushNeeded);
2982 break;
2983 }
2984 transactions.push_back(transaction);
2985 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2986 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002987 transaction.buffer, transaction.postTime,
2988 transaction.privileged, transaction.hasListenerCallbacks,
2989 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002990 transactionQueue.pop();
2991 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002992 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002993
Valerie Haufce31b82019-04-30 16:41:14 -07002994 if (transactionQueue.empty()) {
2995 it = mTransactionQueues.erase(it);
2996 mTransactionCV.broadcast();
2997 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002998 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002999 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003000 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003001 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003002 return flushedATransaction;
3003}
3004
3005bool SurfaceFlinger::transactionFlushNeeded() {
3006 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003007}
3008
chaviwca27f252018-02-06 16:46:39 -08003009
Marissa Wall17b4e452018-12-26 16:32:34 -08003010bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003011 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003012 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003013 if (!useCachedExpectedPresentTime)
3014 populateExpectedPresentTime();
3015
3016 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003017 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3018 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3019 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3020 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3021 return false;
3022 }
3023
Marissa Wall713b63f2018-10-17 15:42:43 -07003024 for (const ComposerState& state : states) {
3025 const layer_state_t& s = state.state;
3026 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3027 continue;
3028 }
3029 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003030 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003031 }
3032 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003033 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003034}
3035
Valerie Hau9dab9732019-08-20 09:29:25 -07003036void SurfaceFlinger::setTransactionState(
3037 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3038 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3039 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3040 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003041 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003042
Valerie Haubc6ddb12019-03-08 11:10:15 -08003043 const int64_t postTime = systemTime();
3044
Robert Carr14167e02019-02-13 13:50:55 -08003045 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3046
Mathias Agopian698c0872011-06-28 19:09:31 -07003047 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003048
Marissa Wall713b63f2018-10-17 15:42:43 -07003049 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003050 auto itr = mTransactionQueues.find(applyToken);
3051 // if this is an animation frame, wait until prior animation frame has
3052 // been applied by SF
3053 if (flags & eAnimation) {
3054 while (itr != mTransactionQueues.end()) {
3055 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3056 if (CC_UNLIKELY(err != NO_ERROR)) {
3057 ALOGW_IF(err == TIMED_OUT,
3058 "setTransactionState timed out "
3059 "waiting for animation frame to apply");
3060 break;
3061 }
3062 itr = mTransactionQueues.find(applyToken);
3063 }
3064 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003065
3066 // Expected present time is computed and cached on invalidate, so it may be stale.
3067 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3068 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003069 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003070 uncacheBuffer, postTime, privileged,
3071 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003072 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003073 return;
3074 }
3075
Valerie Haubc6ddb12019-03-08 11:10:15 -08003076 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003077 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3078 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003079}
3080
Valerie Hau9dab9732019-08-20 09:29:25 -07003081void SurfaceFlinger::applyTransactionState(
3082 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3083 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3084 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3085 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3086 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003087 uint32_t transactionFlags = 0;
3088
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003089 if (flags & eAnimation) {
3090 // For window updates that are part of an animation we must wait for
3091 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003092 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003093 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003094 if (CC_UNLIKELY(err != NO_ERROR)) {
3095 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003096 // caller after a few seconds.
3097 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3098 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003099 mAnimTransactionPending = false;
3100 break;
3101 }
3102 }
3103 }
3104
chaviwca27f252018-02-06 16:46:39 -08003105 for (const DisplayState& display : displays) {
3106 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003107 }
3108
Valerie Hau9dab9732019-08-20 09:29:25 -07003109 // start and end registration for listeners w/ no surface so they can get their callback. Note
3110 // that listeners with SurfaceControls will start registration during setClientStateLocked
3111 // below.
3112 for (const auto& listener : listenerCallbacks) {
3113 mTransactionCompletedThread.startRegistration(listener);
3114 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003115 }
3116
Valerie Hau9dab9732019-08-20 09:29:25 -07003117 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003118 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003119 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003120 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3121 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003122 }
3123
Valerie Hau9dab9732019-08-20 09:29:25 -07003124 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003125 mTransactionCompletedThread.endRegistration(listenerCallback);
3126 }
3127
Marissa Walle2ffb422018-10-12 11:33:52 -07003128 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003129 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003130 mTransactionCompletedThread.sendCallbacks();
3131 }
3132 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003133
chaviw273171b2018-12-26 11:46:30 -08003134 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3135
Marissa Wall947d34e2019-03-29 14:03:53 -07003136 if (uncacheBuffer.isValid()) {
3137 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003138 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003139 }
3140
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003141 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3142 // anyway. This can be used as a flush mechanism for previous async transactions.
3143 // Empty animation transaction can be used to simulate back-pressure, so also force a
3144 // transaction for empty animation transactions.
3145 if (transactionFlags == 0 &&
3146 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003147 transactionFlags = eTransactionNeeded;
3148 }
3149
Marissa Wall06255332019-03-27 13:48:27 -07003150 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3151 // so we don't have to wake up again next frame to preform an uneeded traversal.
3152 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3153 transactionFlags = transactionFlags & (~eTraversalNeeded);
3154 mTraversalNeededMainThread = true;
3155 }
3156
Mathias Agopian386aa982011-11-07 21:58:03 -08003157 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003158 if (mInterceptor->isEnabled()) {
3159 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003160 }
Irvel468051e2016-06-13 16:44:44 -07003161
Mathias Agopian386aa982011-11-07 21:58:03 -08003162 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003163 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3164 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003165 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003166
3167 // if this is a synchronous transaction, wait for it to take effect
3168 // before returning.
3169 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003170 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003171 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003172 if (flags & eAnimation) {
3173 mAnimTransactionPending = true;
3174 }
chaviw4fe36852019-04-15 16:25:49 -07003175 if (mPendingInputWindowCommands.syncInputWindows) {
3176 mPendingSyncInputWindows = true;
3177 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003178
3179 // applyTransactionState can be called by either the main SF thread or by
3180 // another process through setTransactionState. While a given process may wish
3181 // to wait on synchronous transactions, the main SF thread should never
3182 // be blocked. Therefore, we only wait if isMainThread is false.
3183 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003184 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3185 if (CC_UNLIKELY(err != NO_ERROR)) {
3186 // just in case something goes wrong in SF, return to the
3187 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003188 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3189 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003190 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003191 break;
3192 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003193 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003194 }
3195}
3196
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003197uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3198 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3199 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003200
Mathias Agopiane57f2922012-08-09 16:29:12 -07003201 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003202 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3203
3204 const uint32_t what = s.what;
3205 if (what & DisplayState::eSurfaceChanged) {
3206 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3207 state.surface = s.surface;
3208 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003209 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003210 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003211 if (what & DisplayState::eLayerStackChanged) {
3212 if (state.layerStack != s.layerStack) {
3213 state.layerStack = s.layerStack;
3214 flags |= eDisplayTransactionNeeded;
3215 }
3216 }
3217 if (what & DisplayState::eDisplayProjectionChanged) {
3218 if (state.orientation != s.orientation) {
3219 state.orientation = s.orientation;
3220 flags |= eDisplayTransactionNeeded;
3221 }
3222 if (state.frame != s.frame) {
3223 state.frame = s.frame;
3224 flags |= eDisplayTransactionNeeded;
3225 }
3226 if (state.viewport != s.viewport) {
3227 state.viewport = s.viewport;
3228 flags |= eDisplayTransactionNeeded;
3229 }
3230 }
3231 if (what & DisplayState::eDisplaySizeChanged) {
3232 if (state.width != s.width) {
3233 state.width = s.width;
3234 flags |= eDisplayTransactionNeeded;
3235 }
3236 if (state.height != s.height) {
3237 state.height = s.height;
3238 flags |= eDisplayTransactionNeeded;
3239 }
3240 }
3241
Mathias Agopiane57f2922012-08-09 16:29:12 -07003242 return flags;
3243}
3244
Robert Carr14167e02019-02-13 13:50:55 -08003245bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003246 IPCThreadState* ipc = IPCThreadState::self();
3247 const int pid = ipc->getCallingPid();
3248 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003249 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003250 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003251 return false;
3252 }
3253 return true;
3254}
3255
Marissa Wall3dad52d2019-03-22 14:03:19 -07003256uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003257 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3258 bool privileged,
3259 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003260 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003261
Valerie Hau9dab9732019-08-20 09:29:25 -07003262 for (auto& listener : s.listeners) {
3263 // note that startRegistration will not re-register if the listener has
3264 // already be registered for a prior surface control
3265 mTransactionCompletedThread.startRegistration(listener);
3266 listenerCallbacks.insert(listener);
3267 }
3268
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003269 sp<Layer> layer = nullptr;
3270 if (s.surface) {
3271 layer = fromHandle(s.surface);
3272 } else {
3273 // The client may provide us a null handle. Treat it as if the layer was removed.
3274 ALOGW("Attempt to set client state with a null layer handle");
3275 }
chaviw8b3871a2017-11-01 17:41:01 -07003276 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003277 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003278 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003279 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003280 }
chaviw8b3871a2017-11-01 17:41:01 -07003281 return 0;
3282 }
3283
chaviw8b3871a2017-11-01 17:41:01 -07003284 uint32_t flags = 0;
3285
Garfield Tan8a3083e2018-12-03 13:21:07 -08003286 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003287
3288 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3289 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003290 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003291 layer->pushPendingState();
3292 }
3293
chaviw8b3871a2017-11-01 17:41:01 -07003294 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003295 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003296 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003297 }
chaviw8b3871a2017-11-01 17:41:01 -07003298 }
3299 if (what & layer_state_t::eLayerChanged) {
3300 // NOTE: index needs to be calculated before we update the state
3301 const auto& p = layer->getParent();
3302 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003303 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003304 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003305 mCurrentState.layersSortedByZ.removeAt(idx);
3306 mCurrentState.layersSortedByZ.add(layer);
3307 // we need traversal (state changed)
3308 // AND transaction (list changed)
3309 flags |= eTransactionNeeded|eTraversalNeeded;
3310 }
chaviw8b3871a2017-11-01 17:41:01 -07003311 } else {
3312 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003313 flags |= eTransactionNeeded|eTraversalNeeded;
3314 }
3315 }
chaviw8b3871a2017-11-01 17:41:01 -07003316 }
3317 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003318 // NOTE: index needs to be calculated before we update the state
3319 const auto& p = layer->getParent();
3320 if (p == nullptr) {
3321 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3322 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3323 mCurrentState.layersSortedByZ.removeAt(idx);
3324 mCurrentState.layersSortedByZ.add(layer);
3325 // we need traversal (state changed)
3326 // AND transaction (list changed)
3327 flags |= eTransactionNeeded|eTraversalNeeded;
3328 }
3329 } else {
3330 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3331 flags |= eTransactionNeeded|eTraversalNeeded;
3332 }
chaviw8b3871a2017-11-01 17:41:01 -07003333 }
3334 }
3335 if (what & layer_state_t::eSizeChanged) {
3336 if (layer->setSize(s.w, s.h)) {
3337 flags |= eTraversalNeeded;
3338 }
3339 }
3340 if (what & layer_state_t::eAlphaChanged) {
3341 if (layer->setAlpha(s.alpha))
3342 flags |= eTraversalNeeded;
3343 }
3344 if (what & layer_state_t::eColorChanged) {
3345 if (layer->setColor(s.color))
3346 flags |= eTraversalNeeded;
3347 }
Peiyong Lind3788632018-09-18 16:01:31 -07003348 if (what & layer_state_t::eColorTransformChanged) {
3349 if (layer->setColorTransform(s.colorTransform)) {
3350 flags |= eTraversalNeeded;
3351 }
3352 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003353 if (what & layer_state_t::eBackgroundColorChanged) {
3354 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3355 flags |= eTraversalNeeded;
3356 }
3357 }
chaviw8b3871a2017-11-01 17:41:01 -07003358 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003359 // TODO: b/109894387
3360 //
3361 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3362 // rotation. To see the problem observe that if we have a square parent, and a child
3363 // of the same size, then we rotate the child 45 degrees around it's center, the child
3364 // must now be cropped to a non rectangular 8 sided region.
3365 //
3366 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3367 // private API, and the WindowManager only uses rotation in one case, which is on a top
3368 // level layer in which cropping is not an issue.
3369 //
3370 // However given that abuse of rotation matrices could lead to surfaces extending outside
3371 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3372 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3373 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003374 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003375 flags |= eTraversalNeeded;
3376 }
3377 if (what & layer_state_t::eTransparentRegionChanged) {
3378 if (layer->setTransparentRegionHint(s.transparentRegion))
3379 flags |= eTraversalNeeded;
3380 }
3381 if (what & layer_state_t::eFlagsChanged) {
3382 if (layer->setFlags(s.flags, s.mask))
3383 flags |= eTraversalNeeded;
3384 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003385 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003386 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003387 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003388 if (what & layer_state_t::eCornerRadiusChanged) {
3389 if (layer->setCornerRadius(s.cornerRadius))
3390 flags |= eTraversalNeeded;
3391 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003392 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3393 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3394 }
chaviw8b3871a2017-11-01 17:41:01 -07003395 if (what & layer_state_t::eLayerStackChanged) {
3396 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3397 // We only allow setting layer stacks for top level layers,
3398 // everything else inherits layer stack from its parent.
3399 if (layer->hasParent()) {
3400 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003401 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003402 } else if (idx < 0) {
3403 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003404 "that also does not appear in the top level layer list. Something"
3405 " has gone wrong.",
3406 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003407 } else if (layer->setLayerStack(s.layerStack)) {
3408 mCurrentState.layersSortedByZ.removeAt(idx);
3409 mCurrentState.layersSortedByZ.add(layer);
3410 // we need traversal (state changed)
3411 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003412 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003413 }
3414 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003415 if (what & layer_state_t::eDeferTransaction_legacy) {
3416 if (s.barrierHandle_legacy != nullptr) {
3417 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3418 } else if (s.barrierGbp_legacy != nullptr) {
3419 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003420 if (authenticateSurfaceTextureLocked(gbp)) {
3421 const auto& otherLayer =
3422 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003423 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003424 } else {
3425 ALOGE("Attempt to defer transaction to to an"
3426 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003427 }
3428 }
chaviw8b3871a2017-11-01 17:41:01 -07003429 // We don't trigger a traversal here because if no other state is
3430 // changed, we don't want this to cause any more work
3431 }
chaviw8b3871a2017-11-01 17:41:01 -07003432 if (what & layer_state_t::eReparentChildren) {
3433 if (layer->reparentChildren(s.reparentHandle)) {
3434 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003435 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003436 }
chaviw8b3871a2017-11-01 17:41:01 -07003437 if (what & layer_state_t::eDetachChildren) {
3438 layer->detachChildren();
3439 }
3440 if (what & layer_state_t::eOverrideScalingModeChanged) {
3441 layer->setOverrideScalingMode(s.overrideScalingMode);
3442 // We don't trigger a traversal here because if no other state is
3443 // changed, we don't want this to cause any more work
3444 }
Marissa Wall61c58622018-07-18 10:12:20 -07003445 if (what & layer_state_t::eTransformChanged) {
3446 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3447 }
3448 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3449 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3450 flags |= eTraversalNeeded;
3451 }
3452 if (what & layer_state_t::eCropChanged) {
3453 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3454 }
Marissa Wall861616d2018-10-22 12:52:23 -07003455 if (what & layer_state_t::eFrameChanged) {
3456 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3457 }
Marissa Wall61c58622018-07-18 10:12:20 -07003458 if (what & layer_state_t::eAcquireFenceChanged) {
3459 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3460 }
3461 if (what & layer_state_t::eDataspaceChanged) {
3462 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3463 }
3464 if (what & layer_state_t::eHdrMetadataChanged) {
3465 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3466 }
3467 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3468 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3469 }
3470 if (what & layer_state_t::eApiChanged) {
3471 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3472 }
3473 if (what & layer_state_t::eSidebandStreamChanged) {
3474 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3475 }
Robert Carr720e5062018-07-30 17:45:14 -07003476 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003477 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003478 layer->setInputInfo(s.inputInfo);
3479 flags |= eTraversalNeeded;
3480 } else {
3481 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3482 }
Robert Carr720e5062018-07-30 17:45:14 -07003483 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003484 if (what & layer_state_t::eMetadataChanged) {
3485 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3486 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003487 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3488 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3489 flags |= eTraversalNeeded;
3490 }
3491 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003492 if (what & layer_state_t::eShadowRadiusChanged) {
3493 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3494 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003495 if (what & layer_state_t::eFrameRateSelectionPriority) {
3496 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3497 flags |= eTraversalNeeded;
3498 }
3499 }
Steven Thomas3172e202020-01-06 19:25:30 -08003500 if (what & layer_state_t::eFrameRateChanged) {
3501 if (layer->setFrameRate(s.frameRate)) flags |= eTraversalNeeded;
3502 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003503 // This has to happen after we reparent children because when we reparent to null we remove
3504 // child layers from current state and remove its relative z. If the children are reparented in
3505 // the same transaction, then we have to make sure we reparent the children first so we do not
3506 // lose its relative z order.
3507 if (what & layer_state_t::eReparent) {
3508 bool hadParent = layer->hasParent();
3509 if (layer->reparent(s.parentHandleForChild)) {
3510 if (!hadParent) {
3511 mCurrentState.layersSortedByZ.remove(layer);
3512 }
3513 flags |= eTransactionNeeded | eTraversalNeeded;
3514 }
3515 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003516 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003517 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3518 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003519 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3520 }
3521 }
Marissa Wall78b72202019-03-15 14:58:34 -07003522 bool bufferChanged = what & layer_state_t::eBufferChanged;
3523 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3524 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003525 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003526 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003527 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3528 if (success) {
3529 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3530 success = ClientCache::getInstance()
3531 .registerErasedRecipient(s.cachedBuffer,
3532 wp<ClientCache::ErasedRecipient>(this));
3533 if (!success) {
3534 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3535 }
3536 }
Marissa Wall78b72202019-03-15 14:58:34 -07003537 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003538 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003539 } else if (bufferChanged) {
3540 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003541 }
Marissa Wall78b72202019-03-15 14:58:34 -07003542 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003543 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003544 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003545 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003546 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003547 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3548 // Do not put anything that updates layer state or modifies flags after
3549 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003550 return flags;
3551}
3552
chaviw273171b2018-12-26 11:46:30 -08003553uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3554 uint32_t flags = 0;
3555 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3556 flags |= eTraversalNeeded;
3557 }
3558
chaviwa911b102019-02-14 10:18:33 -08003559 if (inputWindowCommands.syncInputWindows) {
3560 flags |= eTraversalNeeded;
3561 }
3562
Vishnu Nairec0ab382019-02-13 15:32:56 -08003563 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003564 return flags;
3565}
3566
chaviwfe94a222019-08-21 13:52:59 -07003567status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3568 sp<IBinder>* outHandle) {
3569 if (!mirrorFromHandle) {
3570 return NAME_NOT_FOUND;
3571 }
3572
3573 sp<Layer> mirrorLayer;
3574 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003575 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003576
3577 {
3578 Mutex::Autolock _l(mStateLock);
3579 mirrorFrom = fromHandle(mirrorFromHandle);
3580 if (!mirrorFrom) {
3581 return NAME_NOT_FOUND;
3582 }
3583
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003584 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3585 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003586 if (result != NO_ERROR) {
3587 return result;
3588 }
3589
3590 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3591 }
3592
3593 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3594}
3595
Marissa Wall2d814fb2019-04-09 18:52:57 +00003596status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3597 uint32_t h, PixelFormat format, uint32_t flags,
3598 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003599 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003600 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3601 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003602 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003603 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003604 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003605 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003606 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003607
Robert Carrc0df3122019-04-11 13:18:21 -07003608 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3609 "Expected only one of parentLayer or parentHandle to be non-null. "
3610 "Programmer error?");
3611
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003612 status_t result = NO_ERROR;
3613
3614 sp<Layer> layer;
3615
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003616 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003617
Evan Roskya1f1e152019-01-24 16:17:46 -08003618 bool primaryDisplayOnly = false;
3619
3620 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3621 // TODO b/64227542
3622 if (metadata.has(METADATA_WINDOW_TYPE)) {
3623 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3624 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003625 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003626 primaryDisplayOnly = true;
3627 }
3628 }
3629
Mathias Agopian3165cc22012-08-08 19:42:09 -07003630 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003631 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003632 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3633 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003634
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003635 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003636 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003637 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003638 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003639 break;
chaviw13fdc492017-06-27 12:40:18 -07003640 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003641 // check if buffer size is set for color layer.
3642 if (w > 0 || h > 0) {
3643 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3644 int(w), int(h));
3645 return BAD_VALUE;
3646 }
3647
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003648 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3649 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003650 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003651 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003652 // check if buffer size is set for container layer.
3653 if (w > 0 || h > 0) {
3654 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3655 int(w), int(h));
3656 return BAD_VALUE;
3657 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003658 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3659 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003660 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003661 default:
3662 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003663 break;
3664 }
3665
Dan Stoza7d89d062015-04-30 13:29:25 -07003666 if (result != NO_ERROR) {
3667 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003668 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003669
Evan Roskya1f1e152019-01-24 16:17:46 -08003670 if (primaryDisplayOnly) {
3671 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003672 }
3673
Robert Carrb89ea9d2018-12-10 13:01:14 -08003674 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003675 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3676 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003677 if (result != NO_ERROR) {
3678 return result;
3679 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003680 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003681
3682 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003683 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003684}
3685
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003686std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3687 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003688
3689 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003690 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003691
Dan Stoza436ccf32018-06-21 12:10:12 -07003692 // Grab the state lock since we're accessing mCurrentState
3693 Mutex::Autolock lock(mStateLock);
3694
Cody Northropbc755282017-03-31 12:00:08 -06003695 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003696 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003697 while (matchFound) {
3698 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003699 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003700 if (layer->getName() == uniqueName) {
3701 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003702 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003703 }
3704 });
3705 }
3706
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003707 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003708 return uniqueName;
3709}
3710
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003711status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003712 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003713 LayerMetadata metadata, PixelFormat& format,
3714 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003715 sp<IGraphicBufferProducer>* gbp,
3716 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003717 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003718 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003719 case PIXEL_FORMAT_TRANSPARENT:
3720 case PIXEL_FORMAT_TRANSLUCENT:
3721 format = PIXEL_FORMAT_RGBA_8888;
3722 break;
3723 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003724 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003725 break;
3726 }
3727
chaviwb4c6e582019-08-16 14:35:07 -07003728 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003729 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003730 args.textureName = getNewTexture();
3731 {
3732 // Grab the SF state lock during this since it's the only safe way to access
3733 // RenderEngine when creating a BufferLayerConsumer
3734 // TODO: Check if this lock is still needed here
3735 Mutex::Autolock lock(mStateLock);
3736 layer = getFactory().createBufferQueueLayer(args);
3737 }
3738
Marissa Wallfd668622018-05-10 10:21:13 -07003739 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003740 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003741 *handle = layer->getHandle();
3742 *gbp = layer->getProducer();
3743 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003744 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003745
Marissa Wallfd668622018-05-10 10:21:13 -07003746 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003747 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003748}
3749
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003750status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003751 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003752 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003753 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003754 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003755 args.displayDevice = getDefaultDisplayDevice();
3756 args.textureName = getNewTexture();
3757 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003758 if (outTransformHint) {
3759 *outTransformHint = layer->getTransformHint();
3760 }
Marissa Wall61c58622018-07-18 10:12:20 -07003761 *handle = layer->getHandle();
3762 *outLayer = layer;
3763
3764 return NO_ERROR;
3765}
3766
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003767status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003768 uint32_t h, uint32_t flags, LayerMetadata metadata,
3769 sp<IBinder>* handle, sp<Layer>* outLayer) {
3770 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003771 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003772 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003773 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003774}
3775
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003776status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003777 uint32_t w, uint32_t h, uint32_t flags,
3778 LayerMetadata metadata, sp<IBinder>* handle,
3779 sp<Layer>* outLayer) {
3780 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003781 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003782 *handle = (*outLayer)->getHandle();
3783 return NO_ERROR;
3784}
3785
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003786void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003787 mLayersPendingRemoval.add(layer);
3788 mLayersRemoved = true;
3789 setTransactionFlags(eTransactionNeeded);
3790}
3791
Robert Carr695d5282018-12-18 15:27:58 -08003792void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003793{
Robert Carr2e102c92018-10-23 12:11:15 -07003794 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003795 // If a layer has a parent, we allow it to out-live it's handle
3796 // with the idea that the parent holds a reference and will eventually
3797 // be cleaned up. However no one cleans up the top-level so we do so
3798 // here.
3799 if (layer->getParent() == nullptr) {
3800 mCurrentState.layersSortedByZ.remove(layer);
3801 }
3802 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003803
3804 auto it = mLayersByLocalBinderToken.begin();
3805 while (it != mLayersByLocalBinderToken.end()) {
3806 if (it->second == layer) {
3807 it = mLayersByLocalBinderToken.erase(it);
3808 } else {
3809 it++;
3810 }
3811 }
3812
Robert Carr695d5282018-12-18 15:27:58 -08003813 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003814}
3815
Mathias Agopianb60314a2012-04-10 22:09:54 -07003816// ---------------------------------------------------------------------------
3817
Andy McFadden13a082e2012-08-24 10:16:42 -07003818void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003819 const auto display = getDefaultDisplayDeviceLocked();
3820 if (!display) return;
3821
3822 const sp<IBinder> token = display->getDisplayToken().promote();
3823 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003824
Jesse Hall01e29052013-02-19 16:13:35 -08003825 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003826 Vector<ComposerState> state;
3827 Vector<DisplayState> displays;
3828 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003829 d.what = DisplayState::eDisplayProjectionChanged |
3830 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003831 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003832 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003833 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003834 d.frame.makeInvalid();
3835 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003836 d.width = 0;
3837 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003838 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003839 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3840 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003841
Dominik Laskowskie9774092018-12-11 10:04:24 -08003842 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003843
Dominik Laskowski83b88212018-12-11 13:34:06 -08003844 const nsecs_t vsyncPeriod = getVsyncPeriod();
3845 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003846
Brian Andersond0010582017-03-07 13:20:31 -08003847 // Use phase of 0 since phase is not known.
3848 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003849 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003850 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003851}
3852
3853void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003854 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003855 postMessageAsync(
3856 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003857}
3858
Ady Abraham27c70212019-06-11 10:52:26 -07003859void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3860 if (mHWCVsyncState != enabled) {
3861 getHwComposer().setVsyncEnabled(displayId, enabled);
3862 mHWCVsyncState = enabled;
3863 }
3864}
3865
Dominik Laskowskie9774092018-12-11 10:04:24 -08003866void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003867 if (display->isVirtual()) {
3868 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003869 return;
3870 }
3871
Dominik Laskowski075d3172018-05-24 15:50:06 -07003872 const auto displayId = display->getId();
3873 LOG_ALWAYS_FATAL_IF(!displayId);
3874
Dominik Laskowski34157762018-10-31 13:07:19 -07003875 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003876
3877 int currentMode = display->getPowerMode();
3878 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003879 return;
3880 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003881
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003882 display->setPowerMode(mode);
3883
Lloyd Pique4dccc412018-01-22 17:21:36 -08003884 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003885 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003886 }
3887
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003888 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003889 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003890 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003891 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003892 mScheduler->onScreenAcquired(mAppConnectionHandle);
3893 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003894 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003895
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003896 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003897 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003898 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003899
3900 struct sched_param param = {0};
3901 param.sched_priority = 1;
3902 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3903 ALOGW("Couldn't set SCHED_FIFO on display on");
3904 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003905 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003906 // Turn off the display
3907 struct sched_param param = {0};
3908 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3909 ALOGW("Couldn't set SCHED_OTHER on display off");
3910 }
3911
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003912 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003913 mScheduler->disableHardwareVsync(true);
3914 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003915 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003916
Ady Abraham27c70212019-06-11 10:52:26 -07003917 // Make sure HWVsync is disabled before turning off the display
3918 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3919
Dominik Laskowski075d3172018-05-24 15:50:06 -07003920 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003921 mVisibleRegionsDirty = true;
3922 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003923 } else if (mode == HWC_POWER_MODE_DOZE ||
3924 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003925 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003926 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003927 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003928 mScheduler->onScreenAcquired(mAppConnectionHandle);
3929 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003930 }
3931 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3932 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003933 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003934 mScheduler->disableHardwareVsync(true);
3935 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003936 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003937 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003938 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003939 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003940 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003941 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003942
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003943 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003944 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003945 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003946 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003947 }
3948
Dominik Laskowski34157762018-10-31 13:07:19 -07003949 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003950}
3951
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003952void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003953 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003954 const auto display = getDisplayDevice(displayToken);
3955 if (!display) {
3956 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3957 displayToken.get());
3958 } else if (display->isVirtual()) {
3959 ALOGW("Attempt to set power mode %d for virtual display", mode);
3960 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003961 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003962 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003963 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003964}
3965
3966// ---------------------------------------------------------------------------
3967
Dominik Laskowskic2867142019-01-21 11:33:38 -08003968status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3969 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003970 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003971
Mathias Agopianbd115332013-04-18 16:41:04 -07003972 IPCThreadState* ipc = IPCThreadState::self();
3973 const int pid = ipc->getCallingPid();
3974 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003975
Mathias Agopianbd115332013-04-18 16:41:04 -07003976 if ((uid != AID_SHELL) &&
3977 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003978 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3979 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003980 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003981 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003982 // (this would indicate SF is stuck, but we want to be able to
3983 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003984 status_t err = mStateLock.timedLock(s2ns(1));
3985 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003986 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003987 StringAppendF(&result,
3988 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3989 "(no locks held)\n",
3990 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003991 }
3992
Dominik Laskowskic2867142019-01-21 11:33:38 -08003993 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003994 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003995 {"--dispsync"s,
3996 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003997 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003998 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3999 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
4000 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4001 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4002 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4003 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004004 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004005 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4006 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004007
Dominik Laskowskic2867142019-01-21 11:33:38 -08004008 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004009
Dominik Laskowski46470112019-08-02 13:13:11 -07004010 const auto it = dumpers.find(flag);
4011 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004012 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004013 } else if (!asProto) {
4014 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004015 }
4016
Mathias Agopian9795c422009-08-26 16:36:26 -07004017 if (locked) {
4018 mStateLock.unlock();
4019 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004020
Dominik Laskowski46470112019-08-02 13:13:11 -07004021 if (it == dumpers.end()) {
4022 const LayersProto layersProto = dumpProtoFromMainThread();
4023 if (asProto) {
4024 result.append(layersProto.SerializeAsString());
4025 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004026 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004027 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4028 result.append(LayerProtoParser::layerTreeToString(layerTree));
4029 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004030 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004031 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004032 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004033 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004034 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004035 return NO_ERROR;
4036}
4037
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004038status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4039 if (asProto && mTracing.isEnabled()) {
4040 mTracing.writeToFileAsync();
4041 }
4042
4043 return doDump(fd, DumpArgs(), asProto);
4044}
4045
Dominik Laskowskic2867142019-01-21 11:33:38 -08004046void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004047 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004048 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004049}
4050
Dominik Laskowskic2867142019-01-21 11:33:38 -08004051void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004052 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004053
Dominik Laskowskic2867142019-01-21 11:33:38 -08004054 if (args.size() > 1) {
4055 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004056 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004057 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004058 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004059 }
Robert Carr2047fae2016-11-28 14:09:09 -08004060 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004061 } else {
4062 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004063 }
4064}
4065
Dominik Laskowskic2867142019-01-21 11:33:38 -08004066void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004067 const bool clearAll = args.size() < 2;
4068 const auto name = clearAll ? String8() : String8(args[1]);
4069
Robert Carr2047fae2016-11-28 14:09:09 -08004070 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004071 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004072 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004073 }
Robert Carr2047fae2016-11-28 14:09:09 -08004074 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004075
Svetoslavd85084b2014-03-20 10:28:31 -07004076 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004077}
4078
Dominik Laskowskic2867142019-01-21 11:33:38 -08004079void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4080 mTimeStats->parseArgs(asProto, args, result);
4081}
4082
Jamie Gennis6547ff42013-07-16 20:12:42 -07004083// This should only be called from the main thread. Otherwise it would need
4084// the lock and should use mCurrentState rather than mDrawingState.
4085void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004086 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004087 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004088 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004089
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004090 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004091}
4092
Yiwei Zhang5434a782018-12-05 18:06:32 -08004093void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004094 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004095
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004096 if (isLayerTripleBufferingDisabled())
4097 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004098
Yiwei Zhang5434a782018-12-05 18:06:32 -08004099 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4100 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4101 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4102 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4103 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4104 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004105 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004106}
4107
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004108void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004109 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004110
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004111 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004112 result.append("\n");
4113
Ady Abraham9e16a482019-12-03 17:19:41 -08004114 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004115 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004116 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004117 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004118
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004119 HwcConfigIndexType defaultConfig;
4120 float minFps, maxFps;
4121 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004122 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004123 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004124 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004125 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004126 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4127 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004128
Ana Krulecc2870422019-01-29 19:00:58 -08004129 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004130}
4131
Yiwei Zhang5434a782018-12-05 18:06:32 -08004132void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4133 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004134 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4135 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004136 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004137 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004138 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004139 }
David Sodman4a36e932017-11-07 14:29:47 -08004140 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004141 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004142 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004143 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4144 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004145}
4146
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004147void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4148 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004149 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4150 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004151 for (const auto& segment : history) {
4152 if (!segment.usedThirdBuffer) {
4153 stats.twoBufferTime += segment.totalTime;
4154 }
4155 if (segment.occupancyAverage < 1.0f) {
4156 stats.doubleBufferedTime += segment.totalTime;
4157 } else if (segment.occupancyAverage < 2.0f) {
4158 stats.tripleBufferedTime += segment.totalTime;
4159 }
4160 ++stats.numSegments;
4161 stats.totalTime += segment.totalTime;
4162 }
4163}
4164
Yiwei Zhang5434a782018-12-05 18:06:32 -08004165void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4166 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004167
4168 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4169 const size_t count = currentLayers.size();
4170 for (size_t i=0 ; i<count ; i++) {
4171 currentLayers[i]->dumpFrameEvents(result);
4172 }
4173}
4174
Yiwei Zhang5434a782018-12-05 18:06:32 -08004175void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004176 result.append("Buffering stats:\n");
4177 result.append(" [Layer name] <Active time> <Two buffer> "
4178 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004179 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004180 typedef std::tuple<std::string, float, float, float> BufferTuple;
4181 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004182 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004183 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004184 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004185 if (stats.numSegments == 0) {
4186 continue;
4187 }
4188 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4189 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4190 stats.totalTime;
4191 float doubleBufferRatio = static_cast<float>(
4192 stats.doubleBufferedTime) / stats.totalTime;
4193 float tripleBufferRatio = static_cast<float>(
4194 stats.tripleBufferedTime) / stats.totalTime;
4195 sorted.insert({activeTime, {name, twoBufferRatio,
4196 doubleBufferRatio, tripleBufferRatio}});
4197 }
4198 for (const auto& sortedPair : sorted) {
4199 float activeTime = sortedPair.first;
4200 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004201 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4202 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004203 }
4204 result.append("\n");
4205}
4206
Yiwei Zhang5434a782018-12-05 18:06:32 -08004207void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004208 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004209 const auto displayId = display->getId();
4210 if (!displayId) {
4211 continue;
4212 }
4213 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004214 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004215 continue;
4216 }
4217
Yiwei Zhang5434a782018-12-05 18:06:32 -08004218 StringAppendF(&result,
4219 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4220 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004221 uint8_t port;
4222 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004223 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004224 result.append("no identification data\n");
4225 continue;
4226 }
4227
4228 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004229 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004230 continue;
4231 }
4232
4233 const auto edid = parseEdid(data);
4234 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004235 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004236 continue;
4237 }
4238
Yiwei Zhang5434a782018-12-05 18:06:32 -08004239 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004240 result.append(edid->displayName.data(), edid->displayName.length());
4241 result.append("\"\n");
4242 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004243}
4244
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004245void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4246 std::string& result) const {
4247 hwc2_display_t hwcDisplayId;
4248 uint8_t port;
4249 DisplayIdentificationData data;
4250
4251 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4252 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4253 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4254 }
4255}
4256
Yiwei Zhang5434a782018-12-05 18:06:32 -08004257void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004258 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004259 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4260 StringAppendF(&result, "DisplayColorSetting: %s\n",
4261 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004262
4263 // TODO: print out if wide-color mode is active or not
4264
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004265 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004266 const auto displayId = display->getId();
4267 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004268 continue;
4269 }
4270
Yiwei Zhang5434a782018-12-05 18:06:32 -08004271 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004272 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004273 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004274 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004275 }
4276
Lloyd Pique32cbe282018-10-19 13:09:22 -07004277 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004278 StringAppendF(&result, " Current color mode: %s (%d)\n",
4279 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004280 }
4281 result.append("\n");
4282}
4283
Vishnu Nair8406fd72019-07-30 11:29:31 -07004284LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004285 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004286 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4287 layer->writeToProto(layersProto, traceFlags);
4288 }
chaviw1d044282017-09-27 12:19:28 -07004289 return layersProto;
4290}
4291
Vishnu Nair0f085c62019-08-30 08:49:12 -07004292void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4293 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4294 // it.
4295 LayerProto* rootProto = layersProto.add_layers();
4296 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4297 rootProto->set_id(offscreenRootLayerId);
4298 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004299 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004300
4301 for (Layer* offscreenLayer : mOffscreenLayers) {
4302 // Add layer as child of the fake root
4303 rootProto->add_children(offscreenLayer->sequence);
4304
4305 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004306 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004307 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004308 }
4309}
4310
Vishnu Nair8406fd72019-07-30 11:29:31 -07004311LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4312 LayersProto layersProto;
4313 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4314 return layersProto;
4315}
4316
Vishnu Nair0f085c62019-08-30 08:49:12 -07004317void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4318 result.append("Offscreen Layers:\n");
4319 postMessageSync(new LambdaMessage([&]() {
4320 for (Layer* offscreenLayer : mOffscreenLayers) {
4321 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4322 layer->dumpCallingUidPid(result);
4323 });
4324 }
4325 }));
4326}
4327
Dominik Laskowskic2867142019-01-21 11:33:38 -08004328void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4329 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004330 Colorizer colorizer(colorize);
4331
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004332 // figure out if we're stuck somewhere
4333 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004334 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004335 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4336
4337 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004338 * Dump library configuration.
4339 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004340
4341 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004342 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004343 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004344 appendSfConfigString(result);
4345 appendUiConfigString(result);
4346 appendGuiConfigString(result);
4347 result.append("\n");
4348
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004349 result.append("\nDisplay identification data:\n");
4350 dumpDisplayIdentificationData(result);
4351
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004352 result.append("\nWide-Color information:\n");
4353 dumpWideColorInfo(result);
4354
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004355 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004356 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004357 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004358 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004359 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004360
Andy McFadden41d67d72014-04-25 16:58:34 -07004361 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004362 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004363 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004364 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004365 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004366
Dan Stozab90cf072015-03-05 11:05:59 -08004367 dumpStaticScreenStats(result);
4368 result.append("\n");
4369
Alec Mouri40189b02019-03-05 15:07:54 -08004370 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4371 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4372 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004373
Dan Stozae77c7662016-05-13 11:37:28 -07004374 dumpBufferingStats(result);
4375
Andy McFadden4803b742012-09-24 19:07:20 -07004376 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004377 * Dump the visible layer list
4378 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004379 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004380 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004381 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4382 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004383 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004384
Chia-I Wu2f884132018-09-13 15:17:58 -07004385 {
Lloyd Pique207def92019-02-28 16:09:52 -08004386 StringAppendF(&result, "Composition layers\n");
4387 mDrawingState.traverseInZOrder([&](Layer* layer) {
4388 auto compositionLayer = layer->getCompositionLayer();
4389 if (compositionLayer) compositionLayer->dump(result);
4390 });
4391 }
4392
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004393 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004394 * Dump Display state
4395 */
4396
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004397 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004398 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004399 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004400 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004401 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004402 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004403 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004404
4405 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004406 * Dump CompositionEngine state
4407 */
4408
4409 mCompositionEngine->dump(result);
4410
4411 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004412 * Dump SurfaceFlinger global state
4413 */
4414
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004415 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004416 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004417 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004418
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004419 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004420
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004421 DebugEGLImageTracker::getInstance()->dump(result);
4422
Dominik Laskowski075d3172018-05-24 15:50:06 -07004423 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004424 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4425 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004426 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4427 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004428 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004429 StringAppendF(&result,
4430 " transaction-flags : %08x\n"
4431 " gpu_to_cpu_unsupported : %d\n",
4432 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004433
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004434 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004435 displayId && getHwComposer().isConnected(*displayId)) {
4436 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004437 StringAppendF(&result,
4438 " refresh-rate : %f fps\n"
4439 " x-dpi : %f\n"
4440 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004441 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4442 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004443 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004444
Yiwei Zhang5434a782018-12-05 18:06:32 -08004445 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004446
Dan Stozae22aec72016-08-01 13:20:59 -07004447 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004448 * Tracing state
4449 */
4450 mTracing.dump(result);
4451 result.append("\n");
4452
4453 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004454 * HWC layer minidump
4455 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004456 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004457 const auto displayId = display->getId();
4458 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004459 continue;
4460 }
4461
Yiwei Zhang5434a782018-12-05 18:06:32 -08004462 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004463 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004464 const sp<DisplayDevice> displayDevice = display;
4465 mCurrentState.traverseInZOrder(
4466 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004467 result.append("\n");
4468 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004469
4470 /*
4471 * Dump HWComposer state
4472 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004473 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004474 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004475 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004476 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004477 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004478 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004479
4480 /*
4481 * Dump gralloc state
4482 */
4483 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4484 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004485
4486 /*
4487 * Dump VrFlinger state if in use.
4488 */
4489 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4490 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004491 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004492 result.append("\n");
4493 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004494
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004495 result.append(mTimeStats->miniDump());
4496 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004497}
4498
Chia-I Wu28f320b2018-05-03 11:02:56 -07004499void SurfaceFlinger::updateColorMatrixLocked() {
4500 mat4 colorMatrix;
4501 if (mGlobalSaturationFactor != 1.0f) {
4502 // Rec.709 luma coefficients
4503 float3 luminance{0.213f, 0.715f, 0.072f};
4504 luminance *= 1.0f - mGlobalSaturationFactor;
4505 mat4 saturationMatrix = mat4(
4506 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4507 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4508 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4509 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4510 );
4511 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4512 } else {
4513 colorMatrix = mClientColorMatrix * mDaltonizer();
4514 }
4515
4516 if (mCurrentState.colorMatrix != colorMatrix) {
4517 mCurrentState.colorMatrix = colorMatrix;
4518 mCurrentState.colorMatrixChanged = true;
4519 setTransactionFlags(eTransactionNeeded);
4520 }
4521}
4522
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004523status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004524#pragma clang diagnostic push
4525#pragma clang diagnostic error "-Wswitch-enum"
4526 switch (static_cast<ISurfaceComposerTag>(code)) {
4527 // These methods should at minimum make sure that the client requested
4528 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004529 case BOOT_FINISHED:
4530 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004531 case CREATE_DISPLAY:
4532 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004533 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004534 case GET_ANIMATION_FRAME_STATS:
4535 case GET_HDR_CAPABILITIES:
Ana Krulec0782b882019-10-15 17:34:54 -07004536 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004537 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004538 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004539 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4540 case SET_AUTO_LOW_LATENCY_MODE:
4541 case GET_GAME_CONTENT_TYPE_SUPPORT:
4542 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004543 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004544 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004545 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004546 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004547 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004548 case NOTIFY_POWER_HINT:
4549 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004550 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4551 IPCThreadState* ipc = IPCThreadState::self();
4552 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4553 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004554 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004555 }
Robert Carr1db73f62016-12-21 12:58:51 -08004556 return OK;
4557 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004558 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004559 IPCThreadState* ipc = IPCThreadState::self();
4560 const int pid = ipc->getCallingPid();
4561 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004562 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4563 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004564 return PERMISSION_DENIED;
4565 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004566 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004567 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004568 // Used by apps to hook Choreographer to SurfaceFlinger.
4569 case CREATE_DISPLAY_EVENT_CONNECTION:
4570 // The following calls are currently used by clients that do not
4571 // request necessary permissions. However, they do not expose any secret
4572 // information, so it is OK to pass them.
4573 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004574 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004575 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004576 case GET_PHYSICAL_DISPLAY_IDS:
4577 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004578 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004579 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004580 case GET_DISPLAY_CONFIGS:
4581 case GET_DISPLAY_STATS:
4582 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4583 // Calling setTransactionState is safe, because you need to have been
4584 // granted a reference to Client* and Handle* to do anything with it.
4585 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004586 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004587 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004588 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004589 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004590 case IS_WIDE_COLOR_DISPLAY:
4591 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4592 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004593 return OK;
4594 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004595 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004596 case CAPTURE_SCREEN:
4597 case ADD_REGION_SAMPLING_LISTENER:
4598 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004599 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004600 IPCThreadState* ipc = IPCThreadState::self();
4601 const int pid = ipc->getCallingPid();
4602 const int uid = ipc->getCallingUid();
4603 if ((uid != AID_GRAPHICS) &&
4604 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4605 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4606 return PERMISSION_DENIED;
4607 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004608 return OK;
4609 }
4610 // The following codes are deprecated and should never be allowed to access SF.
4611 case CONNECT_DISPLAY_UNUSED:
4612 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4613 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4614 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004615 }
chaviw93df2ea2019-04-30 16:45:12 -07004616 case CAPTURE_SCREEN_BY_ID: {
4617 IPCThreadState* ipc = IPCThreadState::self();
4618 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004619 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004620 return OK;
4621 }
4622 return PERMISSION_DENIED;
4623 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004624 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004625
4626 // These codes are used for the IBinder protocol to either interrogate the recipient
4627 // side of the transaction for its canonical interface descriptor or to dump its state.
4628 // We let them pass by default.
4629 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4630 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4631 code == IBinder::SYSPROPS_TRANSACTION) {
4632 return OK;
4633 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004634 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004635 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004636 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004637 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4638 return OK;
4639 }
4640 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4641 return PERMISSION_DENIED;
4642#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004643}
4644
Ana Krulec13be8ad2018-08-21 02:43:56 +00004645status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4646 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004647 status_t credentialCheck = CheckTransactCodeCredentials(code);
4648 if (credentialCheck != OK) {
4649 return credentialCheck;
4650 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004651
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004652 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4653 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004654 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004655 IPCThreadState* ipc = IPCThreadState::self();
4656 const int uid = ipc->getCallingUid();
4657 if (CC_UNLIKELY(uid != AID_SYSTEM
4658 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004659 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004660 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004661 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004662 return PERMISSION_DENIED;
4663 }
4664 int n;
4665 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004666 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004667 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004668 return NO_ERROR;
4669 case 1002: // SHOW_UPDATES
4670 n = data.readInt32();
4671 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004672 invalidateHwcGeometry();
4673 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004674 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004675 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004676 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004677 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004678 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004679 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004680 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004681 setTransactionFlags(
4682 eTransactionNeeded|
4683 eDisplayTransactionNeeded|
4684 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004685 return NO_ERROR;
4686 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004687 case 1006:{ // send empty update
4688 signalRefresh();
4689 return NO_ERROR;
4690 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004691 case 1008: // toggle use of hw composer
4692 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004693 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004694 invalidateHwcGeometry();
4695 repaintEverything();
4696 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004697 case 1009: // toggle use of transform hint
4698 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004699 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004700 invalidateHwcGeometry();
4701 repaintEverything();
4702 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004703 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004704 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004705 reply->writeInt32(0);
4706 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004707 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004708 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004709 return NO_ERROR;
4710 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004711 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004712 if (!display) {
4713 return NAME_NOT_FOUND;
4714 }
4715
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004716 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004717 return NO_ERROR;
4718 }
4719 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004720 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004721 // daltonize
4722 n = data.readInt32();
4723 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004724 case 1:
4725 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4726 break;
4727 case 2:
4728 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4729 break;
4730 case 3:
4731 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4732 break;
4733 default:
4734 mDaltonizer.setType(ColorBlindnessType::None);
4735 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004736 }
4737 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004738 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004739 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004740 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004741 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004742
4743 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004744 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004745 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004746 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004747 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004748 // apply a color matrix
4749 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004750 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004751 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004752 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004753 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004754 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004755 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004756 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004757 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004758 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004759 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004760
4761 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4762 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004763 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004764 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4765 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4766 }
4767
Chia-I Wu28f320b2018-05-03 11:02:56 -07004768 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004769 return NO_ERROR;
4770 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004771 case 1016: { // Unused.
4772 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004773 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004774 case 1017: {
4775 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004776 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004777 return NO_ERROR;
4778 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004779 case 1018: { // Modify Choreographer's phase offset
4780 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004781 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004782 return NO_ERROR;
4783 }
4784 case 1019: { // Modify SurfaceFlinger's phase offset
4785 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004786 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004787 return NO_ERROR;
4788 }
Irvel468051e2016-06-13 16:44:44 -07004789 case 1020: { // Layer updates interceptor
4790 n = data.readInt32();
4791 if (n) {
4792 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004793 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004794 }
4795 else{
4796 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004797 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004798 }
4799 return NO_ERROR;
4800 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004801 case 1021: { // Disable HWC virtual displays
4802 n = data.readInt32();
4803 mUseHwcVirtualDisplays = !n;
4804 return NO_ERROR;
4805 }
Romain Guy0147a172017-06-01 13:53:56 -07004806 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004807 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004808 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004809
Chia-I Wu28f320b2018-05-03 11:02:56 -07004810 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004811 return NO_ERROR;
4812 }
Romain Guy54f154a2017-10-24 21:40:32 +01004813 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004814 int32_t colorMode;
4815
Chia-I Wu0d711262018-05-21 15:19:35 -07004816 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004817 if (data.readInt32(&colorMode) == NO_ERROR) {
4818 mForceColorMode = static_cast<ColorMode>(colorMode);
4819 }
Romain Guy54f154a2017-10-24 21:40:32 +01004820 invalidateHwcGeometry();
4821 repaintEverything();
4822 return NO_ERROR;
4823 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004824 // Deprecate, use 1030 to check whether the device is color managed.
4825 case 1024: {
4826 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004827 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004828 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004829 n = data.readInt32();
4830 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004831 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004832 Mutex::Autolock lock(mStateLock);
4833 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004834 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004835 reply->writeInt32(NO_ERROR);
4836 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004837 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004838 bool writeFile = false;
4839 {
4840 Mutex::Autolock lock(mStateLock);
4841 mTracingEnabledChanged = true;
4842 writeFile = mTracing.disable();
4843 }
4844
4845 if (writeFile) {
4846 reply->writeInt32(mTracing.writeToFile());
4847 } else {
4848 reply->writeInt32(NO_ERROR);
4849 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004850 }
4851 return NO_ERROR;
4852 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004853 case 1026: { // Get layer tracing status
4854 reply->writeBool(mTracing.isEnabled());
4855 return NO_ERROR;
4856 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004857 // Is a DisplayColorSetting supported?
4858 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004859 const auto display = getDefaultDisplayDevice();
4860 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004861 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004862 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004863
4864 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4865 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004866 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004867 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004868 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004869 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004870 reply->writeBool(true);
4871 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004872 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004873 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004874 break;
4875 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004876 reply->writeBool(
4877 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004878 break;
4879 }
4880 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004881 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004882 // Is VrFlinger active?
4883 case 1028: {
4884 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004885 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004886 return NO_ERROR;
4887 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004888 // Set buffer size for SF tracing (value in KB)
4889 case 1029: {
4890 n = data.readInt32();
4891 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4892 ALOGW("Invalid buffer size: %d KB", n);
4893 reply->writeInt32(BAD_VALUE);
4894 return BAD_VALUE;
4895 }
4896
4897 ALOGD("Updating trace buffer to %d KB", n);
4898 mTracing.setBufferSize(n * 1024);
4899 reply->writeInt32(NO_ERROR);
4900 return NO_ERROR;
4901 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004902 // Is device color managed?
4903 case 1030: {
4904 reply->writeBool(useColorManagement);
4905 return NO_ERROR;
4906 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004907 // Override default composition data space
4908 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4909 // && adb shell stop zygote && adb shell start zygote
4910 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4911 // adb shell stop zygote && adb shell start zygote
4912 case 1031: {
4913 Mutex::Autolock _l(mStateLock);
4914 n = data.readInt32();
4915 if (n) {
4916 n = data.readInt32();
4917 if (n) {
4918 Dataspace dataspace = static_cast<Dataspace>(n);
4919 if (!validateCompositionDataspace(dataspace)) {
4920 return BAD_VALUE;
4921 }
4922 mDefaultCompositionDataspace = dataspace;
4923 }
4924 n = data.readInt32();
4925 if (n) {
4926 Dataspace dataspace = static_cast<Dataspace>(n);
4927 if (!validateCompositionDataspace(dataspace)) {
4928 return BAD_VALUE;
4929 }
4930 mWideColorGamutCompositionDataspace = dataspace;
4931 }
4932 } else {
4933 // restore composition data space.
4934 mDefaultCompositionDataspace = defaultCompositionDataspace;
4935 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4936 }
4937 return NO_ERROR;
4938 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004939 // Set trace flags
4940 case 1033: {
4941 n = data.readUint32();
4942 ALOGD("Updating trace flags to 0x%x", n);
4943 mTracing.setTraceFlags(n);
4944 reply->writeInt32(NO_ERROR);
4945 return NO_ERROR;
4946 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004947 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004948 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004949 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004950 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08004951 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
4952 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08004953 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004954 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004955 } else {
4956 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004957 }
4958 return NO_ERROR;
4959 }
Ady Abraham34392f72019-04-10 11:29:27 -07004960 case 1035: {
4961 n = data.readInt32();
4962 mDebugDisplayConfigSetByBackdoor = false;
4963 if (n >= 0) {
4964 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004965 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07004966 if (result != NO_ERROR) {
4967 return result;
4968 }
4969 mDebugDisplayConfigSetByBackdoor = true;
4970 }
4971 return NO_ERROR;
4972 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004973 }
4974 }
4975 return err;
4976}
4977
Steven Thomas6d8110b2017-08-31 18:24:21 -07004978void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004979 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004980 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004981}
4982
Ana Krulec7d1d6832018-12-27 11:10:09 -08004983void SurfaceFlinger::repaintEverythingForHWC() {
4984 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004985 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004986}
4987
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004988// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4989class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004990public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004991 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4992 ~WindowDisconnector() {
4993 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004994 }
4995
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004996private:
4997 ANativeWindow* mWindow;
4998 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004999};
5000
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005001status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005002 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08005003 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
5004 const Rect& sourceCrop, uint32_t reqWidth,
5005 uint32_t reqHeight, bool useIdentityTransform,
5006 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005007 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005009 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005010
Dominik Laskowski718f9602019-11-09 20:01:35 -08005011 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
5012 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
5013 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
5014 renderAreaRotation = ui::Transform::ROT_0;
5015 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005016
Chia-I Wu20261cb2018-08-23 12:55:44 -07005017 sp<DisplayDevice> display;
5018 {
5019 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005020
Chia-I Wu20261cb2018-08-23 12:55:44 -07005021 display = getDisplayDeviceLocked(displayToken);
5022 if (!display) return BAD_VALUE;
5023
Chia-I Wucb023152018-08-28 12:57:23 -07005024 // set the requested width/height to the logical display viewport size
5025 // by default
5026 if (reqWidth == 0 || reqHeight == 0) {
5027 reqWidth = uint32_t(display->getViewport().width());
5028 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005029 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005030 }
5031
Peiyong Lin0e003c92018-09-17 11:09:51 -07005032 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005033 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005034
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005035 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5036 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005037 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005038 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005039}
5040
chaviw93df2ea2019-04-30 16:45:12 -07005041static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5042 switch (colorMode) {
5043 case ColorMode::DISPLAY_P3:
5044 case ColorMode::BT2100_PQ:
5045 case ColorMode::BT2100_HLG:
5046 case ColorMode::DISPLAY_BT2020:
5047 return Dataspace::DISPLAY_P3;
5048 default:
5049 return Dataspace::V0_SRGB;
5050 }
5051}
5052
5053const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5054 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5055 if (displayToken) {
5056 return getDisplayDeviceLocked(displayToken);
5057 }
5058 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5059 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005060 return getDisplayByLayerStack(displayOrLayerStack);
5061}
5062
5063const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005064 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005065 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005066 return display;
5067 }
5068 }
5069 return nullptr;
5070}
5071
5072status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5073 sp<GraphicBuffer>* outBuffer) {
5074 sp<DisplayDevice> display;
5075 uint32_t width;
5076 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005077 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005078 {
5079 Mutex::Autolock _l(mStateLock);
5080 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5081 if (!display) {
5082 return BAD_VALUE;
5083 }
5084
5085 width = uint32_t(display->getViewport().width());
5086 height = uint32_t(display->getViewport().height());
5087
Dominik Laskowski718f9602019-11-09 20:01:35 -08005088 const auto orientation = display->getOrientation();
5089 captureOrientation = ui::Transform::toRotationFlags(orientation);
5090
5091 switch (captureOrientation) {
5092 case ui::Transform::ROT_90:
5093 captureOrientation = ui::Transform::ROT_270;
5094 break;
5095
5096 case ui::Transform::ROT_270:
5097 captureOrientation = ui::Transform::ROT_90;
5098 break;
5099
5100 case ui::Transform::ROT_INVALID:
5101 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5102 captureOrientation = ui::Transform::ROT_0;
5103 break;
5104
5105 default:
5106 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005107 }
chaviw93df2ea2019-04-30 16:45:12 -07005108 *outDataspace =
5109 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5110 }
5111
5112 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5113 false /* captureSecureLayers */);
5114
5115 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5116 std::placeholders::_1);
5117 bool ignored = false;
5118 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5119 false /* useIdentityTransform */,
5120 ignored /* outCapturedSecureLayers */);
5121}
5122
Robert Carr866455f2019-04-02 16:28:26 -07005123status_t SurfaceFlinger::captureLayers(
5124 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5125 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5126 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5127 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005128 ATRACE_CALL();
5129
5130 class LayerRenderArea : public RenderArea {
5131 public:
Robert Carr578038f2018-03-09 12:25:24 -08005132 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005133 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005134 bool childrenOnly, const Rect& displayViewport)
5135 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005136 mLayer(layer),
5137 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005138 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005139 mFlinger(flinger),
5140 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005141 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005142 Rect getBounds() const override {
5143 const Layer::State& layerState(mLayer->getDrawingState());
5144 return mLayer->getBufferSize(layerState);
5145 }
Marissa Wall61c58622018-07-18 10:12:20 -07005146 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005147 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005148 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005149 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005150 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005151 }
chaviwa76b2712017-09-20 12:02:26 -07005152 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005153 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005154 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005155 Rect getSourceCrop() const override {
5156 if (mCrop.isEmpty()) {
5157 return getBounds();
5158 } else {
5159 return mCrop;
5160 }
5161 }
Robert Carr578038f2018-03-09 12:25:24 -08005162 class ReparentForDrawing {
5163 public:
5164 const sp<Layer>& oldParent;
5165 const sp<Layer>& newParent;
5166
Vishnu Nair4351ad52019-02-11 14:13:02 -08005167 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5168 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005169 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005170 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005171 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5172 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005173 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005174 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005175 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005176 };
5177
5178 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005179 const Rect sourceCrop = getSourceCrop();
5180 // no need to check rotation because there is none
5181 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5182 sourceCrop.height() != getReqHeight();
5183
Robert Carr578038f2018-03-09 12:25:24 -08005184 if (!mChildrenOnly) {
5185 mTransform = mLayer->getTransform().inverse();
5186 drawLayers();
5187 } else {
5188 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005189 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5190 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005191 // In the "childrenOnly" case we reparent the children to a screenshot
5192 // layer which has no properties set and which does not draw.
5193 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005194 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5195 "Screenshot Parent"s, w, h, 0,
5196 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005197
Vishnu Nair4351ad52019-02-11 14:13:02 -08005198 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005199 drawLayers();
5200 }
5201 }
chaviwa76b2712017-09-20 12:02:26 -07005202
chaviwa76b2712017-09-20 12:02:26 -07005203 private:
chaviw7206d492017-11-10 16:16:12 -08005204 const sp<Layer> mLayer;
5205 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005206
Peiyong Linefefaac2018-08-17 12:27:51 -07005207 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005208 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005209
5210 SurfaceFlinger* mFlinger;
5211 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005212 };
5213
Robert Carrc0df3122019-04-11 13:18:21 -07005214 int reqWidth = 0;
5215 int reqHeight = 0;
5216 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005217 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005218 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005219 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005220 {
5221 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005222
Robert Carrc0df3122019-04-11 13:18:21 -07005223 parent = fromHandle(layerHandleBinder);
5224 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5225 ALOGE("captureLayers called with an invalid or removed parent");
5226 return NAME_NOT_FOUND;
5227 }
5228
5229 const int uid = IPCThreadState::self()->getCallingUid();
5230 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5231 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5232 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5233 return PERMISSION_DENIED;
5234 }
5235
Vishnu Nairefc42e22019-12-03 17:36:12 -08005236 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005237 if (sourceCrop.width() <= 0) {
5238 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005239 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005240 }
5241
5242 if (sourceCrop.height() <= 0) {
5243 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005244 crop.bottom = parentSourceBounds.getHeight();
5245 }
5246
5247 if (crop.isEmpty() || frameScale <= 0.0f) {
5248 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5249 // crop was not specified, or an invalid frame scale was provided.
5250 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005251 }
5252 reqWidth = crop.width() * frameScale;
5253 reqHeight = crop.height() * frameScale;
5254
5255 for (const auto& handle : excludeHandles) {
5256 sp<Layer> excludeLayer = fromHandle(handle);
5257 if (excludeLayer != nullptr) {
5258 excludeLayers.emplace(excludeLayer);
5259 } else {
5260 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5261 return NAME_NOT_FOUND;
5262 }
5263 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005264
5265 auto display = getDisplayByLayerStack(parent->getLayerStack());
5266 if (!display) {
5267 return BAD_VALUE;
5268 }
5269
5270 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005271 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005272
Chia-I Wu20261cb2018-08-23 12:55:44 -07005273 // really small crop or frameScale
5274 if (reqWidth <= 0) {
5275 reqWidth = 1;
5276 }
5277 if (reqHeight <= 0) {
5278 reqHeight = 1;
5279 }
5280
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005281 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5282 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005283 auto traverseLayers = [parent, childrenOnly,
5284 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005285 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5286 if (!layer->isVisible()) {
5287 return;
Robert Carr578038f2018-03-09 12:25:24 -08005288 } else if (childrenOnly && layer == parent.get()) {
5289 return;
chaviwa76b2712017-09-20 12:02:26 -07005290 }
Robert Carr866455f2019-04-02 16:28:26 -07005291
5292 sp<Layer> p = layer;
5293 while (p != nullptr) {
5294 if (excludeLayers.count(p) != 0) {
5295 return;
5296 }
5297 p = p->getParent();
5298 }
5299
chaviwa76b2712017-09-20 12:02:26 -07005300 visitor(layer);
5301 });
5302 };
Robert Carr108b2c72019-04-02 16:32:58 -07005303
5304 bool outCapturedSecureLayers = false;
5305 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5306 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005307}
5308
5309status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5310 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005311 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005312 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005313 bool useIdentityTransform,
5314 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005315 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005316
Peiyong Lin0e003c92018-09-17 11:09:51 -07005317 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005318 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5319 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005320 *outBuffer =
5321 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5322 static_cast<android_pixel_format>(reqPixelFormat), 1,
5323 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005324
Robert Carr108b2c72019-04-02 16:32:58 -07005325 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5326 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005327}
5328
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005329status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5330 TraverseLayersFunction traverseLayers,
5331 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005332 bool useIdentityTransform,
5333 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005334 // This mutex protects syncFd and captureResult for communication of the return values from the
5335 // main thread back to this Binder thread
5336 std::mutex captureMutex;
5337 std::condition_variable captureCondition;
5338 std::unique_lock<std::mutex> captureLock(captureMutex);
5339 int syncFd = -1;
5340 std::optional<status_t> captureResult;
5341
Robert Carr03480e22018-01-04 16:02:06 -08005342 const int uid = IPCThreadState::self()->getCallingUid();
5343 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5344
Dominik Laskowski8c001672018-05-30 16:52:06 -07005345 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005346 // If there is a refresh pending, bug out early and tell the binder thread to try again
5347 // after the refresh.
5348 if (mRefreshPending) {
5349 ATRACE_NAME("Skipping screenshot for now");
5350 std::unique_lock<std::mutex> captureLock(captureMutex);
5351 captureResult = std::make_optional<status_t>(EAGAIN);
5352 captureCondition.notify_one();
5353 return;
5354 }
5355
5356 status_t result = NO_ERROR;
5357 int fd = -1;
5358 {
5359 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005360 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005361 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005362 useIdentityTransform, forSystem, &fd,
5363 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005364 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005365 }
5366
5367 {
5368 std::unique_lock<std::mutex> captureLock(captureMutex);
5369 syncFd = fd;
5370 captureResult = std::make_optional<status_t>(result);
5371 captureCondition.notify_one();
5372 }
5373 });
5374
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005375 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005376 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005377 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005378 while (*captureResult == EAGAIN) {
5379 captureResult.reset();
5380 result = postMessageAsync(message);
5381 if (result != NO_ERROR) {
5382 return result;
5383 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005384 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005385 }
5386 result = *captureResult;
5387 }
5388
5389 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005390 sync_wait(syncFd, -1);
5391 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005392 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005393
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005394 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005395}
5396
chaviwa76b2712017-09-20 12:02:26 -07005397void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005398 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005399 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5400 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005401 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005402
chaviwa76b2712017-09-20 12:02:26 -07005403 const auto reqWidth = renderArea.getReqWidth();
5404 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005405 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005406 const auto transform = renderArea.getTransform();
5407 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005408 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005409
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005410 renderengine::DisplaySettings clientCompositionDisplay;
5411 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005412
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005413 // assume that bounds are never offset, and that they are the same as the
5414 // buffer bounds.
5415 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005416 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005417 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005418
5419 // Now take into account the rotation flag. We append a transform that
5420 // rotates the layer stack about the origin, then translate by buffer
5421 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005422 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005423 int displacementX = 0;
5424 int displacementY = 0;
5425 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5426 switch (rotation) {
5427 case ui::Transform::ROT_90:
5428 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005429 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005430 break;
5431 case ui::Transform::ROT_180:
5432 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005433 displacementY = renderArea.getBounds().getWidth();
5434 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005435 break;
5436 case ui::Transform::ROT_270:
5437 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005438 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005439 break;
5440 default:
5441 break;
5442 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005443
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005444 // We need to transform the clipping window into the right spot.
5445 // First, rotate the clipping rectangle by the rotation hint to get the
5446 // right orientation
5447 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5448 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5449 const vec4 rotClipTL = rotMatrix * clipTL;
5450 const vec4 rotClipBR = rotMatrix * clipBR;
5451 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5452 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5453 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5454 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5455
5456 // Now reposition the clipping rectangle with the displacement vector
5457 // computed above.
5458 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005459 clientCompositionDisplay.clip =
5460 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5461 newClipRight + displacementX, newClipBottom + displacementY);
5462
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005463 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005464 clientCompositionDisplay.globalTransform =
5465 clipTransform * clientCompositionDisplay.globalTransform;
5466
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005467 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5468 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005469
chaviw50da5042018-04-09 13:49:37 -07005470 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005471
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005472 renderengine::LayerSettings fillLayer;
5473 fillLayer.source.buffer.buffer = nullptr;
5474 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5475 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5476 fillLayer.alpha = half(alpha);
5477 clientCompositionLayers.push_back(fillLayer);
5478
5479 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005480 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005481 const bool supportProtectedContent = false;
5482 Region clip(renderArea.getBounds());
5483 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5484 clip,
5485 useIdentityTransform,
5486 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5487 renderArea.isSecure(),
5488 supportProtectedContent,
5489 clearRegion,
5490 };
5491 auto result = layer->prepareClientComposition(targetSettings);
5492 if (result) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005493 std::optional<renderengine::LayerSettings> shadowLayer =
5494 layer->prepareShadowClientComposition(*result, displayViewport,
5495 clientCompositionDisplay.outputDataspace);
5496 if (shadowLayer) {
5497 clientCompositionLayers.push_back(*shadowLayer);
5498 }
Lloyd Piquef16688f2019-02-19 17:47:57 -08005499 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005500 }
chaviwa76b2712017-09-20 12:02:26 -07005501 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005502
5503 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005504 // Use an empty fence for the buffer fence, since we just created the buffer so
5505 // there is no need for synchronization with the GPU.
5506 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005507 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005508 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005509 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005510 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005511
5512 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005513}
5514
chaviwa76b2712017-09-20 12:02:26 -07005515status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5516 TraverseLayersFunction traverseLayers,
5517 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005518 bool useIdentityTransform, bool forSystem,
5519 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005520 ATRACE_CALL();
5521
chaviwa76b2712017-09-20 12:02:26 -07005522 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005523 outCapturedSecureLayers =
5524 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005525 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005526
Robert Carr03480e22018-01-04 16:02:06 -08005527 // We allow the system server to take screenshots of secure layers for
5528 // use in situations like the Screen-rotation animation and place
5529 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005530 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005531 ALOGW("FB is protected: PERMISSION_DENIED");
5532 return PERMISSION_DENIED;
5533 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005534 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005535 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005536}
5537
chaviw95ef3c42019-02-14 10:55:09 -08005538void SurfaceFlinger::setInputWindowsFinished() {
5539 Mutex::Autolock _l(mStateLock);
5540
5541 mPendingSyncInputWindows = false;
5542 mTransactionCV.broadcast();
5543}
chaviw5f21a5e2019-02-14 10:00:34 -08005544
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005545// ---------------------------------------------------------------------------
5546
Dan Stoza412903f2017-04-27 13:42:17 -07005547void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5548 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005549}
5550
Dan Stoza412903f2017-04-27 13:42:17 -07005551void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5552 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005553}
5554
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005555void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005556 const LayerVector::Visitor& visitor) {
5557 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005558 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005559 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005560 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005561 continue;
5562 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005563 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005564 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005565 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005566 return;
5567 }
chaviwa76b2712017-09-20 12:02:26 -07005568 if (!layer->isVisible()) {
5569 return;
5570 }
5571 visitor(layer);
5572 });
5573 }
5574}
5575
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005576status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5577 HwcConfigIndexType defaultConfig,
5578 float minRefreshRate,
5579 float maxRefreshRate) {
5580 Mutex::Autolock lock(mStateLock);
5581
Dominik Laskowski22488f62019-03-28 09:53:04 -07005582 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005583 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5584 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5585 // it should go thru setDesiredActiveConfig, similar to primary display.
5586 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5587 const auto displayId = display->getId();
5588 LOG_ALWAYS_FATAL_IF(!displayId);
5589
5590 HWC2::VsyncPeriodChangeConstraints constraints;
5591 constraints.desiredTimeNanos = systemTime();
5592 constraints.seamlessRequired = false;
5593
5594 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005595 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5596 constraints, &timeline) < 0) {
5597 return BAD_VALUE;
5598 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005599 if (timeline.refreshRequired) {
5600 repaintEverythingForHWC();
5601 }
5602
Ady Abrahamdfa37362020-01-21 18:02:39 -08005603 display->setActiveConfig(defaultConfig);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005604 const nsecs_t vsyncPeriod =
Ady Abrahamdfa37362020-01-21 18:02:39 -08005605 getHwComposer().getConfigs(*displayId)[defaultConfig.value()]->getVsyncPeriod();
5606 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, defaultConfig,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005607 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005608 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005609 }
5610
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005611 if (mDebugDisplayConfigSetByBackdoor) {
5612 // ignore this request as config is overridden by backdoor
5613 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005614 }
5615
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005616 bool policyChanged;
5617 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5618 &policyChanged) < 0) {
5619 return BAD_VALUE;
5620 }
5621 if (!policyChanged) {
5622 return NO_ERROR;
5623 }
5624
5625 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5626 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005627
5628 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5629 // that listeners that care about a change in allowed configs can get the notification.
5630 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005631 const nsecs_t vsyncPeriod =
5632 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005633 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005634 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005635
Ady Abraham2139f732019-11-13 18:56:40 -08005636 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5637 auto configId = mScheduler->getPreferredConfigId();
5638 auto preferredRefreshRate = configId
5639 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5640 : mRefreshRateConfigs->getMinRefreshRateByPolicy();
5641 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5642 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5643 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5644 ALOGV("switching to Scheduler preferred config %d",
5645 preferredRefreshRate.configId.value());
5646 setDesiredActiveConfig(
5647 {preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
5648 } else {
5649 // Set the highest allowed config
5650 setDesiredActiveConfig({mRefreshRateConfigs->getMaxRefreshRateByPolicy().configId,
5651 Scheduler::ConfigEvent::Changed});
5652 }
5653 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005654 ALOGV("switching to config %d", defaultConfig.value());
5655 setDesiredActiveConfig({defaultConfig, Scheduler::ConfigEvent::Changed});
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005656 }
5657
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005658 return NO_ERROR;
5659}
5660
Ana Krulec0782b882019-10-15 17:34:54 -07005661status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005662 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005663 float maxRefreshRate) {
5664 ATRACE_CALL();
5665
5666 if (!displayToken) {
5667 return BAD_VALUE;
5668 }
5669
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005670 status_t result = NO_ERROR;
5671
Ana Krulec234bb162019-11-10 22:55:55 +01005672 postMessageSync(new LambdaMessage([&]() {
5673 const auto display = getDisplayDeviceLocked(displayToken);
5674 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005675 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005676 ALOGE("Attempt to set desired display configs for invalid display token %p",
5677 displayToken.get());
5678 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005679 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005680 ALOGW("Attempt to set desired display configs for virtual display");
5681 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005682 result =
5683 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5684 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005685 }
5686 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005687
5688 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005689}
5690
5691status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005692 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005693 float* outMinRefreshRate,
5694 float* outMaxRefreshRate) {
5695 ATRACE_CALL();
5696
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005697 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005698 return BAD_VALUE;
5699 }
5700
5701 Mutex::Autolock lock(mStateLock);
5702 const auto display = getDisplayDeviceLocked(displayToken);
5703 if (!display) {
5704 return NAME_NOT_FOUND;
5705 }
5706
5707 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005708 HwcConfigIndexType defaultConfig;
5709 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5710 *outDefaultConfig = defaultConfig.value();
5711 return NO_ERROR;
5712 } else if (display->isVirtual()) {
5713 return BAD_VALUE;
5714 } else {
5715 const auto displayId = display->getId();
5716 if (!displayId) {
5717 return BAD_VALUE;
5718 }
5719 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5720 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5721 *outMinRefreshRate = 1e9f / vsyncPeriod;
5722 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5723 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005724 }
Ana Krulec0782b882019-10-15 17:34:54 -07005725}
5726
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005727void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005728 mFlinger->setInputWindowsFinished();
5729}
5730
Robert Carrc0df3122019-04-11 13:18:21 -07005731sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005732 BBinder* b = nullptr;
5733 if (handle) {
5734 b = handle->localBinder();
5735 }
Robert Carrc0df3122019-04-11 13:18:21 -07005736 if (b == nullptr) {
5737 return nullptr;
5738 }
5739 auto it = mLayersByLocalBinderToken.find(b);
5740 if (it != mLayersByLocalBinderToken.end()) {
5741 return it->second.promote();
5742 }
5743 return nullptr;
5744}
5745
Dominik Laskowski75848362019-11-11 17:57:20 -08005746void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005747 mNumLayers++;
5748 mScheduler->registerLayer(layer);
5749}
5750
5751void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5752 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005753 removeFromOffscreenLayers(layer);
5754}
5755
5756// WARNING: ONLY CALL THIS FROM LAYER DTOR
5757// Here we add children in the current state to offscreen layers and remove the
5758// layer itself from the offscreen layer list. Since
5759// this is the dtor, it is safe to access the current state. This keeps us
5760// from dangling children layers such that they are not reachable from the
5761// Drawing state nor the offscreen layer list
5762// See b/141111965
5763void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5764 for (auto& child : layer->getCurrentChildren()) {
5765 mOffscreenLayers.emplace(child.get());
5766 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005767 mOffscreenLayers.erase(layer);
5768}
5769
Alec Mouri4545a8a2019-08-08 20:05:32 -07005770void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5771 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5772}
5773
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005774status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5775 float lightPosY, float lightPosZ,
5776 float lightRadius) {
5777 Mutex::Autolock _l(mStateLock);
5778 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5779 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5780 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5781 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5782 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5783
5784 // these values are overridden when calculating the shadow settings for a layer.
5785 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5786 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005787 return NO_ERROR;
5788}
5789
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005790} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005791
Mathias Agopian3f844832013-08-07 21:24:32 -07005792#if defined(__gl_h_)
5793#error "don't include gl/gl.h in this file"
5794#endif
5795
5796#if defined(__gl2_h_)
5797#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005798#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005799
5800// TODO(b/129481165): remove the #pragma below and fix conversion issues
5801#pragma clang diagnostic pop // ignored "-Wconversion"