blob: ba57d3763f2919715766e6c9ff578c38e52294c6 [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();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700505
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700506 // wait patiently for the window manager death
507 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700508 mWindowManager = defaultServiceManager()->getService(name);
509 if (mWindowManager != 0) {
510 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700511 }
Robert Carr720e5062018-07-30 17:45:14 -0700512 sp<IBinder> input(defaultServiceManager()->getService(
513 String16("inputflinger")));
514 if (input == nullptr) {
515 ALOGE("Failed to link to input service");
516 } else {
517 mInputFlinger = interface_cast<IInputFlinger>(input);
518 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700519
Steven Thomas050b2c82017-03-06 11:45:16 -0800520 if (mVrFlinger) {
521 mVrFlinger->OnBootFinished();
522 }
523
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700524 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700525 // formerly we would just kill the process, but we now ask it to exit so it
526 // can choose where to stop the animation.
527 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700528
529 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
530 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
531 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700532
Ana Krulecbd6654b2019-02-15 15:18:15 -0800533 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800534 readPersistentProperties();
535 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800536
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700537 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
538 // set the refresh rate according to the policy
Ady Abraham2139f732019-11-13 18:56:40 -0800539 const auto& performanceRefreshRate = mRefreshRateConfigs->getMaxRefreshRateByPolicy();
540 changeRefreshRateLocked(performanceRefreshRate, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800541 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800542 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800543}
544
Dan Stoza436ccf32018-06-21 12:10:12 -0700545uint32_t SurfaceFlinger::getNewTexture() {
546 {
547 std::lock_guard lock(mTexturePoolMutex);
548 if (!mTexturePool.empty()) {
549 uint32_t name = mTexturePool.back();
550 mTexturePool.pop_back();
551 ATRACE_INT("TexturePoolSize", mTexturePool.size());
552 return name;
553 }
554
555 // The pool was too small, so increase it for the future
556 ++mTexturePoolSize;
557 }
558
559 // The pool was empty, so we need to get a new texture name directly using a
560 // blocking call to the main thread
561 uint32_t name = 0;
562 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
563 return name;
564}
565
Mathias Agopian3f844832013-08-07 21:24:32 -0700566void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700567 std::lock_guard lock(mTexturePoolMutex);
568 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
569 // to actually delete this or not based on mTexturePoolSize
570 mTexturePool.push_back(texture);
571 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700572}
573
Wei Wangf9b05ee2017-07-19 20:59:39 -0700574// Do not call property_set on main thread which will be blocked by init
575// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700576void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700577 ALOGI( "SurfaceFlinger's main thread ready to run. "
578 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700579 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800580
Steven Thomasb02664d2017-07-26 18:48:28 -0700581 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700582 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800583 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700584 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
585 renderengine::RenderEngineCreationArgs::Builder()
586 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
587 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
588 .setUseColorManagerment(useColorManagement)
589 .setEnableProtectedContext(enable_protected_contents(false))
590 .setPrecacheToneMapperShaderOnly(false)
Lucas Dupin19c8f0e2019-11-25 17:55:44 -0800591 .setSupportsBackgroundBlur(mEnableBlurs)
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700592 .setContextPriority(useContextPriority
593 ? renderengine::RenderEngine::ContextPriority::HIGH
594 : renderengine::RenderEngine::ContextPriority::MEDIUM)
595 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800596 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700597
598 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
599 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700600 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
601 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800602 // Process any initial hotplug and resulting display changes.
603 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700604 const auto display = getDefaultDisplayDeviceLocked();
605 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700606 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700607 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800608
Steven Thomas050b2c82017-03-06 11:45:16 -0800609 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700610 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700611 // This callback is called from the vr flinger dispatch thread. We
612 // need to call signalTransaction(), which requires holding
613 // mStateLock when we're not on the main thread. Acquiring
614 // mStateLock from the vr flinger dispatch thread might trigger a
615 // deadlock in surface flinger (see b/66916578), so post a message
616 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700617 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700618 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
619 mVrFlingerRequestsDisplay = requestDisplay;
620 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700621 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800622 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700623 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
624 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700625 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700626 .value_or(0),
627 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800628 if (!mVrFlinger) {
629 ALOGE("Failed to start vrflinger");
630 }
631 }
632
Mathias Agopian92a979a2012-08-02 18:32:23 -0700633 // initialize our drawing state
634 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700635
Andy McFadden13a082e2012-08-24 10:16:42 -0700636 // set initial conditions (e.g. unblank default device)
637 initializeDisplays();
638
Steven Thomas137d4bc2019-07-25 16:55:14 -0700639 char primeShaderCache[PROPERTY_VALUE_MAX];
640 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
641 if (atoi(primeShaderCache)) {
642 getRenderEngine().primeCache();
643 }
Dan Stoza4e637772016-07-28 13:31:51 -0700644
Wei Wangf9b05ee2017-07-19 20:59:39 -0700645 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700646
647 const bool presentFenceReliable =
648 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
649 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700650
651 if (mStartPropertySetThread->Start() != NO_ERROR) {
652 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800653 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800654
Dan Stoza9e56aa02015-11-02 13:00:03 -0800655 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700656}
657
Romain Guy11d63f42017-07-20 12:47:14 -0700658void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700659 Mutex::Autolock _l(mStateLock);
660
Romain Guy11d63f42017-07-20 12:47:14 -0700661 char value[PROPERTY_VALUE_MAX];
662
663 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800664 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700665 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800666 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100667
668 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700669 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800670
671 property_get("persist.sys.sf.color_mode", value, "0");
672 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700673}
674
Mathias Agopiana67e4182012-06-19 17:26:12 -0700675void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800676 // Start boot animation service by setting a property mailbox
677 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700678 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800679 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700680 if (mStartPropertySetThread->join() != NO_ERROR) {
681 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800682 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700683}
684
Mathias Agopian875d8e12013-06-07 15:35:48 -0700685size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700686 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700687}
688
Mathias Agopian875d8e12013-06-07 15:35:48 -0700689size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700690 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700691}
692
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800693// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800694
Jamie Gennis582270d2011-08-17 18:19:00 -0700695bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800696 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800697 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800698 return authenticateSurfaceTextureLocked(bufferProducer);
699}
700
701bool SurfaceFlinger::authenticateSurfaceTextureLocked(
702 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800703 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800704 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800705}
706
Brian Anderson6b376712017-04-04 10:51:39 -0700707status_t SurfaceFlinger::getSupportedFrameTimestamps(
708 std::vector<FrameEvent>* outSupported) const {
709 *outSupported = {
710 FrameEvent::REQUESTED_PRESENT,
711 FrameEvent::ACQUIRE,
712 FrameEvent::LATCH,
713 FrameEvent::FIRST_REFRESH_START,
714 FrameEvent::LAST_REFRESH_START,
715 FrameEvent::GPU_COMPOSITION_DONE,
716 FrameEvent::DEQUEUE_READY,
717 FrameEvent::RELEASE,
718 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700719 ConditionalLock _l(mStateLock,
720 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700721 if (!getHwComposer().hasCapability(
722 HWC2::Capability::PresentFenceIsNotReliable)) {
723 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
724 }
725 return NO_ERROR;
726}
727
Dominik Laskowski22488f62019-03-28 09:53:04 -0700728status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
729 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700730 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700731 return BAD_VALUE;
732 }
733
Dominik Laskowski22488f62019-03-28 09:53:04 -0700734 Mutex::Autolock lock(mStateLock);
735
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800736 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700737 if (!displayId) {
738 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700739 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700740
Mathias Agopian8b736f12012-08-13 17:54:26 -0700741 // TODO: Not sure if display density should handled by SF any longer
742 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700743 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700744 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700745 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800746 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700747 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700748 }
749 return density;
750 }
751 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700752 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700753 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700754 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700755 return getDensityFromProperty("ro.sf.lcd_density"); }
756 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700757
Dan Stoza7f7da322014-05-02 15:26:25 -0700758 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700759
Dominik Laskowski075d3172018-05-24 15:50:06 -0700760 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700761 DisplayInfo info = DisplayInfo();
762
Dan Stoza9e56aa02015-11-02 13:00:03 -0800763 float xdpi = hwConfig->getDpiX();
764 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700765
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700766 info.w = hwConfig->getWidth();
767 info.h = hwConfig->getHeight();
768 // Default display viewport to display width and height
769 info.viewportW = info.w;
770 info.viewportH = info.h;
771
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800772 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700773 // The density of the device is provided by a build property
774 float density = Density::getBuildDensity() / 160.0f;
775 if (density == 0) {
776 // the build doesn't provide a density -- this is wrong!
777 // use xdpi instead
778 ALOGE("ro.sf.lcd_density must be defined as a build property");
779 density = xdpi / 160.0f;
780 }
781 if (Density::getEmuDensity()) {
782 // if "qemu.sf.lcd_density" is specified, it overrides everything
783 xdpi = ydpi = density = Density::getEmuDensity();
784 density /= 160.0f;
785 }
786 info.density = density;
787
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700788 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowski718f9602019-11-09 20:01:35 -0800789 info.orientation = display->getOrientation();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700790
791 // This is for screenrecord
792 const Rect viewport = display->getViewport();
793 if (viewport.isValid()) {
794 info.viewportW = uint32_t(viewport.getWidth());
795 info.viewportH = uint32_t(viewport.getHeight());
796 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700797 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700798 } else {
799 // TODO: where should this value come from?
800 static const int TV_DENSITY = 213;
801 info.density = TV_DENSITY / 160.0f;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700802
803 const auto display = getDisplayDeviceLocked(displayToken);
804 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700805 }
806
Dan Stoza7f7da322014-05-02 15:26:25 -0700807 info.xdpi = xdpi;
808 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800809 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham2139f732019-11-13 18:56:40 -0800810
Ady Abraham9e16a482019-12-03 17:19:41 -0800811 const auto offset = mPhaseConfiguration->getOffsetsForRefreshRate(info.fps);
Ady Abraham796beb02019-04-11 15:23:07 -0700812 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800813
Andy McFadden91b2ca82014-06-13 14:04:23 -0700814 // This is how far in advance a buffer must be queued for
815 // presentation at a given time. If you want a buffer to appear
816 // on the screen at time N, you must submit the buffer before
817 // (N - presentationDeadline).
818 //
819 // Normally it's one full refresh period (to give SF a chance to
820 // latch the buffer), but this can be reduced by configuring a
821 // DispSync offset. Any additional delays introduced by the hardware
822 // composer or panel must be accounted for here.
823 //
824 // We add an additional 1ms to allow for processing time and
825 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700826 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700827
828 // All non-virtual displays are currently considered secure.
829 info.secure = true;
830
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800831 if (displayId == getInternalDisplayIdLocked() &&
Dominik Laskowski718f9602019-11-09 20:01:35 -0800832 (internalDisplayOrientation == ui::ROTATION_90 ||
833 internalDisplayOrientation == ui::ROTATION_270)) {
Iris Chang7501ed62018-04-30 14:45:42 +0800834 std::swap(info.w, info.h);
835 }
836
Michael Wright28f24d02016-07-12 13:30:53 -0700837 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700838 }
839
Dan Stoza7f7da322014-05-02 15:26:25 -0700840 return NO_ERROR;
841}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700842
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700843status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
844 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700845 return BAD_VALUE;
846 }
847
Ana Krulecc2870422019-01-29 19:00:58 -0800848 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700849 return NO_ERROR;
850}
851
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700852int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
853 const auto display = getDisplayDevice(displayToken);
854 if (!display) {
855 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800856 return BAD_VALUE;
857 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700858
Steven Thomasc9098452019-09-30 17:15:05 -0700859 if (display->isPrimary()) {
860 std::lock_guard<std::mutex> lock(mActiveConfigLock);
861 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800862 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700863 }
Steven Thomasc9098452019-09-30 17:15:05 -0700864 }
Ady Abraham2139f732019-11-13 18:56:40 -0800865
866 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700867}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700868
Ady Abraham03b02dd2019-03-21 15:40:11 -0700869void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800870 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800871 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
872 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800873
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800874 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800875 // config twice. However event generation config might have changed so we need to update it
876 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800877 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700878 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
879 mDesiredActiveConfig = info;
880 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800881
882 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800883 // This will trigger HWC refresh without resetting the idle timer.
884 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700885 // Start receiving vsync samples now, so that we can detect a period
886 // switch.
887 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700888 // As we called to set period, we will call to onRefreshRateChangeCompleted once
889 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700890 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800891
Ady Abraham9e16a482019-12-03 17:19:41 -0800892 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
893 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800894 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800895 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700896
897 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800898 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700899 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800900}
901
902status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
903 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800904
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100905 if (!displayToken) {
906 return BAD_VALUE;
907 }
Ady Abraham838de062019-02-04 10:24:03 -0800908
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100909 status_t result = NO_ERROR;
910
911 postMessageSync(new LambdaMessage([&]() {
912 const auto display = getDisplayDeviceLocked(displayToken);
913 if (!display) {
914 ALOGE("Attempt to set allowed display configs for invalid display token %p",
915 displayToken.get());
916 result = BAD_VALUE;
917 } else if (display->isVirtual()) {
918 ALOGW("Attempt to set allowed display configs for virtual display");
919 result = BAD_VALUE;
920 } else {
921 HwcConfigIndexType config(mode);
922 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
923 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
924 refreshRate.fps);
925 }
926 }));
927
928 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800929}
930
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800931void SurfaceFlinger::setActiveConfigInternal() {
932 ATRACE_CALL();
933
Dominik Laskowski22488f62019-03-28 09:53:04 -0700934 const auto display = getDefaultDisplayDeviceLocked();
935 if (!display) {
936 return;
937 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800938
Dominik Laskowski22488f62019-03-28 09:53:04 -0700939 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800940 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700941 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800942 display->setActiveConfig(mUpcomingActiveConfig.configId);
943
Ady Abraham2139f732019-11-13 18:56:40 -0800944 auto refreshRate =
945 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800946 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
947 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800948 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700949
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800950 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700951 const nsecs_t vsyncPeriod =
952 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
953 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800954 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700955 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800956 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800957}
958
Ady Abraham53852a52019-05-28 18:07:44 -0700959void SurfaceFlinger::desiredActiveConfigChangeDone() {
960 std::lock_guard<std::mutex> lock(mActiveConfigLock);
961 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
962 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700963
964 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham2139f732019-11-13 18:56:40 -0800965 auto refreshRate =
966 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800967 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
968 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700969}
970
Dominik Laskowski22488f62019-03-28 09:53:04 -0700971bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800972 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800973 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -0800974 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700975 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800976 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700977 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800978 return true;
979 }
980
981 // We received the present fence from the HWC, so we assume it successfully updated
982 // the config, hence we update SF.
983 mCheckPendingFence = false;
984 setActiveConfigInternal();
985 }
986
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800987 // Store the local variable to release the lock.
988 ActiveConfigInfo desiredActiveConfig;
989 {
990 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800991 if (!mDesiredActiveConfigChanged) {
992 return false;
993 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800994 desiredActiveConfig = mDesiredActiveConfig;
995 }
996
Ady Abraham2139f732019-11-13 18:56:40 -0800997 auto refreshRate =
998 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
999 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1000 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001001 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001002 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1003 // display is not valid or we are already in the requested mode
1004 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001005 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001006 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001007 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001008
Ady Abraham838de062019-02-04 10:24:03 -08001009 // Desired active config was set, it is different than the config currently in use, however
1010 // allowed configs might have change by the time we process the refresh.
1011 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001012 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001013 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001014 return false;
1015 }
Alec Mouri7f015182019-07-11 13:56:22 -07001016
Ady Abrahamb838aed2019-02-12 15:30:16 -08001017 mUpcomingActiveConfig = desiredActiveConfig;
1018 const auto displayId = display->getId();
1019 LOG_ALWAYS_FATAL_IF(!displayId);
1020
Ady Abraham2139f732019-11-13 18:56:40 -08001021 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001022
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001023 // TODO(b/142753666) use constrains
1024 HWC2::VsyncPeriodChangeConstraints constraints;
1025 constraints.desiredTimeNanos = systemTime();
1026 constraints.seamlessRequired = false;
1027
1028 HWC2::VsyncPeriodChangeTimeline outTimeline;
1029 auto status =
1030 getHwComposer().setActiveConfigWithConstraints(*displayId,
1031 mUpcomingActiveConfig.configId.value(),
1032 constraints, &outTimeline);
1033 if (status != NO_ERROR) {
1034 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1035 return false;
1036 }
1037
1038 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1039 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001040 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001041 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001042}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001043
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001044status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1045 Vector<ColorMode>* outColorModes) {
1046 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001047 return BAD_VALUE;
1048 }
1049
Peiyong Lina52f0292018-03-14 17:26:31 -07001050 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001051 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001052 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001053 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1054
1055 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1056 if (!displayId) {
1057 return NAME_NOT_FOUND;
1058 }
1059
Dominik Laskowski075d3172018-05-24 15:50:06 -07001060 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001061 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001062 }
Michael Wright28f24d02016-07-12 13:30:53 -07001063 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001064
1065 // If it's built-in display and the configuration claims it's not wide color capable,
1066 // filter out all wide color modes. The typical reason why this happens is that the
1067 // hardware is not good enough to support GPU composition of wide color, and thus the
1068 // OEMs choose to disable this capability.
1069 if (isInternalDisplay && !hasWideColorDisplay) {
1070 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1071 isWideColorMode);
1072 } else {
1073 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1074 }
Michael Wright28f24d02016-07-12 13:30:53 -07001075
1076 return NO_ERROR;
1077}
1078
Daniel Solomon42d04562019-01-20 21:03:19 -08001079status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1080 ui::DisplayPrimaries &primaries) {
1081 if (!displayToken) {
1082 return BAD_VALUE;
1083 }
1084
1085 // Currently we only support this API for a single internal display.
1086 if (getInternalDisplayToken() != displayToken) {
1087 return BAD_VALUE;
1088 }
1089
1090 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1091 return NO_ERROR;
1092}
1093
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1095 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001096 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001097 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001098 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001099}
1100
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001101status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001102 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001103 Vector<ColorMode> modes;
1104 getDisplayColorModes(displayToken, &modes);
1105 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1106 if (mode < ColorMode::NATIVE || !exists) {
1107 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1108 decodeColorMode(mode).c_str(), mode, displayToken.get());
1109 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001110 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001111 const auto display = getDisplayDevice(displayToken);
1112 if (!display) {
1113 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1114 decodeColorMode(mode).c_str(), mode, displayToken.get());
1115 } else if (display->isVirtual()) {
1116 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1117 decodeColorMode(mode).c_str(), mode);
1118 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001119 display->getCompositionDisplay()->setColorProfile(
1120 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1121 RenderIntent::COLORIMETRIC,
1122 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001123 }
1124 }));
1125
Michael Wright28f24d02016-07-12 13:30:53 -07001126 return NO_ERROR;
1127}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001128
Galia Peycheva5492cb52019-10-30 14:13:16 +01001129status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1130 bool* outSupport) const {
1131 Mutex::Autolock _l(mStateLock);
1132
1133 if (!displayToken) {
1134 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1135 return BAD_VALUE;
1136 }
1137 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1138 if (!displayId) {
1139 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1140 displayToken.get());
1141 return NAME_NOT_FOUND;
1142 }
1143 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1144 HWC2::DisplayCapability::AutoLowLatencyMode);
1145 return NO_ERROR;
1146}
1147
1148void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1149 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1150}
1151
1152void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1153 if (!displayToken) {
1154 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1155 return;
1156 }
1157 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1158 if (!displayId) {
1159 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1160 displayToken.get());
1161 return;
1162 }
1163
1164 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1165}
1166
1167status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1168 bool* outSupport) const {
1169 Mutex::Autolock _l(mStateLock);
1170
1171 if (!displayToken) {
1172 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1173 return BAD_VALUE;
1174 }
1175 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1176 if (!displayId) {
1177 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1178 displayToken.get());
1179 return NAME_NOT_FOUND;
1180 }
1181
1182 std::vector<HWC2::ContentType> outSupportedContentTypes;
1183 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1184 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1185 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1186 return NO_ERROR;
1187}
1188
1189void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1190 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1191}
1192
1193void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1194 if (!displayToken) {
1195 ALOGE("setGameContentType() failed. Missing display token.");
1196 return;
1197 }
1198 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1199 if (!displayId) {
1200 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1201 displayToken.get());
1202 return;
1203 }
1204
1205 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1206 getHwComposer().setContentType(*displayId, type);
1207}
1208
Svetoslavd85084b2014-03-20 10:28:31 -07001209status_t SurfaceFlinger::clearAnimationFrameStats() {
1210 Mutex::Autolock _l(mStateLock);
1211 mAnimFrameTracker.clearStats();
1212 return NO_ERROR;
1213}
1214
1215status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1216 Mutex::Autolock _l(mStateLock);
1217 mAnimFrameTracker.getStats(outStats);
1218 return NO_ERROR;
1219}
1220
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001221status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1222 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001223 Mutex::Autolock _l(mStateLock);
1224
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001225 const auto display = getDisplayDeviceLocked(displayToken);
1226 if (!display) {
1227 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001228 return BAD_VALUE;
1229 }
1230
Peiyong Linfb069302018-04-25 14:34:31 -07001231 // At this point the DisplayDeivce should already be set up,
1232 // meaning the luminance information is already queried from
1233 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001234 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001235 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1236 capabilities.getDesiredMaxLuminance(),
1237 capabilities.getDesiredMaxAverageLuminance(),
1238 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001239
1240 return NO_ERROR;
1241}
1242
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001243status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1244 ui::PixelFormat* outFormat,
1245 ui::Dataspace* outDataspace,
1246 uint8_t* outComponentMask) const {
1247 if (!outFormat || !outDataspace || !outComponentMask) {
1248 return BAD_VALUE;
1249 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001250 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001251 if (!display || !display->getId()) {
1252 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1253 return BAD_VALUE;
1254 }
1255 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1256 outDataspace, outComponentMask);
1257}
1258
Kevin DuBois74e53772018-11-19 10:52:38 -08001259status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1260 bool enable, uint8_t componentMask,
1261 uint64_t maxFrames) const {
1262 const auto display = getDisplayDevice(displayToken);
1263 if (!display || !display->getId()) {
1264 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1265 return BAD_VALUE;
1266 }
1267
1268 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1269 componentMask, maxFrames);
1270}
1271
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001272status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1273 uint64_t maxFrames, uint64_t timestamp,
1274 DisplayedFrameStats* outStats) const {
1275 const auto display = getDisplayDevice(displayToken);
1276 if (!display || !display->getId()) {
1277 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1278 return BAD_VALUE;
1279 }
1280
1281 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1282 outStats);
1283}
1284
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001285status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1286 if (!outSupported) {
1287 return BAD_VALUE;
1288 }
1289 *outSupported = getRenderEngine().supportsProtectedContent();
1290 return NO_ERROR;
1291}
1292
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001293status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1294 bool* outIsWideColorDisplay) const {
1295 if (!displayToken || !outIsWideColorDisplay) {
1296 return BAD_VALUE;
1297 }
1298 Mutex::Autolock _l(mStateLock);
1299 const auto display = getDisplayDeviceLocked(displayToken);
1300 if (!display) {
1301 return BAD_VALUE;
1302 }
Peiyong Linff84a152019-05-17 18:36:19 -07001303
1304 // Use hasWideColorDisplay to override built-in display.
1305 const auto displayId = display->getId();
1306 if (displayId && displayId == getInternalDisplayIdLocked()) {
1307 *outIsWideColorDisplay = hasWideColorDisplay;
1308 return NO_ERROR;
1309 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001310 *outIsWideColorDisplay = display->hasWideColorGamut();
1311 return NO_ERROR;
1312}
1313
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001314status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001315 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001316 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001317
Dominik Laskowski6505f792019-09-18 11:10:05 -07001318 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1319 mEventQueue->setEventConnection(
1320 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001321 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001322 }));
1323
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001324 return NO_ERROR;
1325}
1326
1327status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001328 Mutex::Autolock lock(mStateLock);
1329 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001330}
1331
Lloyd Pique755e3192018-01-31 16:46:15 -08001332status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1333 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001334 // Try to acquire a lock for 1s, fail gracefully
1335 const status_t err = mStateLock.timedLock(s2ns(1));
1336 const bool locked = (err == NO_ERROR);
1337 if (!locked) {
1338 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1339 return TIMED_OUT;
1340 }
1341
1342 outLayers->clear();
1343 mCurrentState.traverseInZOrder([&](Layer* layer) {
1344 outLayers->push_back(layer->getLayerDebugInfo());
1345 });
1346
1347 mStateLock.unlock();
1348 return NO_ERROR;
1349}
1350
Peiyong Linc6780972018-10-28 15:24:08 -07001351status_t SurfaceFlinger::getCompositionPreference(
1352 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1353 Dataspace* outWideColorGamutDataspace,
1354 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001355 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001356 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001357 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001358 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001359 return NO_ERROR;
1360}
1361
Dan Stozaec460082018-12-17 15:35:09 -08001362status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1363 const sp<IBinder>& stopLayerHandle,
1364 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001365 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001366 return BAD_VALUE;
1367 }
1368 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001369 return NO_ERROR;
1370}
1371
Dan Stozaec460082018-12-17 15:35:09 -08001372status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001373 if (!listener) {
1374 return BAD_VALUE;
1375 }
Dan Stozaec460082018-12-17 15:35:09 -08001376 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001377 return NO_ERROR;
1378}
Dan Gittik57e63c52019-01-18 16:37:54 +00001379
1380status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1381 bool* outSupport) const {
1382 if (!displayToken || !outSupport) {
1383 return BAD_VALUE;
1384 }
1385 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1386 if (!displayId) {
1387 return NAME_NOT_FOUND;
1388 }
1389 *outSupport =
1390 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1391 return NO_ERROR;
1392}
1393
1394status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1395 float brightness) const {
1396 if (!displayToken) {
1397 return BAD_VALUE;
1398 }
1399 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1400 if (!displayId) {
1401 return NAME_NOT_FOUND;
1402 }
1403 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1404}
1405
Ady Abraham8532d012019-05-08 14:50:56 -07001406status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1407 PowerHint powerHint = static_cast<PowerHint>(hintId);
1408
1409 if (powerHint == PowerHint::INTERACTION) {
1410 mScheduler->notifyTouchEvent();
1411 }
1412
1413 return NO_ERROR;
1414}
1415
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001416// ----------------------------------------------------------------------------
1417
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001418sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001419 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001420 const auto& handle =
1421 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001422
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001423 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001424}
1425
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001426// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001427
1428void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001429 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001430}
1431
1432void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001433 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001434 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001435}
1436
1437void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001438 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001439 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001440}
1441
1442void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001443 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001444 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001445}
1446
1447status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001448 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001449 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001450}
1451
1452status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001453 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001454 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001455 if (res == NO_ERROR) {
1456 msg->wait();
1457 }
1458 return res;
1459}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001460
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001461void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001462 do {
1463 waitForEvent();
1464 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001465}
1466
Dominik Laskowski83b88212018-12-11 13:34:06 -08001467nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001468 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001469 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1470 return 0;
1471 }
1472
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001473 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001474}
1475
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001476void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001477 int64_t timestamp,
1478 std::optional<hwc2_vsync_period_t> /*vsyncPeriod*/) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001479 ATRACE_NAME("SF onVsync");
1480
Ady Abraham7159f572019-10-11 11:10:18 -07001481 // TODO(b/140201379): use vsyncPeriod in the new DispSync
1482
Steven Thomas3cfac282017-02-06 12:29:30 -08001483 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001484 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001485 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001486 return;
1487 }
1488
Dominik Laskowski075d3172018-05-24 15:50:06 -07001489 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001490 return;
1491 }
1492
Dominik Laskowski075d3172018-05-24 15:50:06 -07001493 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001494 // For now, we don't do anything with external display vsyncs.
1495 return;
1496 }
1497
Alec Mourif8e689c2019-05-20 18:32:22 -07001498 bool periodFlushed = false;
1499 mScheduler->addResyncSample(timestamp, &periodFlushed);
1500 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001501 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001502 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001503}
1504
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001505void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001506 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1507 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001508}
1509
Ady Abraham2139f732019-11-13 18:56:40 -08001510bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001511 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001512}
1513
Ady Abraham2139f732019-11-13 18:56:40 -08001514void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1515 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001516 const auto display = getDefaultDisplayDeviceLocked();
1517 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001518 return;
1519 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001520 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001521
Ana Krulec7d1d6832018-12-27 11:10:09 -08001522 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001523 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1524 ALOGV("Skipping config %d as it is not part of allowed configs",
1525 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001526 return;
1527 }
1528
Ady Abraham2139f732019-11-13 18:56:40 -08001529 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001530}
1531
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001532void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001533 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001534 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001535 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001536
Lloyd Piqueba04e622017-12-14 17:11:26 -08001537 // Ignore events that do not have the right sequenceId.
1538 if (sequenceId != getBE().mComposerSequenceId) {
1539 return;
1540 }
1541
Steven Thomasb02664d2017-07-26 18:48:28 -07001542 // Only lock if we're not on the main thread. This function is normally
1543 // called on a hwbinder thread, but for the primary display it's called on
1544 // the main thread with the state lock already held, so don't attempt to
1545 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001546 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001547
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001548 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001549
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001550 if (std::this_thread::get_id() == mMainThreadId) {
1551 // Process all pending hot plug events immediately if we are on the main thread.
1552 processDisplayHotplugEventsLocked();
1553 }
1554
Lloyd Piqueba04e622017-12-14 17:11:26 -08001555 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001556}
1557
Ady Abraham7159f572019-10-11 11:10:18 -07001558void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001559 int32_t sequenceId, hwc2_display_t /*display*/,
1560 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1561 Mutex::Autolock lock(mStateLock);
1562 if (sequenceId != getBE().mComposerSequenceId) {
1563 return;
1564 }
1565 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001566}
1567
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001568void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1569 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1570 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1571}
1572
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001573void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001574 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001575 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001576 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001577 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001578 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001579}
1580
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001581void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001582 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001583
1584 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1585 // display power state.
1586 postMessageAsync(new LambdaMessage(
1587 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1588}
1589
1590void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1591 ATRACE_CALL();
1592
Ady Abraham27c70212019-06-11 10:52:26 -07001593 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1594
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001595 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001596 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1597 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001598 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001599 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001600 }
Mathias Agopian86303202012-07-24 22:46:10 -07001601}
1602
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001603// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001604void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001605 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001606 // Clear the drawing state so that the logic inside of
1607 // handleTransactionLocked will fire. It will determine the delta between
1608 // mCurrentState and mDrawingState and re-apply all changes when we make the
1609 // transition.
1610 mDrawingState.displays.clear();
1611 mDisplays.clear();
1612}
1613
Steven Thomas050b2c82017-03-06 11:45:16 -08001614void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001615 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001616 if (!mVrFlinger)
1617 return;
1618 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001619 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001620 return;
1621 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001622
Lloyd Pique441d5042018-10-18 16:49:51 -07001623 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001624 ALOGE("Vr flinger is only supported for remote hardware composer"
1625 " service connections. Ignoring request to transition to vr"
1626 " flinger.");
1627 mVrFlingerRequestsDisplay = false;
1628 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001629 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001630
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001631 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001632
Steven Thomas0123ac62018-07-12 11:32:34 -07001633 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001634 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001635
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001636 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001637
1638 // Clear out all the output layers from the composition engine for all
1639 // displays before destroying the hardware composer interface. This ensures
1640 // any HWC layers are destroyed through that interface before it becomes
1641 // invalid.
1642 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001643 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001644 }
1645
Steven Thomas0123ac62018-07-12 11:32:34 -07001646 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1647 // called below. Clear the reference now so we don't accidentally use it
1648 // later.
1649 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001650
Steven Thomasb02664d2017-07-26 18:48:28 -07001651 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001652 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001653 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001654
Steven Thomasb02664d2017-07-26 18:48:28 -07001655 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001656 // Delete the current instance before creating the new one
1657 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1658 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1659 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1660 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001661
Lloyd Pique441d5042018-10-18 16:49:51 -07001662 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001663 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001664
1665 if (vrFlingerRequestsDisplay) {
1666 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001667 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001668
1669 mVisibleRegionsDirty = true;
1670 invalidateHwcGeometry();
1671
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001672 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001673 display = getDefaultDisplayDeviceLocked();
1674 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001675 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001676
Steven Thomasb02664d2017-07-26 18:48:28 -07001677 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001678 const nsecs_t vsyncPeriod = getVsyncPeriod();
1679 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001680
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001681 // The present fences returned from vr_hwc are not an accurate
1682 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001683 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001684
Steven Thomasb02664d2017-07-26 18:48:28 -07001685 // Use phase of 0 since phase is not known.
1686 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001687 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001688 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001689
Ana Krulecc2870422019-01-29 19:00:58 -08001690 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001691
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001692 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001693 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001694}
1695
Ady Abraham11579302019-09-19 12:35:58 -07001696bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1697 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001698 // We are storing the last 2 present fences. If sf's phase offset is to be
1699 // woken up before the actual vsync but targeting the next vsync, we need to check
1700 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001701 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1702 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001703
Ady Abraham11579302019-09-19 12:35:58 -07001704 if (fence == Fence::NO_FENCE) {
1705 return false;
1706 }
1707
1708 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1709 fence->wait(graceTimeMs);
1710 }
1711
1712 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001713}
1714
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001715void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001716 DisplayStatInfo stats;
1717 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001718 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001719 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001720 mExpectedPresentTime.store(
1721 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001722}
1723
Dominik Laskowski22488f62019-03-28 09:53:04 -07001724void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001725 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001726 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001727 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001728 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001729 // calculate the expected present time once and use the cached
1730 // value throughout this frame to make sure all layers are
1731 // seeing this same value.
1732 populateExpectedPresentTime();
1733
Ady Abraham11579302019-09-19 12:35:58 -07001734 // When Backpressure propagation is enabled we want to give a small grace period
1735 // for the present fence to fire instead of just giving up on this frame to handle cases
1736 // where present fence is just about to get signaled.
1737 const int graceTimeForPresentFenceMs =
1738 (mPropagateBackpressure &&
1739 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1740 ? 1
1741 : 0;
1742 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1743 previousFrameMissed(
1744 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001745 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1746 mHadDeviceComposition && frameMissed};
1747 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1748 mHadClientComposition && frameMissed};
1749
Alec Mouricc0fc602019-02-26 21:45:19 -08001750 if (frameMissed) {
1751 mFrameMissedCount++;
1752 mTimeStats->incrementMissedFrames();
1753 }
1754
Alec Mouri40189b02019-03-05 15:07:54 -08001755 if (hwcFrameMissed) {
1756 mHwcFrameMissedCount++;
1757 }
1758
1759 if (gpuFrameMissed) {
1760 mGpuFrameMissedCount++;
1761 }
1762
Ady Abrahamadb9a992019-09-19 21:21:55 +00001763 if (frameMissed && mPropagateBackpressure) {
1764 if ((hwcFrameMissed && !gpuFrameMissed) ||
1765 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001766 signalLayerUpdate();
1767 break;
1768 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001769 }
Dan Stoza50182882016-07-08 12:02:20 -07001770
Steven Thomas050b2c82017-03-06 11:45:16 -08001771 // Now that we're going to make it to the handleMessageTransaction()
1772 // call below it's safe to call updateVrFlinger(), which will
1773 // potentially trigger a display handoff.
1774 updateVrFlinger();
1775
Dan Stoza6b9454d2014-11-07 16:00:59 -08001776 bool refreshNeeded = handleMessageTransaction();
1777 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001778
Ana Krulecc84d09b2019-11-02 23:10:29 +01001779 // Layers need to get updated (in the previous line) before we can use them for
1780 // choosing the refresh rate.
1781 mScheduler->chooseRefreshRateForContent();
1782 if (performSetActiveConfig()) {
1783 break;
1784 }
1785
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001786 updateCursorAsync();
1787 updateInputFlinger();
1788
Dan Stoza58784442014-12-02 16:58:17 -08001789 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001790 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001791 // Signal a refresh if a transaction modified the window state,
1792 // a new buffer was latched, or if HWC has requested a full
1793 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001794 if (mFrameStartTime <= 0) {
1795 // We should only use the time of the first invalidate
1796 // message that signals a refresh as the beginning of the
1797 // frame. Otherwise the real frame time will be
1798 // underestimated.
1799 mFrameStartTime = frameStart;
1800 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001801 signalRefresh();
1802 }
1803 break;
1804 }
1805 case MessageQueue::REFRESH: {
1806 handleMessageRefresh();
1807 break;
1808 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001809 }
1810}
1811
Dan Stoza6b9454d2014-11-07 16:00:59 -08001812bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001813 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001814 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001815
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001816 bool flushedATransaction = flushTransactionQueues();
1817
1818 bool runHandleTransaction = transactionFlags &&
1819 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1820
1821 if (runHandleTransaction) {
1822 handleTransaction(eTransactionMask);
1823 } else {
1824 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001825 }
1826
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001827 if (transactionFlushNeeded()) {
1828 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001829 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001830
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001831 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001832}
1833
Mathias Agopian4fec8732012-06-29 14:12:52 -07001834void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001835 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001836
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001837 mRefreshPending = false;
1838
Lloyd Piqueab039b52019-02-13 14:22:42 -08001839 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001840 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001841 for (const auto& [_, display] : mDisplays) {
1842 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1843 }
1844 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1845 auto compositionLayer = layer->getCompositionLayer();
1846 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1847 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001848 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1849 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1850 auto compositionLayer = layer->getCompositionLayer();
Adithya Srinivasan87c1b80e2019-11-21 11:43:06 -08001851 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001852 }
1853
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001854 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001855 refreshArgs.outputColorSetting = useColorManagement
1856 ? mDisplayColorSetting
1857 : compositionengine::OutputColorSetting::kUnmanaged;
1858 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1859 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001860
1861 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1862 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001863
1864 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1865 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1866 mDrawingState.colorMatrixChanged = false;
1867 }
1868
1869 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1870
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001871 if (mDebugRegion != 0) {
1872 refreshArgs.devOptFlashDirtyRegionsDelay =
1873 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1874 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001875
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001876 mGeometryInvalid = false;
1877
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001878 // Store the present time just before calling to the composition engine so we could notify
1879 // the scheduler.
1880 const auto presentTime = systemTime();
1881
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001882 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001883 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1884 // Reset the frame start time now that we've recorded this frame.
1885 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001886
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001887 mScheduler->onDisplayRefreshed(presentTime);
1888
David Sodmanfa9b2af2017-12-24 13:28:59 -08001889 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001890 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001891
Lloyd Pique66d68602019-02-13 14:23:31 -08001892 mHadClientComposition =
1893 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1894 auto& displayDevice = tokenDisplayPair.second;
1895 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1896 });
1897 mHadDeviceComposition =
1898 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1899 auto& displayDevice = tokenDisplayPair.second;
1900 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1901 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001902
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001903 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001904
David Sodman7e4ae112018-02-09 15:02:28 -08001905 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001906 if (mVisibleRegionsDirty) {
1907 mVisibleRegionsDirty = false;
1908 if (mTracingEnabled) {
1909 mTracing.notify("visibleRegionsDirty");
1910 }
1911 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001912
1913 if (mCompositionEngine->needsAnotherUpdate()) {
1914 signalLayerUpdate();
1915 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001916}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001917
David Sodmanfa9b2af2017-12-24 13:28:59 -08001918
1919bool SurfaceFlinger::handleMessageInvalidate() {
1920 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001921 bool refreshNeeded = handlePageFlip();
1922
Vishnu Nair4351ad52019-02-11 14:13:02 -08001923 if (mVisibleRegionsDirty) {
1924 computeLayerBounds();
1925 }
1926
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001927 for (auto& layer : mLayersPendingRefresh) {
1928 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001929 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001930 invalidateLayerStack(layer, visibleReg);
1931 }
1932 mLayersPendingRefresh.clear();
1933 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001934}
1935
Ana Krulece588e312018-09-18 12:32:24 -07001936void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1937 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001938 // Update queue of past composite+present times and determine the
1939 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001940 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001941 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001942 while (!getBE().mCompositePresentTimes.empty()) {
1943 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944 // Cached values should have been updated before calling this method,
1945 // which helps avoid duplicate syscalls.
1946 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1947 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1948 break;
1949 }
1950 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001951 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001952 }
1953
1954 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001955 while (getBE().mCompositePresentTimes.size() > 16) {
1956 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001957 }
1958
Ana Krulece588e312018-09-18 12:32:24 -07001959 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001960}
1961
Ana Krulece588e312018-09-18 12:32:24 -07001962void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1963 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001964 // Integer division and modulo round toward 0 not -inf, so we need to
1965 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08001966 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
1967 ? (stats.vsyncPeriod -
1968 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
1969 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001970
Ady Abraham9e16a482019-12-03 17:19:41 -08001971 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001972 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001973 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001974 }
1975
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001976 // Snap the latency to a value that removes scheduling jitter from the
1977 // composition and present times, which often have >1ms of jitter.
1978 // Reducing jitter is important if an app attempts to extrapolate
1979 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08001980 // Snapping also allows an app to precisely calculate
1981 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001982 nsecs_t bias = stats.vsyncPeriod / 2;
1983 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1984 nsecs_t snappedCompositeToPresentLatency =
1985 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001986
David Sodman99974d22017-11-28 12:04:33 -08001987 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001988 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1989 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001990 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001991}
1992
David Sodman2b406362017-12-15 13:33:47 -08001993void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001994{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001995 ATRACE_CALL();
1996 ALOGV("postComposition");
1997
Brian Anderson3546a3f2016-07-14 11:51:14 -07001998 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001999 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002000 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002001 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002002 }
2003
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002004 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002005 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002006
David Sodman73beded2017-11-15 11:56:06 -08002007 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002008 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002009 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002010 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002011 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2012 ->getRenderSurface()
2013 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002014 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002015 } else {
2016 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2017 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002018
David Sodman73beded2017-11-15 11:56:06 -08002019 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002020 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2021 mPreviousPresentFences[0] = displayDevice
2022 ? getHwComposer().getPresentFence(*displayDevice->getId())
2023 : Fence::NO_FENCE;
2024 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002025 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002026
Ana Krulece588e312018-09-18 12:32:24 -07002027 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002028 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002029
Lloyd Piqueab039b52019-02-13 14:22:42 -08002030 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2031 // be sampled a little later than when we started doing work for this frame,
2032 // but that should be okay since updateCompositorTiming has snapping logic.
2033 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2034 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002035 CompositorTiming compositorTiming;
2036 {
David Sodman99974d22017-11-28 12:04:33 -08002037 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2038 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002039 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002040
Robert Carr2047fae2016-11-28 14:09:09 -08002041 mDrawingState.traverseInZOrder([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002042 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2043 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002044 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002045 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002046 }
Robert Carr2047fae2016-11-28 14:09:09 -08002047 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002048
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002049 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002050 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002051 }
2052
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002053 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002054 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2055 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002056 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002057 }
2058 }
2059
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002060 if (mAnimCompositionPending) {
2061 mAnimCompositionPending = false;
2062
Brian Anderson4e606e32017-03-16 15:34:57 -07002063 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002064 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002065 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002066 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002067 // The HWC doesn't support present fences, so use the refresh
2068 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002069 const nsecs_t presentTime =
2070 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002071 mAnimFrameTracker.setActualPresentTime(presentTime);
2072 }
2073 mAnimFrameTracker.advanceFrame();
2074 }
Dan Stozab90cf072015-03-05 11:05:59 -08002075
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002076 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002077 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002078 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002079 }
2080
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002081 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002082
Lloyd Pique32cbe282018-10-19 13:09:22 -07002083 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2084 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002085 return;
2086 }
2087
2088 nsecs_t currentTime = systemTime();
2089 if (mHasPoweredOff) {
2090 mHasPoweredOff = false;
2091 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002092 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002093 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002094 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2095 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002096 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002097 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002098 }
David Sodman4a36e932017-11-07 14:29:47 -08002099 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002100 }
David Sodman4a36e932017-11-07 14:29:47 -08002101 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002102
2103 {
2104 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002105 if (mTexturePool.size() < mTexturePoolSize) {
2106 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002107 const size_t offset = mTexturePool.size();
2108 mTexturePool.resize(mTexturePoolSize);
2109 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2110 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002111 } else if (mTexturePool.size() > mTexturePoolSize) {
2112 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2113 const size_t offset = mTexturePoolSize;
2114 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2115 mTexturePool.resize(mTexturePoolSize);
2116 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002117 }
2118 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002119
Ady Abrahambe0f9482019-04-24 15:41:53 -07002120 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002121 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002122
Kevin DuBois413287f2019-02-25 08:46:47 -08002123 if (mLumaSampling && mRegionSamplingThread) {
2124 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002125 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002126
2127 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2128 // side-effect of getTotalSize(), so we check that again here
2129 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002130 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002131 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2132 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002133}
2134
Vishnu Nair4351ad52019-02-11 14:13:02 -08002135void SurfaceFlinger::computeLayerBounds() {
2136 for (const auto& pair : mDisplays) {
2137 const auto& displayDevice = pair.second;
2138 const auto display = displayDevice->getCompositionDisplay();
2139 for (const auto& layer : mDrawingState.layersSortedByZ) {
2140 // only consider the layers on the given layer stack
2141 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002142 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002143 }
2144
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002145 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2146 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002147 }
2148 }
2149}
2150
David Sodmanfa9b2af2017-12-24 13:28:59 -08002151void SurfaceFlinger::postFrame()
2152{
2153 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002154 const auto display = getDefaultDisplayDeviceLocked();
2155 if (display && getHwComposer().isConnected(*display->getId())) {
2156 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002157 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2158 logFrameStats();
2159 }
2160 }
2161}
2162
Mathias Agopian87baae12012-07-31 12:38:26 -07002163void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002164{
Mathias Agopian841cde52012-03-01 15:44:37 -08002165 ATRACE_CALL();
2166
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002167 // here we keep a copy of the drawing state (that is the state that's
2168 // going to be overwritten by handleTransactionLocked()) outside of
2169 // mStateLock so that the side-effects of the State assignment
2170 // don't happen with mStateLock held (which can cause deadlocks).
2171 State drawingState(mDrawingState);
2172
Mathias Agopianca4d3602011-05-19 15:38:14 -07002173 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002174 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002175
Mathias Agopianca4d3602011-05-19 15:38:14 -07002176 // Here we're guaranteed that some transaction flags are set
2177 // so we can call handleTransactionLocked() unconditionally.
2178 // We call getTransactionFlags(), which will also clear the flags,
2179 // with mStateLock held to guarantee that mCurrentState won't change
2180 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002181
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002182 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002183 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002184 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002185
Mathias Agopianca4d3602011-05-19 15:38:14 -07002186 mDebugInTransaction = 0;
2187 invalidateHwcGeometry();
2188 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002189}
2190
Lloyd Piqueba04e622017-12-14 17:11:26 -08002191void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2192 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002193 const std::optional<DisplayIdentificationInfo> info =
2194 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002195
Dominik Laskowski075d3172018-05-24 15:50:06 -07002196 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002197 continue;
2198 }
2199
Lloyd Piqueba04e622017-12-14 17:11:26 -08002200 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002201 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002202 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002203 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2204 initScheduler(info->id);
2205 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002206 mPhysicalDisplayTokens[info->id] = new BBinder();
2207 DisplayDeviceState state;
2208 state.displayId = info->id;
2209 state.isSecure = true; // All physical displays are currently considered secure.
2210 state.displayName = info->name;
2211 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2212 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002213 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002214 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002215 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002216
Dominik Laskowski075d3172018-05-24 15:50:06 -07002217 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2218 if (index >= 0) {
2219 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2220 mInterceptor->saveDisplayDeletion(state.sequenceId);
2221 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002222 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002223 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002224 }
2225
2226 processDisplayChangesLocked();
2227 }
2228
2229 mPendingHotplugEvents.clear();
2230}
2231
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002232void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002233 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2234 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002235}
2236
Lloyd Pique99d3da52018-01-22 17:48:03 -08002237sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002238 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002239 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002240 const sp<IGraphicBufferProducer>& producer) {
2241 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002242 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002243 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002244 creationArgs.isSecure = state.isSecure;
2245 creationArgs.displaySurface = dispSurface;
2246 creationArgs.hasWideColorGamut = false;
2247 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002248 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002249
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002250 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002251 creationArgs.isPrimary = isInternalDisplay;
2252
2253 if (useColorManagement && displayId) {
2254 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002255 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002256 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002257 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002258 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002259
Dominik Laskowski7e045462018-05-30 13:02:02 -07002260 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002261 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002262 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002263 }
tangrobin6753a022018-08-10 10:58:54 +08002264 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002265
Dominik Laskowski075d3172018-05-24 15:50:06 -07002266 if (displayId) {
2267 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002268 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002269 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002270 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002271
Lloyd Pique90c115d2018-09-18 21:39:42 -07002272 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002273 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002274 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002275
Lloyd Pique99d3da52018-01-22 17:48:03 -08002276 // Make sure that composition can never be stalled by a virtual display
2277 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002278 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002279 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002280 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2281 }
2282
Dominik Laskowski718f9602019-11-09 20:01:35 -08002283 creationArgs.physicalOrientation =
2284 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002285
Lloyd Pique99d3da52018-01-22 17:48:03 -08002286 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002287 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002288
Lloyd Pique90c115d2018-09-18 21:39:42 -07002289 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002290
2291 if (maxFrameBufferAcquiredBuffers >= 3) {
2292 nativeWindowSurface->preallocateBuffers();
2293 }
2294
2295 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002296 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002297 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002298 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002299 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002300 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002301 display->getCompositionDisplay()->setColorProfile(
2302 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2303 RenderIntent::COLORIMETRIC,
2304 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002305 if (!state.isVirtual()) {
2306 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002307 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2308 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002309 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002310
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002311 display->setLayerStack(state.layerStack);
2312 display->setProjection(state.orientation, state.viewport, state.frame);
2313 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002314
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002316}
2317
Lloyd Pique347200f2017-12-14 17:00:15 -08002318void SurfaceFlinger::processDisplayChangesLocked() {
2319 // here we take advantage of Vector's copy-on-write semantics to
2320 // improve performance by skipping the transaction entirely when
2321 // know that the lists are identical
2322 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2323 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2324 if (!curr.isIdenticalTo(draw)) {
2325 mVisibleRegionsDirty = true;
2326 const size_t cc = curr.size();
2327 size_t dc = draw.size();
2328
2329 // find the displays that were removed
2330 // (ie: in drawing state but not in current state)
2331 // also handle displays that changed
2332 // (ie: displays that are in both lists)
2333 for (size_t i = 0; i < dc;) {
2334 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2335 if (j < 0) {
2336 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002337 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002338 // Save display ID before disconnecting.
2339 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002340 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002341
2342 if (!display->isVirtual()) {
2343 LOG_ALWAYS_FATAL_IF(!displayId);
2344 dispatchDisplayHotplugEvent(displayId->value, false);
2345 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002346 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002347
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002348 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002349 } else {
2350 // this display is in both lists. see if something changed.
2351 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002352 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002353 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2354 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2355 if (state_binder != draw_binder) {
2356 // changing the surface is like destroying and
2357 // recreating the DisplayDevice, so we just remove it
2358 // from the drawing state, so that it get re-added
2359 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002360 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002361 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002362 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002363 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002364 mDrawingState.displays.removeItemsAt(i);
2365 dc--;
2366 // at this point we must loop to the next item
2367 continue;
2368 }
2369
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002370 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002371 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002372 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002373 }
2374 if ((state.orientation != draw[i].orientation) ||
2375 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002376 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002377 }
2378 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002379 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002380 }
2381 }
2382 }
2383 ++i;
2384 }
2385
2386 // find displays that were added
2387 // (ie: in current state but not in drawing state)
2388 for (size_t i = 0; i < cc; i++) {
2389 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2390 const DisplayDeviceState& state(curr[i]);
2391
Lloyd Pique542307f2018-10-19 13:24:08 -07002392 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002393 sp<IGraphicBufferProducer> producer;
2394 sp<IGraphicBufferProducer> bqProducer;
2395 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002396 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002397
Dominik Laskowski075d3172018-05-24 15:50:06 -07002398 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002399 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002400 // Virtual displays without a surface are dormant:
2401 // they have external state (layer stack, projection,
2402 // etc.) but no internal state (i.e. a DisplayDevice).
2403 if (state.surface != nullptr) {
2404 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002405 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002406 int width = 0;
2407 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2408 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2409 int height = 0;
2410 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2411 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2412 int intFormat = 0;
2413 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2414 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002415 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002416
Dominik Laskowski075d3172018-05-24 15:50:06 -07002417 displayId =
2418 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002419 }
2420
2421 // TODO: Plumb requested format back up to consumer
2422
2423 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002424 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002425 bqProducer, bqConsumer,
2426 state.displayName);
2427
2428 dispSurface = vds;
2429 producer = vds;
2430 }
2431 } else {
2432 ALOGE_IF(state.surface != nullptr,
2433 "adding a supported display, but rendering "
2434 "surface is provided (%p), ignoring it",
2435 state.surface.get());
2436
Dominik Laskowski075d3172018-05-24 15:50:06 -07002437 displayId = state.displayId;
2438 LOG_ALWAYS_FATAL_IF(!displayId);
2439 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002440 producer = bqProducer;
2441 }
2442
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002443 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002444 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002445 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002446 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002447 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002448 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002449 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002450 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002451 }
2452 }
2453 }
2454 }
2455 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002456
2457 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002458}
2459
Mathias Agopian87baae12012-07-31 12:38:26 -07002460void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002461{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002462 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2463
Dan Stoza7dde5992015-05-22 09:51:44 -07002464 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002465 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2466 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002467 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002468
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002469 /*
2470 * Traversal of the children
2471 * (perform the transaction for each of them if needed)
2472 */
2473
Marissa Wall06255332019-03-27 13:48:27 -07002474 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002475 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002476 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002477 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002478
2479 const uint32_t flags = layer->doTransaction(0);
2480 if (flags & Layer::eVisibleRegion)
2481 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002482
2483 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002484 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002485 }
Robert Carr2047fae2016-11-28 14:09:09 -08002486 });
Marissa Wall06255332019-03-27 13:48:27 -07002487 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002488 }
2489
2490 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002491 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492 */
2493
Mathias Agopiane57f2922012-08-09 16:29:12 -07002494 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002495 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002496 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002497 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002498
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002499 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002500 // The transform hint might have changed for some layers
2501 // (either because a display has changed, or because a layer
2502 // as changed).
2503 //
2504 // Walk through all the layers in currentLayers,
2505 // and update their transform hint.
2506 //
2507 // If a layer is visible only on a single display, then that
2508 // display is used to calculate the hint, otherwise we use the
2509 // default display.
2510 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002511 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002512 // the hint is set before we acquire a buffer from the surface texture.
2513 //
2514 // NOTE: layer transactions have taken place already, so we use their
2515 // drawing state. However, SurfaceFlinger's own transaction has not
2516 // happened yet, so we must use the current state layer list
2517 // (soon to become the drawing state list).
2518 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002519 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002520 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002521 bool first = true;
2522 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002523 // NOTE: we rely on the fact that layers are sorted by
2524 // layerStack first (so we don't have to traverse the list
2525 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002526 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002527 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002528 currentlayerStack = layerStack;
2529 // figure out if this layerstack is mirrored
2530 // (more than one display) if so, pick the default display,
2531 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002532 hintDisplay = nullptr;
2533 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002534 if (display->getCompositionDisplay()
2535 ->belongsInOutput(layer->getLayerStack(),
2536 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002537 if (hintDisplay) {
2538 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002539 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002540 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002541 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002542 }
2543 }
2544 }
2545 }
Chet Haase91d25932013-04-11 15:24:55 -07002546
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002547 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002548 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2549 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002550
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002551 // could be null when this layer is using a layerStack
2552 // that is not visible on any display. Also can occur at
2553 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002554 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002555 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002556
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002557 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002558 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002559 if (hintDisplay) {
2560 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002561 }
Robert Carr2047fae2016-11-28 14:09:09 -08002562
2563 first = false;
2564 });
Mathias Agopian84300952012-11-21 16:02:13 -08002565 }
2566
2567
Mathias Agopian3559b072012-08-15 13:46:03 -07002568 /*
2569 * Perform our own transaction if needed
2570 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002571
2572 if (mLayersAdded) {
2573 mLayersAdded = false;
2574 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002575 mVisibleRegionsDirty = true;
2576 }
2577
2578 // some layers might have been removed, so
2579 // we need to update the regions they're exposing.
2580 if (mLayersRemoved) {
2581 mLayersRemoved = false;
2582 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002583 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002584 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002585 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002586 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002587 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002588 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002589 }
Robert Carr2047fae2016-11-28 14:09:09 -08002590 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002591 }
2592
Vishnu Nairec0ab382019-02-13 15:32:56 -08002593 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002594 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002595}
2596
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002597void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002598 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002599 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002600 return;
2601 }
2602
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002603 if (mVisibleRegionsDirty || mInputInfoChanged) {
2604 mInputInfoChanged = false;
2605 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002606 } else if (mInputWindowCommands.syncInputWindows) {
2607 // If the caller requested to sync input windows, but there are no
2608 // changes to input windows, notify immediately.
2609 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002610 }
2611
Arthur Hung6cbb9752019-09-05 16:38:18 +08002612 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002613}
2614
2615void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002616 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002617
2618 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2619 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002620 // When calculating the screen bounds we ignore the transparent region since it may
2621 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002622 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002623 }
2624 });
chaviw291d88a2019-02-14 10:33:58 -08002625
2626 mInputFlinger->setInputWindows(inputHandles,
2627 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2628 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002629}
2630
Vishnu Nairec0ab382019-02-13 15:32:56 -08002631void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002632 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002633 mPendingInputWindowCommands.clear();
2634}
2635
Riley Andrews03414a12014-07-01 14:22:59 -07002636void SurfaceFlinger::updateCursorAsync()
2637{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002638 compositionengine::CompositionRefreshArgs refreshArgs;
2639 for (const auto& [_, display] : mDisplays) {
2640 if (display->getId()) {
2641 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002642 }
2643 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002644
2645 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002646}
2647
Ady Abraham2139f732019-11-13 18:56:40 -08002648void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
2649 Scheduler::ConfigEvent event) {
2650 Mutex::Autolock lock(mStateLock);
2651 changeRefreshRateLocked(refreshRate, event);
2652}
2653
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002654void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2655 if (mScheduler) {
2656 // In practice it's not allowed to hotplug in/out the primary display once it's been
2657 // connected during startup, but some tests do it, so just warn and return.
2658 ALOGW("Can't re-init scheduler");
2659 return;
2660 }
2661
Ady Abraham2139f732019-11-13 18:56:40 -08002662 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002663 mRefreshRateConfigs =
2664 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2665 getHwComposer().getConfigs(
2666 primaryDisplayId),
2667 currentConfig);
2668 mRefreshRateStats =
2669 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2670 currentConfig, HWC_POWER_MODE_OFF);
2671 mRefreshRateStats->setConfigMode(currentConfig);
2672
Ady Abraham9e16a482019-12-03 17:19:41 -08002673 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2674
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002675 // start the EventThread
2676 mScheduler =
2677 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002678 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002679 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002680 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002681 impl::EventThread::InterceptVSyncsCallback());
2682 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002683 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002684 [this](nsecs_t timestamp) {
2685 mInterceptor->saveVSyncEvent(timestamp);
2686 });
2687
2688 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2689 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002690 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002691
2692 mRegionSamplingThread =
2693 new RegionSamplingThread(*this, *mScheduler,
2694 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002695 // Dispatch a config change request for the primary display on scheduler
2696 // initialization, so that the EventThreads always contain a reference to a
2697 // prior configuration.
2698 //
2699 // This is a bit hacky, but this avoids a back-pointer into the main SF
2700 // classes from EventThread, and there should be no run-time binder cost
2701 // anyway since there are no connected apps at this point.
2702 const nsecs_t vsyncPeriod =
2703 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2704 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2705 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002706}
2707
Mathias Agopian4fec8732012-06-29 14:12:52 -07002708void SurfaceFlinger::commitTransaction()
2709{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002710 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002711
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002712 mTransactionPending = false;
2713 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002714 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002715}
2716
Lloyd Pique58e24a32019-08-01 15:50:14 -07002717void SurfaceFlinger::commitTransactionLocked() {
2718 if (!mLayersPendingRemoval.isEmpty()) {
2719 // Notify removed layers now that they can't be drawn from
2720 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002721 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002722
2723 // Ensure any buffers set to display on any children are released.
2724 if (l->isRemovedFromCurrentState()) {
2725 l->latchAndReleaseBuffer();
2726 }
2727
2728 // If the layer has been removed and has no parent, then it will not be reachable
2729 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2730 // ensure we can copy its current to drawing state.
2731 if (!l->getParent()) {
2732 mOffscreenLayers.emplace(l.get());
2733 }
2734 }
2735 mLayersPendingRemoval.clear();
2736 }
2737
2738 // If this transaction is part of a window animation then the next frame
2739 // we composite should be considered an animation as well.
2740 mAnimCompositionPending = mAnimTransactionPending;
2741
2742 mDrawingState = mCurrentState;
2743 // clear the "changed" flags in current state
2744 mCurrentState.colorMatrixChanged = false;
2745
2746 mDrawingState.traverseInZOrder([&](Layer* layer) {
2747 layer->commitChildList();
2748
2749 // If the layer can be reached when traversing mDrawingState, then the layer is no
2750 // longer offscreen. Remove the layer from the offscreenLayer set.
2751 if (mOffscreenLayers.count(layer)) {
2752 mOffscreenLayers.erase(layer);
2753 }
2754 });
2755
2756 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002757 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002758}
2759
Nataniel Borges2b796da2019-02-15 13:32:18 -08002760void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2761 if (mTracingEnabledChanged) {
2762 mTracingEnabled = mTracing.isEnabled();
2763 mTracingEnabledChanged = false;
2764 }
2765
2766 // Synchronize with Tracing thread
2767 std::unique_lock<std::mutex> lock;
2768 if (mTracingEnabled) {
2769 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2770 }
2771
2772 lockedOperation();
2773
2774 // Synchronize with Tracing thread
2775 if (mTracingEnabled) {
2776 lock.unlock();
2777 }
2778}
2779
chaviw74d90ad2019-04-26 14:45:26 -07002780void SurfaceFlinger::commitOffscreenLayers() {
2781 for (Layer* offscreenLayer : mOffscreenLayers) {
2782 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2783 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2784 if (!trFlags) return;
2785
2786 layer->doTransaction(0);
2787 layer->commitChildList();
2788 });
2789 }
2790}
2791
Chia-I Wuab0c3192017-08-01 11:29:00 -07002792void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002793 for (const auto& [token, displayDevice] : mDisplays) {
2794 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002795 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002796 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002797 }
2798 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002799}
2800
Dan Stoza6b9454d2014-11-07 16:00:59 -08002801bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802{
Ady Abraham09bd3922019-04-08 10:44:56 -07002803 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002804 ALOGV("handlePageFlip");
2805
Brian Andersond6927fb2016-07-23 23:37:30 -07002806 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807
Mathias Agopian4fec8732012-06-29 14:12:52 -07002808 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002809 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002810 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002811
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002812 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2813
Eric Penner51c59cd2014-07-28 19:51:58 -07002814 // Store the set of layers that need updates. This set must not change as
2815 // buffers are being latched, as this could result in a deadlock.
2816 // Example: Two producers share the same command stream and:
2817 // 1.) Layer 0 is latched
2818 // 2.) Layer 0 gets a new frame
2819 // 2.) Layer 1 gets a new frame
2820 // 3.) Layer 1 is latched.
2821 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2822 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002823 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002824 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002825 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002826 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002827 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002828 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002829 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002830 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002831 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002832 } else {
2833 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002834 }
Robert Carr2047fae2016-11-28 14:09:09 -08002835 });
2836
chaviw49a108c2019-08-12 11:23:06 -07002837 // The client can continue submitting buffers for offscreen layers, but they will not
2838 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2839 // layers to ensure dequeueBuffer doesn't block indefinitely.
2840 for (Layer* offscreenLayer : mOffscreenLayers) {
2841 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2842 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2843 }
2844
Lloyd Piquef2c79392018-12-20 16:23:33 -08002845 if (!mLayersWithQueuedFrames.empty()) {
2846 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2847 // writes to Layer current state. See also b/119481871
2848 Mutex::Autolock lock(mStateLock);
2849
2850 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002851 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002852 mLayersPendingRefresh.push_back(layer);
2853 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002854 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002855 if (layer->isBufferLatched()) {
2856 newDataLatched = true;
2857 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002858 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002859 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002860
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002861 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002862
2863 // If we will need to wake up at some time in the future to deal with a
2864 // queued frame that shouldn't be displayed during this vsync period, wake
2865 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002866 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002867 signalLayerUpdate();
2868 }
2869
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002870 // enter boot animation on first buffer latch
2871 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2872 ALOGI("Enter boot animation");
2873 mBootStage = BootStage::BOOTANIMATION;
2874 }
2875
chaviw74b03172019-08-19 11:09:03 -07002876 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2877
Dan Stoza6b9454d2014-11-07 16:00:59 -08002878 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002879 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002880}
2881
Mathias Agopianad456f92011-01-13 17:53:01 -08002882void SurfaceFlinger::invalidateHwcGeometry()
2883{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002884 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002885}
2886
Robert Carrc0df3122019-04-11 13:18:21 -07002887status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2888 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2889 const sp<IBinder>& parentHandle,
2890 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002891 // add this layer to the current state list
2892 {
2893 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002894 sp<Layer> parent;
2895 if (parentHandle != nullptr) {
2896 parent = fromHandle(parentHandle);
2897 if (parent == nullptr) {
2898 return NAME_NOT_FOUND;
2899 }
2900 } else {
2901 parent = parentLayer;
2902 }
2903
Robert Carr1f0a16a2016-10-24 16:27:39 -07002904 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002905 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002906 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002907 return NO_MEMORY;
2908 }
Robert Carrc0df3122019-04-11 13:18:21 -07002909
2910 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2911
Robert Carrb89ea9d2018-12-10 13:01:14 -08002912 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002913 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002914 } else if (parent == nullptr) {
2915 lbc->onRemovedFromCurrentState();
2916 } else if (parent->isRemovedFromCurrentState()) {
2917 parent->addChild(lbc);
2918 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002919 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002920 parent->addChild(lbc);
2921 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002922
Yiwei Zhang243b3782018-05-15 17:40:04 -07002923 if (gbc != nullptr) {
2924 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2925 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2926 mMaxGraphicBufferProducerListSize,
2927 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2928 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002929 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002930 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002931 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002932 }
2933
Mathias Agopian96f08192010-06-02 23:28:45 -07002934 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002935 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002936
Dan Stoza7d89d062015-04-30 13:29:25 -07002937 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002938}
2939
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002940uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002941 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002942}
2943
Mathias Agopian3f844832013-08-07 21:24:32 -07002944uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002945 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002946}
2947
Mathias Agopian3f844832013-08-07 21:24:32 -07002948uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002949 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002950}
2951
2952uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002953 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002954 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002955 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002956 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002957 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002958 }
2959 return old;
2960}
2961
Marissa Wall713b63f2018-10-17 15:42:43 -07002962bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002963 // to prevent onHandleDestroyed from being called while the lock is held,
2964 // we must keep a copy of the transactions (specifically the composer
2965 // states) around outside the scope of the lock
2966 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002967 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002968 {
2969 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002970
Valerie Haufce31b82019-04-30 16:41:14 -07002971 auto it = mTransactionQueues.begin();
2972 while (it != mTransactionQueues.end()) {
2973 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002974
Valerie Haufce31b82019-04-30 16:41:14 -07002975 while (!transactionQueue.empty()) {
2976 const auto& transaction = transactionQueue.front();
2977 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002978 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002979 transaction.states)) {
2980 setTransactionFlags(eTransactionFlushNeeded);
2981 break;
2982 }
2983 transactions.push_back(transaction);
2984 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2985 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002986 transaction.buffer, transaction.postTime,
2987 transaction.privileged, transaction.hasListenerCallbacks,
2988 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002989 transactionQueue.pop();
2990 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002991 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002992
Valerie Haufce31b82019-04-30 16:41:14 -07002993 if (transactionQueue.empty()) {
2994 it = mTransactionQueues.erase(it);
2995 mTransactionCV.broadcast();
2996 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002997 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002998 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002999 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003000 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003001 return flushedATransaction;
3002}
3003
3004bool SurfaceFlinger::transactionFlushNeeded() {
3005 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003006}
3007
chaviwca27f252018-02-06 16:46:39 -08003008
Marissa Wall17b4e452018-12-26 16:32:34 -08003009bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003010 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003011 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003012 if (!useCachedExpectedPresentTime)
3013 populateExpectedPresentTime();
3014
3015 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003016 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3017 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3018 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3019 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3020 return false;
3021 }
3022
Marissa Wall713b63f2018-10-17 15:42:43 -07003023 for (const ComposerState& state : states) {
3024 const layer_state_t& s = state.state;
3025 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3026 continue;
3027 }
3028 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003029 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003030 }
3031 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003032 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003033}
3034
Valerie Hau9dab9732019-08-20 09:29:25 -07003035void SurfaceFlinger::setTransactionState(
3036 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3037 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3038 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3039 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003040 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003041
Valerie Haubc6ddb12019-03-08 11:10:15 -08003042 const int64_t postTime = systemTime();
3043
Robert Carr14167e02019-02-13 13:50:55 -08003044 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3045
Mathias Agopian698c0872011-06-28 19:09:31 -07003046 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003047
Marissa Wall713b63f2018-10-17 15:42:43 -07003048 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003049 auto itr = mTransactionQueues.find(applyToken);
3050 // if this is an animation frame, wait until prior animation frame has
3051 // been applied by SF
3052 if (flags & eAnimation) {
3053 while (itr != mTransactionQueues.end()) {
3054 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3055 if (CC_UNLIKELY(err != NO_ERROR)) {
3056 ALOGW_IF(err == TIMED_OUT,
3057 "setTransactionState timed out "
3058 "waiting for animation frame to apply");
3059 break;
3060 }
3061 itr = mTransactionQueues.find(applyToken);
3062 }
3063 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003064
3065 // Expected present time is computed and cached on invalidate, so it may be stale.
3066 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3067 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003068 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003069 uncacheBuffer, postTime, privileged,
3070 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003071 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003072 return;
3073 }
3074
Valerie Haubc6ddb12019-03-08 11:10:15 -08003075 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003076 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3077 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003078}
3079
Valerie Hau9dab9732019-08-20 09:29:25 -07003080void SurfaceFlinger::applyTransactionState(
3081 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3082 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3083 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3084 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3085 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003086 uint32_t transactionFlags = 0;
3087
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003088 if (flags & eAnimation) {
3089 // For window updates that are part of an animation we must wait for
3090 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003091 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003092 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003093 if (CC_UNLIKELY(err != NO_ERROR)) {
3094 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003095 // caller after a few seconds.
3096 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3097 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003098 mAnimTransactionPending = false;
3099 break;
3100 }
3101 }
3102 }
3103
chaviwca27f252018-02-06 16:46:39 -08003104 for (const DisplayState& display : displays) {
3105 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003106 }
3107
Valerie Hau9dab9732019-08-20 09:29:25 -07003108 // start and end registration for listeners w/ no surface so they can get their callback. Note
3109 // that listeners with SurfaceControls will start registration during setClientStateLocked
3110 // below.
3111 for (const auto& listener : listenerCallbacks) {
3112 mTransactionCompletedThread.startRegistration(listener);
3113 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003114 }
3115
Valerie Hau9dab9732019-08-20 09:29:25 -07003116 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003117 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003118 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003119 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3120 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003121 }
3122
Valerie Hau9dab9732019-08-20 09:29:25 -07003123 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003124 mTransactionCompletedThread.endRegistration(listenerCallback);
3125 }
3126
Marissa Walle2ffb422018-10-12 11:33:52 -07003127 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003128 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003129 mTransactionCompletedThread.sendCallbacks();
3130 }
3131 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003132
chaviw273171b2018-12-26 11:46:30 -08003133 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3134
Marissa Wall947d34e2019-03-29 14:03:53 -07003135 if (uncacheBuffer.isValid()) {
3136 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003137 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003138 }
3139
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003140 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3141 // anyway. This can be used as a flush mechanism for previous async transactions.
3142 // Empty animation transaction can be used to simulate back-pressure, so also force a
3143 // transaction for empty animation transactions.
3144 if (transactionFlags == 0 &&
3145 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003146 transactionFlags = eTransactionNeeded;
3147 }
3148
Marissa Wall06255332019-03-27 13:48:27 -07003149 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3150 // so we don't have to wake up again next frame to preform an uneeded traversal.
3151 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3152 transactionFlags = transactionFlags & (~eTraversalNeeded);
3153 mTraversalNeededMainThread = true;
3154 }
3155
Mathias Agopian386aa982011-11-07 21:58:03 -08003156 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003157 if (mInterceptor->isEnabled()) {
3158 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003159 }
Irvel468051e2016-06-13 16:44:44 -07003160
Mathias Agopian386aa982011-11-07 21:58:03 -08003161 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003162 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3163 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003164 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003165
3166 // if this is a synchronous transaction, wait for it to take effect
3167 // before returning.
3168 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003169 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003170 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003171 if (flags & eAnimation) {
3172 mAnimTransactionPending = true;
3173 }
chaviw4fe36852019-04-15 16:25:49 -07003174 if (mPendingInputWindowCommands.syncInputWindows) {
3175 mPendingSyncInputWindows = true;
3176 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003177
3178 // applyTransactionState can be called by either the main SF thread or by
3179 // another process through setTransactionState. While a given process may wish
3180 // to wait on synchronous transactions, the main SF thread should never
3181 // be blocked. Therefore, we only wait if isMainThread is false.
3182 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003183 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3184 if (CC_UNLIKELY(err != NO_ERROR)) {
3185 // just in case something goes wrong in SF, return to the
3186 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003187 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3188 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003189 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003190 break;
3191 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003192 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003193 }
3194}
3195
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003196uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3197 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3198 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003199
Mathias Agopiane57f2922012-08-09 16:29:12 -07003200 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003201 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3202
3203 const uint32_t what = s.what;
3204 if (what & DisplayState::eSurfaceChanged) {
3205 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3206 state.surface = s.surface;
3207 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003208 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003209 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003210 if (what & DisplayState::eLayerStackChanged) {
3211 if (state.layerStack != s.layerStack) {
3212 state.layerStack = s.layerStack;
3213 flags |= eDisplayTransactionNeeded;
3214 }
3215 }
3216 if (what & DisplayState::eDisplayProjectionChanged) {
3217 if (state.orientation != s.orientation) {
3218 state.orientation = s.orientation;
3219 flags |= eDisplayTransactionNeeded;
3220 }
3221 if (state.frame != s.frame) {
3222 state.frame = s.frame;
3223 flags |= eDisplayTransactionNeeded;
3224 }
3225 if (state.viewport != s.viewport) {
3226 state.viewport = s.viewport;
3227 flags |= eDisplayTransactionNeeded;
3228 }
3229 }
3230 if (what & DisplayState::eDisplaySizeChanged) {
3231 if (state.width != s.width) {
3232 state.width = s.width;
3233 flags |= eDisplayTransactionNeeded;
3234 }
3235 if (state.height != s.height) {
3236 state.height = s.height;
3237 flags |= eDisplayTransactionNeeded;
3238 }
3239 }
3240
Mathias Agopiane57f2922012-08-09 16:29:12 -07003241 return flags;
3242}
3243
Robert Carr14167e02019-02-13 13:50:55 -08003244bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003245 IPCThreadState* ipc = IPCThreadState::self();
3246 const int pid = ipc->getCallingPid();
3247 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003248 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003249 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003250 return false;
3251 }
3252 return true;
3253}
3254
Marissa Wall3dad52d2019-03-22 14:03:19 -07003255uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003256 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3257 bool privileged,
3258 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003259 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003260
Valerie Hau9dab9732019-08-20 09:29:25 -07003261 for (auto& listener : s.listeners) {
3262 // note that startRegistration will not re-register if the listener has
3263 // already be registered for a prior surface control
3264 mTransactionCompletedThread.startRegistration(listener);
3265 listenerCallbacks.insert(listener);
3266 }
3267
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003268 sp<Layer> layer = nullptr;
3269 if (s.surface) {
3270 layer = fromHandle(s.surface);
3271 } else {
3272 // The client may provide us a null handle. Treat it as if the layer was removed.
3273 ALOGW("Attempt to set client state with a null layer handle");
3274 }
chaviw8b3871a2017-11-01 17:41:01 -07003275 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003276 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003277 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003278 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003279 }
chaviw8b3871a2017-11-01 17:41:01 -07003280 return 0;
3281 }
3282
chaviw8b3871a2017-11-01 17:41:01 -07003283 uint32_t flags = 0;
3284
Garfield Tan8a3083e2018-12-03 13:21:07 -08003285 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003286
3287 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3288 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003289 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003290 layer->pushPendingState();
3291 }
3292
chaviw8b3871a2017-11-01 17:41:01 -07003293 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003294 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003295 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003296 }
chaviw8b3871a2017-11-01 17:41:01 -07003297 }
3298 if (what & layer_state_t::eLayerChanged) {
3299 // NOTE: index needs to be calculated before we update the state
3300 const auto& p = layer->getParent();
3301 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003302 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003303 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003304 mCurrentState.layersSortedByZ.removeAt(idx);
3305 mCurrentState.layersSortedByZ.add(layer);
3306 // we need traversal (state changed)
3307 // AND transaction (list changed)
3308 flags |= eTransactionNeeded|eTraversalNeeded;
3309 }
chaviw8b3871a2017-11-01 17:41:01 -07003310 } else {
3311 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003312 flags |= eTransactionNeeded|eTraversalNeeded;
3313 }
3314 }
chaviw8b3871a2017-11-01 17:41:01 -07003315 }
3316 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003317 // NOTE: index needs to be calculated before we update the state
3318 const auto& p = layer->getParent();
3319 if (p == nullptr) {
3320 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3321 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3322 mCurrentState.layersSortedByZ.removeAt(idx);
3323 mCurrentState.layersSortedByZ.add(layer);
3324 // we need traversal (state changed)
3325 // AND transaction (list changed)
3326 flags |= eTransactionNeeded|eTraversalNeeded;
3327 }
3328 } else {
3329 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3330 flags |= eTransactionNeeded|eTraversalNeeded;
3331 }
chaviw8b3871a2017-11-01 17:41:01 -07003332 }
3333 }
3334 if (what & layer_state_t::eSizeChanged) {
3335 if (layer->setSize(s.w, s.h)) {
3336 flags |= eTraversalNeeded;
3337 }
3338 }
3339 if (what & layer_state_t::eAlphaChanged) {
3340 if (layer->setAlpha(s.alpha))
3341 flags |= eTraversalNeeded;
3342 }
3343 if (what & layer_state_t::eColorChanged) {
3344 if (layer->setColor(s.color))
3345 flags |= eTraversalNeeded;
3346 }
Peiyong Lind3788632018-09-18 16:01:31 -07003347 if (what & layer_state_t::eColorTransformChanged) {
3348 if (layer->setColorTransform(s.colorTransform)) {
3349 flags |= eTraversalNeeded;
3350 }
3351 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003352 if (what & layer_state_t::eBackgroundColorChanged) {
3353 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3354 flags |= eTraversalNeeded;
3355 }
3356 }
chaviw8b3871a2017-11-01 17:41:01 -07003357 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003358 // TODO: b/109894387
3359 //
3360 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3361 // rotation. To see the problem observe that if we have a square parent, and a child
3362 // of the same size, then we rotate the child 45 degrees around it's center, the child
3363 // must now be cropped to a non rectangular 8 sided region.
3364 //
3365 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3366 // private API, and the WindowManager only uses rotation in one case, which is on a top
3367 // level layer in which cropping is not an issue.
3368 //
3369 // However given that abuse of rotation matrices could lead to surfaces extending outside
3370 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3371 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3372 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003373 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003374 flags |= eTraversalNeeded;
3375 }
3376 if (what & layer_state_t::eTransparentRegionChanged) {
3377 if (layer->setTransparentRegionHint(s.transparentRegion))
3378 flags |= eTraversalNeeded;
3379 }
3380 if (what & layer_state_t::eFlagsChanged) {
3381 if (layer->setFlags(s.flags, s.mask))
3382 flags |= eTraversalNeeded;
3383 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003384 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003385 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003386 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003387 if (what & layer_state_t::eCornerRadiusChanged) {
3388 if (layer->setCornerRadius(s.cornerRadius))
3389 flags |= eTraversalNeeded;
3390 }
Lucas Dupin19c8f0e2019-11-25 17:55:44 -08003391 if (what & layer_state_t::eBackgroundBlurRadiusChanged) {
3392 if (layer->setBackgroundBlurRadius(s.backgroundBlurRadius)) flags |= eTraversalNeeded;
3393 }
chaviw8b3871a2017-11-01 17:41:01 -07003394 if (what & layer_state_t::eLayerStackChanged) {
3395 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3396 // We only allow setting layer stacks for top level layers,
3397 // everything else inherits layer stack from its parent.
3398 if (layer->hasParent()) {
3399 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003400 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003401 } else if (idx < 0) {
3402 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003403 "that also does not appear in the top level layer list. Something"
3404 " has gone wrong.",
3405 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003406 } else if (layer->setLayerStack(s.layerStack)) {
3407 mCurrentState.layersSortedByZ.removeAt(idx);
3408 mCurrentState.layersSortedByZ.add(layer);
3409 // we need traversal (state changed)
3410 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003411 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003412 }
3413 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003414 if (what & layer_state_t::eDeferTransaction_legacy) {
3415 if (s.barrierHandle_legacy != nullptr) {
3416 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3417 } else if (s.barrierGbp_legacy != nullptr) {
3418 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003419 if (authenticateSurfaceTextureLocked(gbp)) {
3420 const auto& otherLayer =
3421 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003422 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003423 } else {
3424 ALOGE("Attempt to defer transaction to to an"
3425 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003426 }
3427 }
chaviw8b3871a2017-11-01 17:41:01 -07003428 // We don't trigger a traversal here because if no other state is
3429 // changed, we don't want this to cause any more work
3430 }
chaviw8b3871a2017-11-01 17:41:01 -07003431 if (what & layer_state_t::eReparentChildren) {
3432 if (layer->reparentChildren(s.reparentHandle)) {
3433 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003434 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003435 }
chaviw8b3871a2017-11-01 17:41:01 -07003436 if (what & layer_state_t::eDetachChildren) {
3437 layer->detachChildren();
3438 }
3439 if (what & layer_state_t::eOverrideScalingModeChanged) {
3440 layer->setOverrideScalingMode(s.overrideScalingMode);
3441 // We don't trigger a traversal here because if no other state is
3442 // changed, we don't want this to cause any more work
3443 }
Marissa Wall61c58622018-07-18 10:12:20 -07003444 if (what & layer_state_t::eTransformChanged) {
3445 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3446 }
3447 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3448 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3449 flags |= eTraversalNeeded;
3450 }
3451 if (what & layer_state_t::eCropChanged) {
3452 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3453 }
Marissa Wall861616d2018-10-22 12:52:23 -07003454 if (what & layer_state_t::eFrameChanged) {
3455 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3456 }
Marissa Wall61c58622018-07-18 10:12:20 -07003457 if (what & layer_state_t::eAcquireFenceChanged) {
3458 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3459 }
3460 if (what & layer_state_t::eDataspaceChanged) {
3461 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3462 }
3463 if (what & layer_state_t::eHdrMetadataChanged) {
3464 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3465 }
3466 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3467 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3468 }
3469 if (what & layer_state_t::eApiChanged) {
3470 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3471 }
3472 if (what & layer_state_t::eSidebandStreamChanged) {
3473 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3474 }
Robert Carr720e5062018-07-30 17:45:14 -07003475 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003476 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003477 layer->setInputInfo(s.inputInfo);
3478 flags |= eTraversalNeeded;
3479 } else {
3480 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3481 }
Robert Carr720e5062018-07-30 17:45:14 -07003482 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003483 if (what & layer_state_t::eMetadataChanged) {
3484 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3485 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003486 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3487 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3488 flags |= eTraversalNeeded;
3489 }
3490 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003491 if (what & layer_state_t::eShadowRadiusChanged) {
3492 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3493 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003494 if (what & layer_state_t::eFrameRateSelectionPriority) {
3495 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3496 flags |= eTraversalNeeded;
3497 }
3498 }
Steven Thomas3172e202020-01-06 19:25:30 -08003499 if (what & layer_state_t::eFrameRateChanged) {
3500 if (layer->setFrameRate(s.frameRate)) flags |= eTraversalNeeded;
3501 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003502 // This has to happen after we reparent children because when we reparent to null we remove
3503 // child layers from current state and remove its relative z. If the children are reparented in
3504 // the same transaction, then we have to make sure we reparent the children first so we do not
3505 // lose its relative z order.
3506 if (what & layer_state_t::eReparent) {
3507 bool hadParent = layer->hasParent();
3508 if (layer->reparent(s.parentHandleForChild)) {
3509 if (!hadParent) {
3510 mCurrentState.layersSortedByZ.remove(layer);
3511 }
3512 flags |= eTransactionNeeded | eTraversalNeeded;
3513 }
3514 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003515 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003516 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3517 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003518 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3519 }
3520 }
Marissa Wall78b72202019-03-15 14:58:34 -07003521 bool bufferChanged = what & layer_state_t::eBufferChanged;
3522 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3523 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003524 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003525 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003526 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3527 if (success) {
3528 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3529 success = ClientCache::getInstance()
3530 .registerErasedRecipient(s.cachedBuffer,
3531 wp<ClientCache::ErasedRecipient>(this));
3532 if (!success) {
3533 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3534 }
3535 }
Marissa Wall78b72202019-03-15 14:58:34 -07003536 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003537 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003538 } else if (bufferChanged) {
3539 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003540 }
Marissa Wall78b72202019-03-15 14:58:34 -07003541 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003542 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003543 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003544 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003545 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003546 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3547 // Do not put anything that updates layer state or modifies flags after
3548 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003549 return flags;
3550}
3551
chaviw273171b2018-12-26 11:46:30 -08003552uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3553 uint32_t flags = 0;
3554 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3555 flags |= eTraversalNeeded;
3556 }
3557
chaviwa911b102019-02-14 10:18:33 -08003558 if (inputWindowCommands.syncInputWindows) {
3559 flags |= eTraversalNeeded;
3560 }
3561
Vishnu Nairec0ab382019-02-13 15:32:56 -08003562 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003563 return flags;
3564}
3565
chaviwfe94a222019-08-21 13:52:59 -07003566status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3567 sp<IBinder>* outHandle) {
3568 if (!mirrorFromHandle) {
3569 return NAME_NOT_FOUND;
3570 }
3571
3572 sp<Layer> mirrorLayer;
3573 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003574 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003575
3576 {
3577 Mutex::Autolock _l(mStateLock);
3578 mirrorFrom = fromHandle(mirrorFromHandle);
3579 if (!mirrorFrom) {
3580 return NAME_NOT_FOUND;
3581 }
3582
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003583 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3584 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003585 if (result != NO_ERROR) {
3586 return result;
3587 }
3588
3589 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3590 }
3591
3592 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3593}
3594
Marissa Wall2d814fb2019-04-09 18:52:57 +00003595status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3596 uint32_t h, PixelFormat format, uint32_t flags,
3597 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003598 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003599 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3600 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003601 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003602 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003603 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003604 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003605 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003606
Robert Carrc0df3122019-04-11 13:18:21 -07003607 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3608 "Expected only one of parentLayer or parentHandle to be non-null. "
3609 "Programmer error?");
3610
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003611 status_t result = NO_ERROR;
3612
3613 sp<Layer> layer;
3614
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003615 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003616
Evan Roskya1f1e152019-01-24 16:17:46 -08003617 bool primaryDisplayOnly = false;
3618
3619 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3620 // TODO b/64227542
3621 if (metadata.has(METADATA_WINDOW_TYPE)) {
3622 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3623 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003624 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003625 primaryDisplayOnly = true;
3626 }
3627 }
3628
Mathias Agopian3165cc22012-08-08 19:42:09 -07003629 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003630 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003631 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3632 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003633
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003634 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003635 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003636 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003637 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003638 break;
chaviw13fdc492017-06-27 12:40:18 -07003639 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003640 // check if buffer size is set for color layer.
3641 if (w > 0 || h > 0) {
3642 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3643 int(w), int(h));
3644 return BAD_VALUE;
3645 }
3646
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003647 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3648 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003649 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003650 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003651 // check if buffer size is set for container layer.
3652 if (w > 0 || h > 0) {
3653 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3654 int(w), int(h));
3655 return BAD_VALUE;
3656 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003657 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3658 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003659 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003660 default:
3661 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003662 break;
3663 }
3664
Dan Stoza7d89d062015-04-30 13:29:25 -07003665 if (result != NO_ERROR) {
3666 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003667 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003668
Evan Roskya1f1e152019-01-24 16:17:46 -08003669 if (primaryDisplayOnly) {
3670 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003671 }
3672
Robert Carrb89ea9d2018-12-10 13:01:14 -08003673 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003674 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3675 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003676 if (result != NO_ERROR) {
3677 return result;
3678 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003679 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003680
3681 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003682 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003683}
3684
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003685std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3686 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003687
3688 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003689 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003690
Dan Stoza436ccf32018-06-21 12:10:12 -07003691 // Grab the state lock since we're accessing mCurrentState
3692 Mutex::Autolock lock(mStateLock);
3693
Cody Northropbc755282017-03-31 12:00:08 -06003694 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003695 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003696 while (matchFound) {
3697 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003698 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003699 if (layer->getName() == uniqueName) {
3700 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003701 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003702 }
3703 });
3704 }
3705
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003706 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003707 return uniqueName;
3708}
3709
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003710status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003711 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003712 LayerMetadata metadata, PixelFormat& format,
3713 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003714 sp<IGraphicBufferProducer>* gbp,
3715 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003716 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003717 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003718 case PIXEL_FORMAT_TRANSPARENT:
3719 case PIXEL_FORMAT_TRANSLUCENT:
3720 format = PIXEL_FORMAT_RGBA_8888;
3721 break;
3722 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003723 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003724 break;
3725 }
3726
chaviwb4c6e582019-08-16 14:35:07 -07003727 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003728 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003729 args.textureName = getNewTexture();
3730 {
3731 // Grab the SF state lock during this since it's the only safe way to access
3732 // RenderEngine when creating a BufferLayerConsumer
3733 // TODO: Check if this lock is still needed here
3734 Mutex::Autolock lock(mStateLock);
3735 layer = getFactory().createBufferQueueLayer(args);
3736 }
3737
Marissa Wallfd668622018-05-10 10:21:13 -07003738 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003739 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003740 *handle = layer->getHandle();
3741 *gbp = layer->getProducer();
3742 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003743 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003744
Marissa Wallfd668622018-05-10 10:21:13 -07003745 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003746 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003747}
3748
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003749status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003750 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003751 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003752 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003753 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003754 args.displayDevice = getDefaultDisplayDevice();
3755 args.textureName = getNewTexture();
3756 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003757 if (outTransformHint) {
3758 *outTransformHint = layer->getTransformHint();
3759 }
Marissa Wall61c58622018-07-18 10:12:20 -07003760 *handle = layer->getHandle();
3761 *outLayer = layer;
3762
3763 return NO_ERROR;
3764}
3765
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003766status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003767 uint32_t h, uint32_t flags, LayerMetadata metadata,
3768 sp<IBinder>* handle, sp<Layer>* outLayer) {
3769 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003770 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003771 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003772 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003773}
3774
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003775status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003776 uint32_t w, uint32_t h, uint32_t flags,
3777 LayerMetadata metadata, sp<IBinder>* handle,
3778 sp<Layer>* outLayer) {
3779 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003780 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003781 *handle = (*outLayer)->getHandle();
3782 return NO_ERROR;
3783}
3784
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003785void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003786 mLayersPendingRemoval.add(layer);
3787 mLayersRemoved = true;
3788 setTransactionFlags(eTransactionNeeded);
3789}
3790
Robert Carr695d5282018-12-18 15:27:58 -08003791void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003792{
Robert Carr2e102c92018-10-23 12:11:15 -07003793 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003794 // If a layer has a parent, we allow it to out-live it's handle
3795 // with the idea that the parent holds a reference and will eventually
3796 // be cleaned up. However no one cleans up the top-level so we do so
3797 // here.
3798 if (layer->getParent() == nullptr) {
3799 mCurrentState.layersSortedByZ.remove(layer);
3800 }
3801 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003802
3803 auto it = mLayersByLocalBinderToken.begin();
3804 while (it != mLayersByLocalBinderToken.end()) {
3805 if (it->second == layer) {
3806 it = mLayersByLocalBinderToken.erase(it);
3807 } else {
3808 it++;
3809 }
3810 }
3811
Robert Carr695d5282018-12-18 15:27:58 -08003812 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003813}
3814
Mathias Agopianb60314a2012-04-10 22:09:54 -07003815// ---------------------------------------------------------------------------
3816
Andy McFadden13a082e2012-08-24 10:16:42 -07003817void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003818 const auto display = getDefaultDisplayDeviceLocked();
3819 if (!display) return;
3820
3821 const sp<IBinder> token = display->getDisplayToken().promote();
3822 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003823
Jesse Hall01e29052013-02-19 16:13:35 -08003824 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003825 Vector<ComposerState> state;
3826 Vector<DisplayState> displays;
3827 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003828 d.what = DisplayState::eDisplayProjectionChanged |
3829 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003830 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003831 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003832 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003833 d.frame.makeInvalid();
3834 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003835 d.width = 0;
3836 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003837 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003838 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3839 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003840
Dominik Laskowskie9774092018-12-11 10:04:24 -08003841 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003842
Dominik Laskowski83b88212018-12-11 13:34:06 -08003843 const nsecs_t vsyncPeriod = getVsyncPeriod();
3844 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003845
Brian Andersond0010582017-03-07 13:20:31 -08003846 // Use phase of 0 since phase is not known.
3847 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003848 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003849 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003850}
3851
3852void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003853 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003854 postMessageAsync(
3855 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003856}
3857
Ady Abraham27c70212019-06-11 10:52:26 -07003858void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3859 if (mHWCVsyncState != enabled) {
3860 getHwComposer().setVsyncEnabled(displayId, enabled);
3861 mHWCVsyncState = enabled;
3862 }
3863}
3864
Dominik Laskowskie9774092018-12-11 10:04:24 -08003865void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003866 if (display->isVirtual()) {
3867 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003868 return;
3869 }
3870
Dominik Laskowski075d3172018-05-24 15:50:06 -07003871 const auto displayId = display->getId();
3872 LOG_ALWAYS_FATAL_IF(!displayId);
3873
Dominik Laskowski34157762018-10-31 13:07:19 -07003874 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003875
3876 int currentMode = display->getPowerMode();
3877 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003878 return;
3879 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003880
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003881 display->setPowerMode(mode);
3882
Lloyd Pique4dccc412018-01-22 17:21:36 -08003883 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003884 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003885 }
3886
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003887 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003888 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003889 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003890 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003891 mScheduler->onScreenAcquired(mAppConnectionHandle);
3892 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003893 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003894
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003895 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003896 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003897 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003898
3899 struct sched_param param = {0};
3900 param.sched_priority = 1;
3901 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3902 ALOGW("Couldn't set SCHED_FIFO on display on");
3903 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003904 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003905 // Turn off the display
3906 struct sched_param param = {0};
3907 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3908 ALOGW("Couldn't set SCHED_OTHER on display off");
3909 }
3910
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003911 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003912 mScheduler->disableHardwareVsync(true);
3913 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003914 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003915
Ady Abraham27c70212019-06-11 10:52:26 -07003916 // Make sure HWVsync is disabled before turning off the display
3917 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3918
Dominik Laskowski075d3172018-05-24 15:50:06 -07003919 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003920 mVisibleRegionsDirty = true;
3921 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003922 } else if (mode == HWC_POWER_MODE_DOZE ||
3923 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003924 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003925 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003926 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003927 mScheduler->onScreenAcquired(mAppConnectionHandle);
3928 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003929 }
3930 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3931 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003932 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003933 mScheduler->disableHardwareVsync(true);
3934 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003935 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003936 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003937 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003938 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003939 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003940 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003941
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003942 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003943 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003944 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003945 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003946 }
3947
Dominik Laskowski34157762018-10-31 13:07:19 -07003948 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003949}
3950
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003951void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003952 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003953 const auto display = getDisplayDevice(displayToken);
3954 if (!display) {
3955 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3956 displayToken.get());
3957 } else if (display->isVirtual()) {
3958 ALOGW("Attempt to set power mode %d for virtual display", mode);
3959 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003960 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003961 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003962 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003963}
3964
3965// ---------------------------------------------------------------------------
3966
Dominik Laskowskic2867142019-01-21 11:33:38 -08003967status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3968 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003969 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003970
Mathias Agopianbd115332013-04-18 16:41:04 -07003971 IPCThreadState* ipc = IPCThreadState::self();
3972 const int pid = ipc->getCallingPid();
3973 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003974
Mathias Agopianbd115332013-04-18 16:41:04 -07003975 if ((uid != AID_SHELL) &&
3976 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003977 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3978 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003979 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003980 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003981 // (this would indicate SF is stuck, but we want to be able to
3982 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003983 status_t err = mStateLock.timedLock(s2ns(1));
3984 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003985 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003986 StringAppendF(&result,
3987 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3988 "(no locks held)\n",
3989 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003990 }
3991
Dominik Laskowskic2867142019-01-21 11:33:38 -08003992 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003993 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003994 {"--dispsync"s,
3995 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003996 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003997 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3998 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3999 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
4000 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
4001 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
4002 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004003 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08004004 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
4005 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004006
Dominik Laskowskic2867142019-01-21 11:33:38 -08004007 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004008
Dominik Laskowski46470112019-08-02 13:13:11 -07004009 const auto it = dumpers.find(flag);
4010 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004011 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004012 } else if (!asProto) {
4013 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004014 }
4015
Mathias Agopian9795c422009-08-26 16:36:26 -07004016 if (locked) {
4017 mStateLock.unlock();
4018 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004019
Dominik Laskowski46470112019-08-02 13:13:11 -07004020 if (it == dumpers.end()) {
4021 const LayersProto layersProto = dumpProtoFromMainThread();
4022 if (asProto) {
4023 result.append(layersProto.SerializeAsString());
4024 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004025 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004026 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4027 result.append(LayerProtoParser::layerTreeToString(layerTree));
4028 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004029 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004030 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004031 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004032 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004033 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004034 return NO_ERROR;
4035}
4036
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004037status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4038 if (asProto && mTracing.isEnabled()) {
4039 mTracing.writeToFileAsync();
4040 }
4041
4042 return doDump(fd, DumpArgs(), asProto);
4043}
4044
Dominik Laskowskic2867142019-01-21 11:33:38 -08004045void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004046 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004047 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004048}
4049
Dominik Laskowskic2867142019-01-21 11:33:38 -08004050void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004051 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004052
Dominik Laskowskic2867142019-01-21 11:33:38 -08004053 if (args.size() > 1) {
4054 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004055 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004056 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004057 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004058 }
Robert Carr2047fae2016-11-28 14:09:09 -08004059 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004060 } else {
4061 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004062 }
4063}
4064
Dominik Laskowskic2867142019-01-21 11:33:38 -08004065void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004066 const bool clearAll = args.size() < 2;
4067 const auto name = clearAll ? String8() : String8(args[1]);
4068
Robert Carr2047fae2016-11-28 14:09:09 -08004069 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004070 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004071 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004072 }
Robert Carr2047fae2016-11-28 14:09:09 -08004073 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004074
Svetoslavd85084b2014-03-20 10:28:31 -07004075 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004076}
4077
Dominik Laskowskic2867142019-01-21 11:33:38 -08004078void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4079 mTimeStats->parseArgs(asProto, args, result);
4080}
4081
Jamie Gennis6547ff42013-07-16 20:12:42 -07004082// This should only be called from the main thread. Otherwise it would need
4083// the lock and should use mCurrentState rather than mDrawingState.
4084void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004085 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004086 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004087 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004088
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004089 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004090}
4091
Yiwei Zhang5434a782018-12-05 18:06:32 -08004092void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004093 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004094
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004095 if (isLayerTripleBufferingDisabled())
4096 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004097
Yiwei Zhang5434a782018-12-05 18:06:32 -08004098 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4099 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4100 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4101 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4102 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4103 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004104 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004105}
4106
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004107void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004108 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004109
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004110 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004111 result.append("\n");
4112
Ady Abraham9e16a482019-12-03 17:19:41 -08004113 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004114 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004115 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004116 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004117
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004118 HwcConfigIndexType defaultConfig;
4119 float minFps, maxFps;
4120 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004121 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004122 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004123 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004124 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004125 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4126 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004127
Ana Krulecc2870422019-01-29 19:00:58 -08004128 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004129}
4130
Yiwei Zhang5434a782018-12-05 18:06:32 -08004131void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4132 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004133 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4134 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004135 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004136 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004137 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004138 }
David Sodman4a36e932017-11-07 14:29:47 -08004139 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004140 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004141 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004142 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4143 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004144}
4145
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004146void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4147 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004148 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4149 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004150 for (const auto& segment : history) {
4151 if (!segment.usedThirdBuffer) {
4152 stats.twoBufferTime += segment.totalTime;
4153 }
4154 if (segment.occupancyAverage < 1.0f) {
4155 stats.doubleBufferedTime += segment.totalTime;
4156 } else if (segment.occupancyAverage < 2.0f) {
4157 stats.tripleBufferedTime += segment.totalTime;
4158 }
4159 ++stats.numSegments;
4160 stats.totalTime += segment.totalTime;
4161 }
4162}
4163
Yiwei Zhang5434a782018-12-05 18:06:32 -08004164void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4165 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004166
4167 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4168 const size_t count = currentLayers.size();
4169 for (size_t i=0 ; i<count ; i++) {
4170 currentLayers[i]->dumpFrameEvents(result);
4171 }
4172}
4173
Yiwei Zhang5434a782018-12-05 18:06:32 -08004174void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004175 result.append("Buffering stats:\n");
4176 result.append(" [Layer name] <Active time> <Two buffer> "
4177 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004178 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004179 typedef std::tuple<std::string, float, float, float> BufferTuple;
4180 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004181 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004182 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004183 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004184 if (stats.numSegments == 0) {
4185 continue;
4186 }
4187 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4188 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4189 stats.totalTime;
4190 float doubleBufferRatio = static_cast<float>(
4191 stats.doubleBufferedTime) / stats.totalTime;
4192 float tripleBufferRatio = static_cast<float>(
4193 stats.tripleBufferedTime) / stats.totalTime;
4194 sorted.insert({activeTime, {name, twoBufferRatio,
4195 doubleBufferRatio, tripleBufferRatio}});
4196 }
4197 for (const auto& sortedPair : sorted) {
4198 float activeTime = sortedPair.first;
4199 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004200 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4201 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004202 }
4203 result.append("\n");
4204}
4205
Yiwei Zhang5434a782018-12-05 18:06:32 -08004206void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004207 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004208 const auto displayId = display->getId();
4209 if (!displayId) {
4210 continue;
4211 }
4212 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004213 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004214 continue;
4215 }
4216
Yiwei Zhang5434a782018-12-05 18:06:32 -08004217 StringAppendF(&result,
4218 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4219 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004220 uint8_t port;
4221 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004222 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004223 result.append("no identification data\n");
4224 continue;
4225 }
4226
4227 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004228 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004229 continue;
4230 }
4231
4232 const auto edid = parseEdid(data);
4233 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004234 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004235 continue;
4236 }
4237
Yiwei Zhang5434a782018-12-05 18:06:32 -08004238 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004239 result.append(edid->displayName.data(), edid->displayName.length());
4240 result.append("\"\n");
4241 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004242}
4243
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004244void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4245 std::string& result) const {
4246 hwc2_display_t hwcDisplayId;
4247 uint8_t port;
4248 DisplayIdentificationData data;
4249
4250 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4251 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4252 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4253 }
4254}
4255
Yiwei Zhang5434a782018-12-05 18:06:32 -08004256void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004257 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004258 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4259 StringAppendF(&result, "DisplayColorSetting: %s\n",
4260 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004261
4262 // TODO: print out if wide-color mode is active or not
4263
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004264 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004265 const auto displayId = display->getId();
4266 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004267 continue;
4268 }
4269
Yiwei Zhang5434a782018-12-05 18:06:32 -08004270 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004271 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004272 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004273 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004274 }
4275
Lloyd Pique32cbe282018-10-19 13:09:22 -07004276 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004277 StringAppendF(&result, " Current color mode: %s (%d)\n",
4278 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004279 }
4280 result.append("\n");
4281}
4282
Vishnu Nair8406fd72019-07-30 11:29:31 -07004283LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004284 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004285 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4286 layer->writeToProto(layersProto, traceFlags);
4287 }
chaviw1d044282017-09-27 12:19:28 -07004288 return layersProto;
4289}
4290
Vishnu Nair0f085c62019-08-30 08:49:12 -07004291void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4292 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4293 // it.
4294 LayerProto* rootProto = layersProto.add_layers();
4295 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4296 rootProto->set_id(offscreenRootLayerId);
4297 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004298 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004299
4300 for (Layer* offscreenLayer : mOffscreenLayers) {
4301 // Add layer as child of the fake root
4302 rootProto->add_children(offscreenLayer->sequence);
4303
4304 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004305 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004306 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004307 }
4308}
4309
Vishnu Nair8406fd72019-07-30 11:29:31 -07004310LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4311 LayersProto layersProto;
4312 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4313 return layersProto;
4314}
4315
Vishnu Nair0f085c62019-08-30 08:49:12 -07004316void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4317 result.append("Offscreen Layers:\n");
4318 postMessageSync(new LambdaMessage([&]() {
4319 for (Layer* offscreenLayer : mOffscreenLayers) {
4320 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4321 layer->dumpCallingUidPid(result);
4322 });
4323 }
4324 }));
4325}
4326
Dominik Laskowskic2867142019-01-21 11:33:38 -08004327void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4328 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004329 Colorizer colorizer(colorize);
4330
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004331 // figure out if we're stuck somewhere
4332 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004334 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4335
4336 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004337 * Dump library configuration.
4338 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004339
4340 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004341 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004342 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004343 appendSfConfigString(result);
4344 appendUiConfigString(result);
4345 appendGuiConfigString(result);
4346 result.append("\n");
4347
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004348 result.append("\nDisplay identification data:\n");
4349 dumpDisplayIdentificationData(result);
4350
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004351 result.append("\nWide-Color information:\n");
4352 dumpWideColorInfo(result);
4353
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004354 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004355 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004356 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004357 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004358 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004359
Andy McFadden41d67d72014-04-25 16:58:34 -07004360 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004361 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004362 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004363 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004364 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004365
Dan Stozab90cf072015-03-05 11:05:59 -08004366 dumpStaticScreenStats(result);
4367 result.append("\n");
4368
Alec Mouri40189b02019-03-05 15:07:54 -08004369 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4370 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4371 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004372
Dan Stozae77c7662016-05-13 11:37:28 -07004373 dumpBufferingStats(result);
4374
Andy McFadden4803b742012-09-24 19:07:20 -07004375 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004376 * Dump the visible layer list
4377 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004378 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004379 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004380 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4381 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004382 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004383
Chia-I Wu2f884132018-09-13 15:17:58 -07004384 {
Lloyd Pique207def92019-02-28 16:09:52 -08004385 StringAppendF(&result, "Composition layers\n");
4386 mDrawingState.traverseInZOrder([&](Layer* layer) {
4387 auto compositionLayer = layer->getCompositionLayer();
4388 if (compositionLayer) compositionLayer->dump(result);
4389 });
4390 }
4391
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004392 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004393 * Dump Display state
4394 */
4395
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004396 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004397 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004398 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004399 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004400 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004401 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004402 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004403
4404 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004405 * Dump CompositionEngine state
4406 */
4407
4408 mCompositionEngine->dump(result);
4409
4410 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004411 * Dump SurfaceFlinger global state
4412 */
4413
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004414 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004415 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004416 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004417
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004418 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004419
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004420 DebugEGLImageTracker::getInstance()->dump(result);
4421
Dominik Laskowski075d3172018-05-24 15:50:06 -07004422 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004423 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4424 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004425 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4426 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004427 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004428 StringAppendF(&result,
4429 " transaction-flags : %08x\n"
4430 " gpu_to_cpu_unsupported : %d\n",
4431 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004432
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004433 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004434 displayId && getHwComposer().isConnected(*displayId)) {
4435 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004436 StringAppendF(&result,
4437 " refresh-rate : %f fps\n"
4438 " x-dpi : %f\n"
4439 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004440 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4441 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004442 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004443
Yiwei Zhang5434a782018-12-05 18:06:32 -08004444 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004445
Dan Stozae22aec72016-08-01 13:20:59 -07004446 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004447 * Tracing state
4448 */
4449 mTracing.dump(result);
4450 result.append("\n");
4451
4452 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004453 * HWC layer minidump
4454 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004455 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004456 const auto displayId = display->getId();
4457 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004458 continue;
4459 }
4460
Yiwei Zhang5434a782018-12-05 18:06:32 -08004461 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004462 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004463 const sp<DisplayDevice> displayDevice = display;
4464 mCurrentState.traverseInZOrder(
4465 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004466 result.append("\n");
4467 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004468
4469 /*
4470 * Dump HWComposer state
4471 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004472 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004473 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004474 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004475 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004476 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004477 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004478
4479 /*
4480 * Dump gralloc state
4481 */
4482 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4483 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004484
4485 /*
4486 * Dump VrFlinger state if in use.
4487 */
4488 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4489 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004490 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004491 result.append("\n");
4492 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004493
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004494 result.append(mTimeStats->miniDump());
4495 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004496}
4497
Chia-I Wu28f320b2018-05-03 11:02:56 -07004498void SurfaceFlinger::updateColorMatrixLocked() {
4499 mat4 colorMatrix;
4500 if (mGlobalSaturationFactor != 1.0f) {
4501 // Rec.709 luma coefficients
4502 float3 luminance{0.213f, 0.715f, 0.072f};
4503 luminance *= 1.0f - mGlobalSaturationFactor;
4504 mat4 saturationMatrix = mat4(
4505 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4506 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4507 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4508 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4509 );
4510 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4511 } else {
4512 colorMatrix = mClientColorMatrix * mDaltonizer();
4513 }
4514
4515 if (mCurrentState.colorMatrix != colorMatrix) {
4516 mCurrentState.colorMatrix = colorMatrix;
4517 mCurrentState.colorMatrixChanged = true;
4518 setTransactionFlags(eTransactionNeeded);
4519 }
4520}
4521
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004522status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004523#pragma clang diagnostic push
4524#pragma clang diagnostic error "-Wswitch-enum"
4525 switch (static_cast<ISurfaceComposerTag>(code)) {
4526 // These methods should at minimum make sure that the client requested
4527 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004528 case BOOT_FINISHED:
4529 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004530 case CREATE_DISPLAY:
4531 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004532 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004533 case GET_ANIMATION_FRAME_STATS:
4534 case GET_HDR_CAPABILITIES:
4535 case SET_ACTIVE_CONFIG:
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
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005603 auto configId = HwcConfigIndexType(defaultConfig);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005604 display->setActiveConfig(configId);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005605 const nsecs_t vsyncPeriod =
5606 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).vsyncPeriod;
5607 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, configId,
5608 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005609 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005610 }
5611
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005612 if (mDebugDisplayConfigSetByBackdoor) {
5613 // ignore this request as config is overridden by backdoor
5614 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005615 }
5616
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005617 bool policyChanged;
5618 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5619 &policyChanged) < 0) {
5620 return BAD_VALUE;
5621 }
5622 if (!policyChanged) {
5623 return NO_ERROR;
5624 }
5625
5626 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5627 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005628
5629 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5630 // that listeners that care about a change in allowed configs can get the notification.
5631 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005632 const nsecs_t vsyncPeriod =
5633 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005634 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005635 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005636
Ady Abraham2139f732019-11-13 18:56:40 -08005637 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5638 auto configId = mScheduler->getPreferredConfigId();
5639 auto preferredRefreshRate = configId
5640 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5641 : mRefreshRateConfigs->getMinRefreshRateByPolicy();
5642 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5643 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5644 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5645 ALOGV("switching to Scheduler preferred config %d",
5646 preferredRefreshRate.configId.value());
5647 setDesiredActiveConfig(
5648 {preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
5649 } else {
5650 // Set the highest allowed config
5651 setDesiredActiveConfig({mRefreshRateConfigs->getMaxRefreshRateByPolicy().configId,
5652 Scheduler::ConfigEvent::Changed});
5653 }
5654 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005655 ALOGV("switching to config %d", defaultConfig.value());
5656 setDesiredActiveConfig({defaultConfig, Scheduler::ConfigEvent::Changed});
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005657 }
5658
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005659 return NO_ERROR;
5660}
5661
Ana Krulec0782b882019-10-15 17:34:54 -07005662status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005663 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005664 float maxRefreshRate) {
5665 ATRACE_CALL();
5666
5667 if (!displayToken) {
5668 return BAD_VALUE;
5669 }
5670
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005671 status_t result = NO_ERROR;
5672
Ana Krulec234bb162019-11-10 22:55:55 +01005673 postMessageSync(new LambdaMessage([&]() {
5674 const auto display = getDisplayDeviceLocked(displayToken);
5675 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005676 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005677 ALOGE("Attempt to set desired display configs for invalid display token %p",
5678 displayToken.get());
5679 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005680 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005681 ALOGW("Attempt to set desired display configs for virtual display");
5682 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005683 result =
5684 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5685 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005686 }
5687 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005688
5689 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005690}
5691
5692status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005693 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005694 float* outMinRefreshRate,
5695 float* outMaxRefreshRate) {
5696 ATRACE_CALL();
5697
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005698 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005699 return BAD_VALUE;
5700 }
5701
5702 Mutex::Autolock lock(mStateLock);
5703 const auto display = getDisplayDeviceLocked(displayToken);
5704 if (!display) {
5705 return NAME_NOT_FOUND;
5706 }
5707
5708 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005709 HwcConfigIndexType defaultConfig;
5710 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5711 *outDefaultConfig = defaultConfig.value();
5712 return NO_ERROR;
5713 } else if (display->isVirtual()) {
5714 return BAD_VALUE;
5715 } else {
5716 const auto displayId = display->getId();
5717 if (!displayId) {
5718 return BAD_VALUE;
5719 }
5720 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5721 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5722 *outMinRefreshRate = 1e9f / vsyncPeriod;
5723 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5724 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005725 }
Ana Krulec0782b882019-10-15 17:34:54 -07005726}
5727
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005728void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005729 mFlinger->setInputWindowsFinished();
5730}
5731
Robert Carrc0df3122019-04-11 13:18:21 -07005732sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005733 BBinder* b = nullptr;
5734 if (handle) {
5735 b = handle->localBinder();
5736 }
Robert Carrc0df3122019-04-11 13:18:21 -07005737 if (b == nullptr) {
5738 return nullptr;
5739 }
5740 auto it = mLayersByLocalBinderToken.find(b);
5741 if (it != mLayersByLocalBinderToken.end()) {
5742 return it->second.promote();
5743 }
5744 return nullptr;
5745}
5746
Dominik Laskowski75848362019-11-11 17:57:20 -08005747void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005748 mNumLayers++;
5749 mScheduler->registerLayer(layer);
5750}
5751
5752void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5753 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005754 removeFromOffscreenLayers(layer);
5755}
5756
5757// WARNING: ONLY CALL THIS FROM LAYER DTOR
5758// Here we add children in the current state to offscreen layers and remove the
5759// layer itself from the offscreen layer list. Since
5760// this is the dtor, it is safe to access the current state. This keeps us
5761// from dangling children layers such that they are not reachable from the
5762// Drawing state nor the offscreen layer list
5763// See b/141111965
5764void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5765 for (auto& child : layer->getCurrentChildren()) {
5766 mOffscreenLayers.emplace(child.get());
5767 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005768 mOffscreenLayers.erase(layer);
5769}
5770
Alec Mouri4545a8a2019-08-08 20:05:32 -07005771void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5772 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5773}
5774
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005775status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5776 float lightPosY, float lightPosZ,
5777 float lightRadius) {
5778 Mutex::Autolock _l(mStateLock);
5779 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5780 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5781 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5782 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5783 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5784
5785 // these values are overridden when calculating the shadow settings for a layer.
5786 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5787 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005788 return NO_ERROR;
5789}
5790
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005791} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005792
Mathias Agopian3f844832013-08-07 21:24:32 -07005793#if defined(__gl_h_)
5794#error "don't include gl/gl.h in this file"
5795#endif
5796
5797#if defined(__gl2_h_)
5798#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005799#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005800
5801// TODO(b/129481165): remove the #pragma below and fix conversion issues
5802#pragma clang diagnostic pop // ignored "-Wconversion"