blob: 3dcf7d16656a4a44dddabc6e08257fb72d85e03c [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
Yiwei Zhang243b3782018-05-15 17:40:04 -0700341 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700342 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
343 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
344
Dan Stozaec460082018-12-17 15:35:09 -0800345 property_get("debug.sf.luma_sampling", value, "1");
346 mLumaSampling = atoi(value);
347
Romain Guy11d63f42017-07-20 12:47:14 -0700348 // We should be reading 'persist.sys.sf.color_saturation' here
349 // but since /data may be encrypted, we need to wait until after vold
350 // comes online to attempt to read the property. The property is
351 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800352
353 if (useTrebleTestingOverride()) {
354 // Without the override SurfaceFlinger cannot connect to HIDL
355 // services that are not listed in the manifests. Considered
356 // deriving the setting from the set service name, but it
357 // would be brittle if the name that's not 'default' is used
358 // for production purposes later on.
359 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
360 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800361}
362
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800363void SurfaceFlinger::onFirstRef()
364{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800365 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800366}
367
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700368SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800369
Dan Stozac7014012014-02-14 15:03:43 -0800370void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800371{
372 // the window manager died on us. prepare its eulogy.
373
Andy McFadden13a082e2012-08-24 10:16:42 -0700374 // restore initial conditions (default device unblank, etc)
375 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800376
377 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700378 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800379}
380
Robert Carr1db73f62016-12-21 12:58:51 -0800381static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700382 status_t err = client->initCheck();
383 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800384 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800385 }
Robert Carr1db73f62016-12-21 12:58:51 -0800386 return nullptr;
387}
388
389sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
390 return initClient(new Client(this));
391}
392
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700393sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
394 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700395{
396 class DisplayToken : public BBinder {
397 sp<SurfaceFlinger> flinger;
398 virtual ~DisplayToken() {
399 // no more references, this display must be terminated
400 Mutex::Autolock _l(flinger->mStateLock);
401 flinger->mCurrentState.displays.removeItem(this);
402 flinger->setTransactionFlags(eDisplayTransactionNeeded);
403 }
404 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700405 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700406 : flinger(flinger) {
407 }
408 };
409
410 sp<BBinder> token = new DisplayToken(this);
411
412 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700413 // Display ID is assigned when virtual display is allocated by HWC.
414 DisplayDeviceState state;
415 state.isSecure = secure;
416 state.displayName = displayName;
417 mCurrentState.displays.add(token, state);
418 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700419 return token;
420}
421
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700422void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700423 Mutex::Autolock _l(mStateLock);
424
Dominik Laskowski075d3172018-05-24 15:50:06 -0700425 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
426 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700427 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700428 return;
429 }
430
Dominik Laskowski075d3172018-05-24 15:50:06 -0700431 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
432 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700433 ALOGE("destroyDisplay called for non-virtual display");
434 return;
435 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700436 mInterceptor->saveDisplayDeletion(state.sequenceId);
437 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700438 setTransactionFlags(eDisplayTransactionNeeded);
439}
440
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800441std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
442 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700443
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800444 const auto internalDisplayId = getInternalDisplayIdLocked();
445 if (!internalDisplayId) {
446 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700447 }
448
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800449 std::vector<PhysicalDisplayId> displayIds;
450 displayIds.reserve(mPhysicalDisplayTokens.size());
451 displayIds.push_back(internalDisplayId->value);
452
453 for (const auto& [id, token] : mPhysicalDisplayTokens) {
454 if (id != *internalDisplayId) {
455 displayIds.push_back(id.value);
456 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700457 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700458
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800459 return displayIds;
460}
461
462sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
463 Mutex::Autolock lock(mStateLock);
464 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700465}
466
Ady Abraham37965d42018-11-01 13:43:32 -0700467status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
468 if (!outGetColorManagement) {
469 return BAD_VALUE;
470 }
471 *outGetColorManagement = useColorManagement;
472 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700473}
474
Lloyd Pique441d5042018-10-18 16:49:51 -0700475HWComposer& SurfaceFlinger::getHwComposer() const {
476 return mCompositionEngine->getHwComposer();
477}
478
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700479renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
480 return mCompositionEngine->getRenderEngine();
481}
482
Lloyd Pique70d91362018-10-18 16:02:55 -0700483compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
484 return *mCompositionEngine.get();
485}
486
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800487void SurfaceFlinger::bootFinished()
488{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700489 if (mStartPropertySetThread->join() != NO_ERROR) {
490 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800491 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800492 const nsecs_t now = systemTime();
493 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000494 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700495
Mikael Pessa90092f42019-08-26 17:22:04 -0700496 mFrameTracer->initialize();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700497
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700498 // wait patiently for the window manager death
499 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700500 mWindowManager = defaultServiceManager()->getService(name);
501 if (mWindowManager != 0) {
502 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700503 }
Robert Carr720e5062018-07-30 17:45:14 -0700504 sp<IBinder> input(defaultServiceManager()->getService(
505 String16("inputflinger")));
506 if (input == nullptr) {
507 ALOGE("Failed to link to input service");
508 } else {
509 mInputFlinger = interface_cast<IInputFlinger>(input);
510 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700511
Steven Thomas050b2c82017-03-06 11:45:16 -0800512 if (mVrFlinger) {
513 mVrFlinger->OnBootFinished();
514 }
515
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700516 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700517 // formerly we would just kill the process, but we now ask it to exit so it
518 // can choose where to stop the animation.
519 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700520
521 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
522 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
523 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700524
Ana Krulecbd6654b2019-02-15 15:18:15 -0800525 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800526 readPersistentProperties();
527 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800528
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700529 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
530 // set the refresh rate according to the policy
Ady Abraham2139f732019-11-13 18:56:40 -0800531 const auto& performanceRefreshRate = mRefreshRateConfigs->getMaxRefreshRateByPolicy();
532 changeRefreshRateLocked(performanceRefreshRate, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800533 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800534 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800535}
536
Dan Stoza436ccf32018-06-21 12:10:12 -0700537uint32_t SurfaceFlinger::getNewTexture() {
538 {
539 std::lock_guard lock(mTexturePoolMutex);
540 if (!mTexturePool.empty()) {
541 uint32_t name = mTexturePool.back();
542 mTexturePool.pop_back();
543 ATRACE_INT("TexturePoolSize", mTexturePool.size());
544 return name;
545 }
546
547 // The pool was too small, so increase it for the future
548 ++mTexturePoolSize;
549 }
550
551 // The pool was empty, so we need to get a new texture name directly using a
552 // blocking call to the main thread
553 uint32_t name = 0;
554 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
555 return name;
556}
557
Mathias Agopian3f844832013-08-07 21:24:32 -0700558void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700559 std::lock_guard lock(mTexturePoolMutex);
560 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
561 // to actually delete this or not based on mTexturePoolSize
562 mTexturePool.push_back(texture);
563 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700564}
565
Wei Wangf9b05ee2017-07-19 20:59:39 -0700566// Do not call property_set on main thread which will be blocked by init
567// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700568void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700569 ALOGI( "SurfaceFlinger's main thread ready to run. "
570 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700571 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800572
Steven Thomasb02664d2017-07-26 18:48:28 -0700573 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700574 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800575 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700576 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
577 renderengine::RenderEngineCreationArgs::Builder()
578 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
579 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
580 .setUseColorManagerment(useColorManagement)
581 .setEnableProtectedContext(enable_protected_contents(false))
582 .setPrecacheToneMapperShaderOnly(false)
583 .setContextPriority(useContextPriority
584 ? renderengine::RenderEngine::ContextPriority::HIGH
585 : renderengine::RenderEngine::ContextPriority::MEDIUM)
586 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800587 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700588
589 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
590 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700591 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
592 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800593 // Process any initial hotplug and resulting display changes.
594 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700595 const auto display = getDefaultDisplayDeviceLocked();
596 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700597 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700598 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800599
Steven Thomas050b2c82017-03-06 11:45:16 -0800600 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700601 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700602 // This callback is called from the vr flinger dispatch thread. We
603 // need to call signalTransaction(), which requires holding
604 // mStateLock when we're not on the main thread. Acquiring
605 // mStateLock from the vr flinger dispatch thread might trigger a
606 // deadlock in surface flinger (see b/66916578), so post a message
607 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700608 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700609 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
610 mVrFlingerRequestsDisplay = requestDisplay;
611 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700612 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800613 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700614 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
615 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700616 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700617 .value_or(0),
618 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800619 if (!mVrFlinger) {
620 ALOGE("Failed to start vrflinger");
621 }
622 }
623
Mathias Agopian92a979a2012-08-02 18:32:23 -0700624 // initialize our drawing state
625 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700626
Andy McFadden13a082e2012-08-24 10:16:42 -0700627 // set initial conditions (e.g. unblank default device)
628 initializeDisplays();
629
Steven Thomas137d4bc2019-07-25 16:55:14 -0700630 char primeShaderCache[PROPERTY_VALUE_MAX];
631 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
632 if (atoi(primeShaderCache)) {
633 getRenderEngine().primeCache();
634 }
Dan Stoza4e637772016-07-28 13:31:51 -0700635
Wei Wangf9b05ee2017-07-19 20:59:39 -0700636 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700637
638 const bool presentFenceReliable =
639 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
640 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700641
642 if (mStartPropertySetThread->Start() != NO_ERROR) {
643 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800644 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800645
Dan Stoza9e56aa02015-11-02 13:00:03 -0800646 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700647}
648
Romain Guy11d63f42017-07-20 12:47:14 -0700649void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700650 Mutex::Autolock _l(mStateLock);
651
Romain Guy11d63f42017-07-20 12:47:14 -0700652 char value[PROPERTY_VALUE_MAX];
653
654 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800655 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700656 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800657 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100658
659 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700660 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800661
662 property_get("persist.sys.sf.color_mode", value, "0");
663 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700664}
665
Mathias Agopiana67e4182012-06-19 17:26:12 -0700666void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800667 // Start boot animation service by setting a property mailbox
668 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700669 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800670 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700671 if (mStartPropertySetThread->join() != NO_ERROR) {
672 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800673 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700674}
675
Mathias Agopian875d8e12013-06-07 15:35:48 -0700676size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700677 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700678}
679
Mathias Agopian875d8e12013-06-07 15:35:48 -0700680size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700681 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700682}
683
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800684// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800685
Jamie Gennis582270d2011-08-17 18:19:00 -0700686bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800687 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800688 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800689 return authenticateSurfaceTextureLocked(bufferProducer);
690}
691
692bool SurfaceFlinger::authenticateSurfaceTextureLocked(
693 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800694 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800695 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800696}
697
Brian Anderson6b376712017-04-04 10:51:39 -0700698status_t SurfaceFlinger::getSupportedFrameTimestamps(
699 std::vector<FrameEvent>* outSupported) const {
700 *outSupported = {
701 FrameEvent::REQUESTED_PRESENT,
702 FrameEvent::ACQUIRE,
703 FrameEvent::LATCH,
704 FrameEvent::FIRST_REFRESH_START,
705 FrameEvent::LAST_REFRESH_START,
706 FrameEvent::GPU_COMPOSITION_DONE,
707 FrameEvent::DEQUEUE_READY,
708 FrameEvent::RELEASE,
709 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700710 ConditionalLock _l(mStateLock,
711 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700712 if (!getHwComposer().hasCapability(
713 HWC2::Capability::PresentFenceIsNotReliable)) {
714 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
715 }
716 return NO_ERROR;
717}
718
Dominik Laskowski22488f62019-03-28 09:53:04 -0700719status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
720 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700721 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700722 return BAD_VALUE;
723 }
724
Dominik Laskowski22488f62019-03-28 09:53:04 -0700725 Mutex::Autolock lock(mStateLock);
726
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800727 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700728 if (!displayId) {
729 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700730 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700731
Mathias Agopian8b736f12012-08-13 17:54:26 -0700732 // TODO: Not sure if display density should handled by SF any longer
733 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700734 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700735 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700736 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800737 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700738 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700739 }
740 return density;
741 }
742 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700743 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700744 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700745 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700746 return getDensityFromProperty("ro.sf.lcd_density"); }
747 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700748
Dan Stoza7f7da322014-05-02 15:26:25 -0700749 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700750
Dominik Laskowski075d3172018-05-24 15:50:06 -0700751 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700752 DisplayInfo info = DisplayInfo();
753
Dan Stoza9e56aa02015-11-02 13:00:03 -0800754 float xdpi = hwConfig->getDpiX();
755 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700756
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700757 info.w = hwConfig->getWidth();
758 info.h = hwConfig->getHeight();
759 // Default display viewport to display width and height
760 info.viewportW = info.w;
761 info.viewportH = info.h;
762
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800763 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700764 // The density of the device is provided by a build property
765 float density = Density::getBuildDensity() / 160.0f;
766 if (density == 0) {
767 // the build doesn't provide a density -- this is wrong!
768 // use xdpi instead
769 ALOGE("ro.sf.lcd_density must be defined as a build property");
770 density = xdpi / 160.0f;
771 }
772 if (Density::getEmuDensity()) {
773 // if "qemu.sf.lcd_density" is specified, it overrides everything
774 xdpi = ydpi = density = Density::getEmuDensity();
775 density /= 160.0f;
776 }
777 info.density = density;
778
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700779 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowski718f9602019-11-09 20:01:35 -0800780 info.orientation = display->getOrientation();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700781
782 // This is for screenrecord
783 const Rect viewport = display->getViewport();
784 if (viewport.isValid()) {
785 info.viewportW = uint32_t(viewport.getWidth());
786 info.viewportH = uint32_t(viewport.getHeight());
787 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700788 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700789 } else {
790 // TODO: where should this value come from?
791 static const int TV_DENSITY = 213;
792 info.density = TV_DENSITY / 160.0f;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700793
794 const auto display = getDisplayDeviceLocked(displayToken);
795 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700796 }
797
Dan Stoza7f7da322014-05-02 15:26:25 -0700798 info.xdpi = xdpi;
799 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800800 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham2139f732019-11-13 18:56:40 -0800801
Ady Abraham9e16a482019-12-03 17:19:41 -0800802 const auto offset = mPhaseConfiguration->getOffsetsForRefreshRate(info.fps);
Ady Abraham796beb02019-04-11 15:23:07 -0700803 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800804
Andy McFadden91b2ca82014-06-13 14:04:23 -0700805 // This is how far in advance a buffer must be queued for
806 // presentation at a given time. If you want a buffer to appear
807 // on the screen at time N, you must submit the buffer before
808 // (N - presentationDeadline).
809 //
810 // Normally it's one full refresh period (to give SF a chance to
811 // latch the buffer), but this can be reduced by configuring a
812 // DispSync offset. Any additional delays introduced by the hardware
813 // composer or panel must be accounted for here.
814 //
815 // We add an additional 1ms to allow for processing time and
816 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700817 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700818
819 // All non-virtual displays are currently considered secure.
820 info.secure = true;
821
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800822 if (displayId == getInternalDisplayIdLocked() &&
Dominik Laskowski718f9602019-11-09 20:01:35 -0800823 (internalDisplayOrientation == ui::ROTATION_90 ||
824 internalDisplayOrientation == ui::ROTATION_270)) {
Iris Chang7501ed62018-04-30 14:45:42 +0800825 std::swap(info.w, info.h);
826 }
827
Michael Wright28f24d02016-07-12 13:30:53 -0700828 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700829 }
830
Dan Stoza7f7da322014-05-02 15:26:25 -0700831 return NO_ERROR;
832}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700833
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700834status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
835 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700836 return BAD_VALUE;
837 }
838
Ana Krulecc2870422019-01-29 19:00:58 -0800839 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700840 return NO_ERROR;
841}
842
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700843int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
844 const auto display = getDisplayDevice(displayToken);
845 if (!display) {
846 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800847 return BAD_VALUE;
848 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700849
Steven Thomasc9098452019-09-30 17:15:05 -0700850 if (display->isPrimary()) {
851 std::lock_guard<std::mutex> lock(mActiveConfigLock);
852 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800853 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700854 }
Steven Thomasc9098452019-09-30 17:15:05 -0700855 }
Ady Abraham2139f732019-11-13 18:56:40 -0800856
857 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700858}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700859
Ady Abraham03b02dd2019-03-21 15:40:11 -0700860void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800861 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800862 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
863 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800864
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800865 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800866 // config twice. However event generation config might have changed so we need to update it
867 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800868 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700869 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
870 mDesiredActiveConfig = info;
871 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800872
873 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800874 // This will trigger HWC refresh without resetting the idle timer.
875 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700876 // Start receiving vsync samples now, so that we can detect a period
877 // switch.
878 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700879 // As we called to set period, we will call to onRefreshRateChangeCompleted once
880 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700881 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800882
Ady Abraham9e16a482019-12-03 17:19:41 -0800883 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
884 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800885 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800886 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700887
888 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800889 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700890 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800891}
892
893status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
894 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800895
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100896 if (!displayToken) {
897 return BAD_VALUE;
898 }
Ady Abraham838de062019-02-04 10:24:03 -0800899
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100900 status_t result = NO_ERROR;
901
902 postMessageSync(new LambdaMessage([&]() {
903 const auto display = getDisplayDeviceLocked(displayToken);
904 if (!display) {
905 ALOGE("Attempt to set allowed display configs for invalid display token %p",
906 displayToken.get());
907 result = BAD_VALUE;
908 } else if (display->isVirtual()) {
909 ALOGW("Attempt to set allowed display configs for virtual display");
910 result = BAD_VALUE;
911 } else {
912 HwcConfigIndexType config(mode);
913 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
914 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
915 refreshRate.fps);
916 }
917 }));
918
919 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800920}
921
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800922void SurfaceFlinger::setActiveConfigInternal() {
923 ATRACE_CALL();
924
Dominik Laskowski22488f62019-03-28 09:53:04 -0700925 const auto display = getDefaultDisplayDeviceLocked();
926 if (!display) {
927 return;
928 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800929
Dominik Laskowski22488f62019-03-28 09:53:04 -0700930 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800931 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700932 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800933 display->setActiveConfig(mUpcomingActiveConfig.configId);
934
Ady Abraham2139f732019-11-13 18:56:40 -0800935 auto refreshRate =
936 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800937 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
938 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800939 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700940
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800941 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700942 const nsecs_t vsyncPeriod =
943 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
944 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800945 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700946 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800947 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800948}
949
Ady Abraham53852a52019-05-28 18:07:44 -0700950void SurfaceFlinger::desiredActiveConfigChangeDone() {
951 std::lock_guard<std::mutex> lock(mActiveConfigLock);
952 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
953 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700954
955 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham2139f732019-11-13 18:56:40 -0800956 auto refreshRate =
957 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800958 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
959 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700960}
961
Dominik Laskowski22488f62019-03-28 09:53:04 -0700962bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800963 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800964 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -0800965 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700966 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800967 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700968 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800969 return true;
970 }
971
972 // We received the present fence from the HWC, so we assume it successfully updated
973 // the config, hence we update SF.
974 mCheckPendingFence = false;
975 setActiveConfigInternal();
976 }
977
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800978 // Store the local variable to release the lock.
979 ActiveConfigInfo desiredActiveConfig;
980 {
981 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800982 if (!mDesiredActiveConfigChanged) {
983 return false;
984 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800985 desiredActiveConfig = mDesiredActiveConfig;
986 }
987
Ady Abraham2139f732019-11-13 18:56:40 -0800988 auto refreshRate =
989 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
990 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
991 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -0700992 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800993 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
994 // display is not valid or we are already in the requested mode
995 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -0700996 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800997 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800998 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800999
Ady Abraham838de062019-02-04 10:24:03 -08001000 // Desired active config was set, it is different than the config currently in use, however
1001 // allowed configs might have change by the time we process the refresh.
1002 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001003 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001004 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001005 return false;
1006 }
Alec Mouri7f015182019-07-11 13:56:22 -07001007
Ady Abrahamb838aed2019-02-12 15:30:16 -08001008 mUpcomingActiveConfig = desiredActiveConfig;
1009 const auto displayId = display->getId();
1010 LOG_ALWAYS_FATAL_IF(!displayId);
1011
Ady Abraham2139f732019-11-13 18:56:40 -08001012 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001013
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001014 // TODO(b/142753666) use constrains
1015 HWC2::VsyncPeriodChangeConstraints constraints;
1016 constraints.desiredTimeNanos = systemTime();
1017 constraints.seamlessRequired = false;
1018
1019 HWC2::VsyncPeriodChangeTimeline outTimeline;
1020 auto status =
1021 getHwComposer().setActiveConfigWithConstraints(*displayId,
1022 mUpcomingActiveConfig.configId.value(),
1023 constraints, &outTimeline);
1024 if (status != NO_ERROR) {
1025 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1026 return false;
1027 }
1028
1029 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1030 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001031 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001032 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001033}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001034
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001035status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1036 Vector<ColorMode>* outColorModes) {
1037 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001038 return BAD_VALUE;
1039 }
1040
Peiyong Lina52f0292018-03-14 17:26:31 -07001041 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001042 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001043 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001044 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1045
1046 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1047 if (!displayId) {
1048 return NAME_NOT_FOUND;
1049 }
1050
Dominik Laskowski075d3172018-05-24 15:50:06 -07001051 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001052 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001053 }
Michael Wright28f24d02016-07-12 13:30:53 -07001054 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001055
1056 // If it's built-in display and the configuration claims it's not wide color capable,
1057 // filter out all wide color modes. The typical reason why this happens is that the
1058 // hardware is not good enough to support GPU composition of wide color, and thus the
1059 // OEMs choose to disable this capability.
1060 if (isInternalDisplay && !hasWideColorDisplay) {
1061 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1062 isWideColorMode);
1063 } else {
1064 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1065 }
Michael Wright28f24d02016-07-12 13:30:53 -07001066
1067 return NO_ERROR;
1068}
1069
Daniel Solomon42d04562019-01-20 21:03:19 -08001070status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1071 ui::DisplayPrimaries &primaries) {
1072 if (!displayToken) {
1073 return BAD_VALUE;
1074 }
1075
1076 // Currently we only support this API for a single internal display.
1077 if (getInternalDisplayToken() != displayToken) {
1078 return BAD_VALUE;
1079 }
1080
1081 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1082 return NO_ERROR;
1083}
1084
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1086 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001087 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001088 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001089 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001090}
1091
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001092status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001093 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001094 Vector<ColorMode> modes;
1095 getDisplayColorModes(displayToken, &modes);
1096 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1097 if (mode < ColorMode::NATIVE || !exists) {
1098 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1099 decodeColorMode(mode).c_str(), mode, displayToken.get());
1100 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001101 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001102 const auto display = getDisplayDevice(displayToken);
1103 if (!display) {
1104 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1105 decodeColorMode(mode).c_str(), mode, displayToken.get());
1106 } else if (display->isVirtual()) {
1107 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1108 decodeColorMode(mode).c_str(), mode);
1109 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001110 display->getCompositionDisplay()->setColorProfile(
1111 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1112 RenderIntent::COLORIMETRIC,
1113 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001114 }
1115 }));
1116
Michael Wright28f24d02016-07-12 13:30:53 -07001117 return NO_ERROR;
1118}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001119
Galia Peycheva5492cb52019-10-30 14:13:16 +01001120status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1121 bool* outSupport) const {
1122 Mutex::Autolock _l(mStateLock);
1123
1124 if (!displayToken) {
1125 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1126 return BAD_VALUE;
1127 }
1128 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1129 if (!displayId) {
1130 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1131 displayToken.get());
1132 return NAME_NOT_FOUND;
1133 }
1134 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1135 HWC2::DisplayCapability::AutoLowLatencyMode);
1136 return NO_ERROR;
1137}
1138
1139void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1140 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1141}
1142
1143void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1144 if (!displayToken) {
1145 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1146 return;
1147 }
1148 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1149 if (!displayId) {
1150 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1151 displayToken.get());
1152 return;
1153 }
1154
1155 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1156}
1157
1158status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1159 bool* outSupport) const {
1160 Mutex::Autolock _l(mStateLock);
1161
1162 if (!displayToken) {
1163 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1164 return BAD_VALUE;
1165 }
1166 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1167 if (!displayId) {
1168 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1169 displayToken.get());
1170 return NAME_NOT_FOUND;
1171 }
1172
1173 std::vector<HWC2::ContentType> outSupportedContentTypes;
1174 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1175 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1176 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1177 return NO_ERROR;
1178}
1179
1180void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1181 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1182}
1183
1184void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1185 if (!displayToken) {
1186 ALOGE("setGameContentType() failed. Missing display token.");
1187 return;
1188 }
1189 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1190 if (!displayId) {
1191 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1192 displayToken.get());
1193 return;
1194 }
1195
1196 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1197 getHwComposer().setContentType(*displayId, type);
1198}
1199
Svetoslavd85084b2014-03-20 10:28:31 -07001200status_t SurfaceFlinger::clearAnimationFrameStats() {
1201 Mutex::Autolock _l(mStateLock);
1202 mAnimFrameTracker.clearStats();
1203 return NO_ERROR;
1204}
1205
1206status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1207 Mutex::Autolock _l(mStateLock);
1208 mAnimFrameTracker.getStats(outStats);
1209 return NO_ERROR;
1210}
1211
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001212status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1213 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001214 Mutex::Autolock _l(mStateLock);
1215
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001216 const auto display = getDisplayDeviceLocked(displayToken);
1217 if (!display) {
1218 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001219 return BAD_VALUE;
1220 }
1221
Peiyong Linfb069302018-04-25 14:34:31 -07001222 // At this point the DisplayDeivce should already be set up,
1223 // meaning the luminance information is already queried from
1224 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001225 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001226 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1227 capabilities.getDesiredMaxLuminance(),
1228 capabilities.getDesiredMaxAverageLuminance(),
1229 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001230
1231 return NO_ERROR;
1232}
1233
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001234status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1235 ui::PixelFormat* outFormat,
1236 ui::Dataspace* outDataspace,
1237 uint8_t* outComponentMask) const {
1238 if (!outFormat || !outDataspace || !outComponentMask) {
1239 return BAD_VALUE;
1240 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001241 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001242 if (!display || !display->getId()) {
1243 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1244 return BAD_VALUE;
1245 }
1246 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1247 outDataspace, outComponentMask);
1248}
1249
Kevin DuBois74e53772018-11-19 10:52:38 -08001250status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1251 bool enable, uint8_t componentMask,
1252 uint64_t maxFrames) const {
1253 const auto display = getDisplayDevice(displayToken);
1254 if (!display || !display->getId()) {
1255 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1256 return BAD_VALUE;
1257 }
1258
1259 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1260 componentMask, maxFrames);
1261}
1262
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001263status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1264 uint64_t maxFrames, uint64_t timestamp,
1265 DisplayedFrameStats* outStats) const {
1266 const auto display = getDisplayDevice(displayToken);
1267 if (!display || !display->getId()) {
1268 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1269 return BAD_VALUE;
1270 }
1271
1272 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1273 outStats);
1274}
1275
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001276status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1277 if (!outSupported) {
1278 return BAD_VALUE;
1279 }
1280 *outSupported = getRenderEngine().supportsProtectedContent();
1281 return NO_ERROR;
1282}
1283
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001284status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1285 bool* outIsWideColorDisplay) const {
1286 if (!displayToken || !outIsWideColorDisplay) {
1287 return BAD_VALUE;
1288 }
1289 Mutex::Autolock _l(mStateLock);
1290 const auto display = getDisplayDeviceLocked(displayToken);
1291 if (!display) {
1292 return BAD_VALUE;
1293 }
Peiyong Linff84a152019-05-17 18:36:19 -07001294
1295 // Use hasWideColorDisplay to override built-in display.
1296 const auto displayId = display->getId();
1297 if (displayId && displayId == getInternalDisplayIdLocked()) {
1298 *outIsWideColorDisplay = hasWideColorDisplay;
1299 return NO_ERROR;
1300 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001301 *outIsWideColorDisplay = display->hasWideColorGamut();
1302 return NO_ERROR;
1303}
1304
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001305status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001306 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001307 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001308
Dominik Laskowski6505f792019-09-18 11:10:05 -07001309 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1310 mEventQueue->setEventConnection(
1311 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001312 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001313 }));
1314
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001315 return NO_ERROR;
1316}
1317
1318status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001319 Mutex::Autolock lock(mStateLock);
1320 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001321}
1322
Lloyd Pique755e3192018-01-31 16:46:15 -08001323status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1324 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001325 // Try to acquire a lock for 1s, fail gracefully
1326 const status_t err = mStateLock.timedLock(s2ns(1));
1327 const bool locked = (err == NO_ERROR);
1328 if (!locked) {
1329 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1330 return TIMED_OUT;
1331 }
1332
1333 outLayers->clear();
1334 mCurrentState.traverseInZOrder([&](Layer* layer) {
1335 outLayers->push_back(layer->getLayerDebugInfo());
1336 });
1337
1338 mStateLock.unlock();
1339 return NO_ERROR;
1340}
1341
Peiyong Linc6780972018-10-28 15:24:08 -07001342status_t SurfaceFlinger::getCompositionPreference(
1343 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1344 Dataspace* outWideColorGamutDataspace,
1345 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001346 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001347 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001348 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001349 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001350 return NO_ERROR;
1351}
1352
Dan Stozaec460082018-12-17 15:35:09 -08001353status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1354 const sp<IBinder>& stopLayerHandle,
1355 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001356 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001357 return BAD_VALUE;
1358 }
1359 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001360 return NO_ERROR;
1361}
1362
Dan Stozaec460082018-12-17 15:35:09 -08001363status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001364 if (!listener) {
1365 return BAD_VALUE;
1366 }
Dan Stozaec460082018-12-17 15:35:09 -08001367 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001368 return NO_ERROR;
1369}
Dan Gittik57e63c52019-01-18 16:37:54 +00001370
1371status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1372 bool* outSupport) const {
1373 if (!displayToken || !outSupport) {
1374 return BAD_VALUE;
1375 }
1376 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1377 if (!displayId) {
1378 return NAME_NOT_FOUND;
1379 }
1380 *outSupport =
1381 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1382 return NO_ERROR;
1383}
1384
1385status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1386 float brightness) const {
1387 if (!displayToken) {
1388 return BAD_VALUE;
1389 }
1390 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1391 if (!displayId) {
1392 return NAME_NOT_FOUND;
1393 }
1394 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1395}
1396
Ady Abraham8532d012019-05-08 14:50:56 -07001397status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1398 PowerHint powerHint = static_cast<PowerHint>(hintId);
1399
1400 if (powerHint == PowerHint::INTERACTION) {
1401 mScheduler->notifyTouchEvent();
1402 }
1403
1404 return NO_ERROR;
1405}
1406
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001407// ----------------------------------------------------------------------------
1408
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001409sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001410 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001411 const auto& handle =
1412 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001413
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001414 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001415}
1416
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001417// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001418
1419void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001420 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001421}
1422
1423void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001424 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001425 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001426}
1427
1428void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001429 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001430 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001431}
1432
1433void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001434 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001435 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001436}
1437
1438status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001439 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001440 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001441}
1442
1443status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001444 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001445 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001446 if (res == NO_ERROR) {
1447 msg->wait();
1448 }
1449 return res;
1450}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001451
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001452void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001453 do {
1454 waitForEvent();
1455 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001456}
1457
Dominik Laskowski83b88212018-12-11 13:34:06 -08001458nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001459 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001460 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1461 return 0;
1462 }
1463
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001464 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001465}
1466
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001467void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001468 int64_t timestamp,
1469 std::optional<hwc2_vsync_period_t> /*vsyncPeriod*/) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001470 ATRACE_NAME("SF onVsync");
1471
Ady Abraham7159f572019-10-11 11:10:18 -07001472 // TODO(b/140201379): use vsyncPeriod in the new DispSync
1473
Steven Thomas3cfac282017-02-06 12:29:30 -08001474 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001475 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001476 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001477 return;
1478 }
1479
Dominik Laskowski075d3172018-05-24 15:50:06 -07001480 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001481 return;
1482 }
1483
Dominik Laskowski075d3172018-05-24 15:50:06 -07001484 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001485 // For now, we don't do anything with external display vsyncs.
1486 return;
1487 }
1488
Alec Mourif8e689c2019-05-20 18:32:22 -07001489 bool periodFlushed = false;
1490 mScheduler->addResyncSample(timestamp, &periodFlushed);
1491 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001492 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001493 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001494}
1495
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001496void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001497 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1498 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001499}
1500
Ady Abraham2139f732019-11-13 18:56:40 -08001501bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001502 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001503}
1504
Ady Abraham2139f732019-11-13 18:56:40 -08001505void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1506 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001507 const auto display = getDefaultDisplayDeviceLocked();
1508 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001509 return;
1510 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001511 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001512
Ana Krulec7d1d6832018-12-27 11:10:09 -08001513 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001514 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1515 ALOGV("Skipping config %d as it is not part of allowed configs",
1516 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001517 return;
1518 }
1519
Ady Abraham2139f732019-11-13 18:56:40 -08001520 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001521}
1522
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001523void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001524 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001525 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001526 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001527
Lloyd Piqueba04e622017-12-14 17:11:26 -08001528 // Ignore events that do not have the right sequenceId.
1529 if (sequenceId != getBE().mComposerSequenceId) {
1530 return;
1531 }
1532
Steven Thomasb02664d2017-07-26 18:48:28 -07001533 // Only lock if we're not on the main thread. This function is normally
1534 // called on a hwbinder thread, but for the primary display it's called on
1535 // the main thread with the state lock already held, so don't attempt to
1536 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001537 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001538
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001539 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001540
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001541 if (std::this_thread::get_id() == mMainThreadId) {
1542 // Process all pending hot plug events immediately if we are on the main thread.
1543 processDisplayHotplugEventsLocked();
1544 }
1545
Lloyd Piqueba04e622017-12-14 17:11:26 -08001546 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001547}
1548
Ady Abraham7159f572019-10-11 11:10:18 -07001549void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001550 int32_t sequenceId, hwc2_display_t /*display*/,
1551 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1552 Mutex::Autolock lock(mStateLock);
1553 if (sequenceId != getBE().mComposerSequenceId) {
1554 return;
1555 }
1556 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001557}
1558
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001559void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1560 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1561 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1562}
1563
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001564void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001565 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001566 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001567 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001568 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001569 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001570}
1571
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001572void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001573 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001574
1575 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1576 // display power state.
1577 postMessageAsync(new LambdaMessage(
1578 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1579}
1580
1581void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1582 ATRACE_CALL();
1583
Ady Abraham27c70212019-06-11 10:52:26 -07001584 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1585
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001586 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001587 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1588 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001589 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001590 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001591 }
Mathias Agopian86303202012-07-24 22:46:10 -07001592}
1593
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001594// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001595void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001596 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001597 // Clear the drawing state so that the logic inside of
1598 // handleTransactionLocked will fire. It will determine the delta between
1599 // mCurrentState and mDrawingState and re-apply all changes when we make the
1600 // transition.
1601 mDrawingState.displays.clear();
1602 mDisplays.clear();
1603}
1604
Steven Thomas050b2c82017-03-06 11:45:16 -08001605void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001606 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001607 if (!mVrFlinger)
1608 return;
1609 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001610 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001611 return;
1612 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001613
Lloyd Pique441d5042018-10-18 16:49:51 -07001614 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001615 ALOGE("Vr flinger is only supported for remote hardware composer"
1616 " service connections. Ignoring request to transition to vr"
1617 " flinger.");
1618 mVrFlingerRequestsDisplay = false;
1619 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001620 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001621
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001622 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001623
Steven Thomas0123ac62018-07-12 11:32:34 -07001624 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001625 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001626
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001627 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001628
1629 // Clear out all the output layers from the composition engine for all
1630 // displays before destroying the hardware composer interface. This ensures
1631 // any HWC layers are destroyed through that interface before it becomes
1632 // invalid.
1633 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001634 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001635 }
1636
Steven Thomas0123ac62018-07-12 11:32:34 -07001637 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1638 // called below. Clear the reference now so we don't accidentally use it
1639 // later.
1640 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001641
Steven Thomasb02664d2017-07-26 18:48:28 -07001642 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001643 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001644 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001645
Steven Thomasb02664d2017-07-26 18:48:28 -07001646 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001647 // Delete the current instance before creating the new one
1648 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1649 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1650 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1651 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001652
Lloyd Pique441d5042018-10-18 16:49:51 -07001653 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001654 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001655
1656 if (vrFlingerRequestsDisplay) {
1657 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001658 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001659
1660 mVisibleRegionsDirty = true;
1661 invalidateHwcGeometry();
1662
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001663 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001664 display = getDefaultDisplayDeviceLocked();
1665 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001666 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001667
Steven Thomasb02664d2017-07-26 18:48:28 -07001668 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001669 const nsecs_t vsyncPeriod = getVsyncPeriod();
1670 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001671
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001672 // The present fences returned from vr_hwc are not an accurate
1673 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001674 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001675
Steven Thomasb02664d2017-07-26 18:48:28 -07001676 // Use phase of 0 since phase is not known.
1677 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001678 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001679 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001680
Ana Krulecc2870422019-01-29 19:00:58 -08001681 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001682
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001683 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001684 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001685}
1686
Ady Abraham11579302019-09-19 12:35:58 -07001687bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1688 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001689 // We are storing the last 2 present fences. If sf's phase offset is to be
1690 // woken up before the actual vsync but targeting the next vsync, we need to check
1691 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001692 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1693 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001694
Ady Abraham11579302019-09-19 12:35:58 -07001695 if (fence == Fence::NO_FENCE) {
1696 return false;
1697 }
1698
1699 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1700 fence->wait(graceTimeMs);
1701 }
1702
1703 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001704}
1705
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001706void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001707 DisplayStatInfo stats;
1708 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001709 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001710 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001711 mExpectedPresentTime.store(
1712 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001713}
1714
Dominik Laskowski22488f62019-03-28 09:53:04 -07001715void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001716 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001717 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001718 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001719 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001720 // calculate the expected present time once and use the cached
1721 // value throughout this frame to make sure all layers are
1722 // seeing this same value.
1723 populateExpectedPresentTime();
1724
Ady Abraham11579302019-09-19 12:35:58 -07001725 // When Backpressure propagation is enabled we want to give a small grace period
1726 // for the present fence to fire instead of just giving up on this frame to handle cases
1727 // where present fence is just about to get signaled.
1728 const int graceTimeForPresentFenceMs =
1729 (mPropagateBackpressure &&
1730 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1731 ? 1
1732 : 0;
1733 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1734 previousFrameMissed(
1735 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001736 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1737 mHadDeviceComposition && frameMissed};
1738 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1739 mHadClientComposition && frameMissed};
1740
Alec Mouricc0fc602019-02-26 21:45:19 -08001741 if (frameMissed) {
1742 mFrameMissedCount++;
1743 mTimeStats->incrementMissedFrames();
1744 }
1745
Alec Mouri40189b02019-03-05 15:07:54 -08001746 if (hwcFrameMissed) {
1747 mHwcFrameMissedCount++;
1748 }
1749
1750 if (gpuFrameMissed) {
1751 mGpuFrameMissedCount++;
1752 }
1753
Dominik Laskowski49cea512019-11-12 14:13:23 -08001754 mScheduler->chooseRefreshRateForContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001755
Ady Abrahamb838aed2019-02-12 15:30:16 -08001756 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001757 break;
1758 }
1759
Ady Abrahamadb9a992019-09-19 21:21:55 +00001760 if (frameMissed && mPropagateBackpressure) {
1761 if ((hwcFrameMissed && !gpuFrameMissed) ||
1762 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001763 signalLayerUpdate();
1764 break;
1765 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001766 }
Dan Stoza50182882016-07-08 12:02:20 -07001767
Steven Thomas050b2c82017-03-06 11:45:16 -08001768 // Now that we're going to make it to the handleMessageTransaction()
1769 // call below it's safe to call updateVrFlinger(), which will
1770 // potentially trigger a display handoff.
1771 updateVrFlinger();
1772
Dan Stoza6b9454d2014-11-07 16:00:59 -08001773 bool refreshNeeded = handleMessageTransaction();
1774 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001775
1776 updateCursorAsync();
1777 updateInputFlinger();
1778
Dan Stoza58784442014-12-02 16:58:17 -08001779 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001780 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001781 // Signal a refresh if a transaction modified the window state,
1782 // a new buffer was latched, or if HWC has requested a full
1783 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001784 if (mFrameStartTime <= 0) {
1785 // We should only use the time of the first invalidate
1786 // message that signals a refresh as the beginning of the
1787 // frame. Otherwise the real frame time will be
1788 // underestimated.
1789 mFrameStartTime = frameStart;
1790 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001791 signalRefresh();
1792 }
1793 break;
1794 }
1795 case MessageQueue::REFRESH: {
1796 handleMessageRefresh();
1797 break;
1798 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001799 }
1800}
1801
Dan Stoza6b9454d2014-11-07 16:00:59 -08001802bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001803 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001804 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001805
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001806 bool flushedATransaction = flushTransactionQueues();
1807
1808 bool runHandleTransaction = transactionFlags &&
1809 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1810
1811 if (runHandleTransaction) {
1812 handleTransaction(eTransactionMask);
1813 } else {
1814 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001815 }
1816
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001817 if (transactionFlushNeeded()) {
1818 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001819 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001820
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001821 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001822}
1823
Mathias Agopian4fec8732012-06-29 14:12:52 -07001824void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001825 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001826
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001827 mRefreshPending = false;
1828
Lloyd Piqueab039b52019-02-13 14:22:42 -08001829 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001830 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001831 for (const auto& [_, display] : mDisplays) {
1832 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1833 }
1834 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1835 auto compositionLayer = layer->getCompositionLayer();
1836 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1837 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001838 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1839 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1840 auto compositionLayer = layer->getCompositionLayer();
Adithya Srinivasan87c1b80e2019-11-21 11:43:06 -08001841 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001842 }
1843
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001844 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001845 refreshArgs.outputColorSetting = useColorManagement
1846 ? mDisplayColorSetting
1847 : compositionengine::OutputColorSetting::kUnmanaged;
1848 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1849 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001850
1851 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1852 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001853
1854 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1855 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1856 mDrawingState.colorMatrixChanged = false;
1857 }
1858
1859 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1860
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001861 if (mDebugRegion != 0) {
1862 refreshArgs.devOptFlashDirtyRegionsDelay =
1863 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1864 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001865
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001866 mGeometryInvalid = false;
1867
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001868 // Store the present time just before calling to the composition engine so we could notify
1869 // the scheduler.
1870 const auto presentTime = systemTime();
1871
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001872 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001873 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1874 // Reset the frame start time now that we've recorded this frame.
1875 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001876
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001877 mScheduler->onDisplayRefreshed(presentTime);
1878
David Sodmanfa9b2af2017-12-24 13:28:59 -08001879 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001880 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001881
Lloyd Pique66d68602019-02-13 14:23:31 -08001882 mHadClientComposition =
1883 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1884 auto& displayDevice = tokenDisplayPair.second;
1885 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1886 });
1887 mHadDeviceComposition =
1888 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1889 auto& displayDevice = tokenDisplayPair.second;
1890 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1891 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001892
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001893 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001894
David Sodman7e4ae112018-02-09 15:02:28 -08001895 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001896 if (mVisibleRegionsDirty) {
1897 mVisibleRegionsDirty = false;
1898 if (mTracingEnabled) {
1899 mTracing.notify("visibleRegionsDirty");
1900 }
1901 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001902
1903 if (mCompositionEngine->needsAnotherUpdate()) {
1904 signalLayerUpdate();
1905 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001906}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001907
David Sodmanfa9b2af2017-12-24 13:28:59 -08001908
1909bool SurfaceFlinger::handleMessageInvalidate() {
1910 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001911 bool refreshNeeded = handlePageFlip();
1912
Vishnu Nair4351ad52019-02-11 14:13:02 -08001913 if (mVisibleRegionsDirty) {
1914 computeLayerBounds();
1915 }
1916
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001917 for (auto& layer : mLayersPendingRefresh) {
1918 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001919 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001920 invalidateLayerStack(layer, visibleReg);
1921 }
1922 mLayersPendingRefresh.clear();
1923 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001924}
1925
Ana Krulece588e312018-09-18 12:32:24 -07001926void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1927 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001928 // Update queue of past composite+present times and determine the
1929 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001930 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001931 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001932 while (!getBE().mCompositePresentTimes.empty()) {
1933 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001934 // Cached values should have been updated before calling this method,
1935 // which helps avoid duplicate syscalls.
1936 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1937 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1938 break;
1939 }
1940 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001941 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001942 }
1943
1944 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001945 while (getBE().mCompositePresentTimes.size() > 16) {
1946 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001947 }
1948
Ana Krulece588e312018-09-18 12:32:24 -07001949 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001950}
1951
Ana Krulece588e312018-09-18 12:32:24 -07001952void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1953 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001954 // Integer division and modulo round toward 0 not -inf, so we need to
1955 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08001956 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
1957 ? (stats.vsyncPeriod -
1958 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
1959 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001960
Ady Abraham9e16a482019-12-03 17:19:41 -08001961 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001962 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001963 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001964 }
1965
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001966 // Snap the latency to a value that removes scheduling jitter from the
1967 // composition and present times, which often have >1ms of jitter.
1968 // Reducing jitter is important if an app attempts to extrapolate
1969 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08001970 // Snapping also allows an app to precisely calculate
1971 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001972 nsecs_t bias = stats.vsyncPeriod / 2;
1973 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1974 nsecs_t snappedCompositeToPresentLatency =
1975 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001976
David Sodman99974d22017-11-28 12:04:33 -08001977 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001978 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1979 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001980 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001981}
1982
David Sodman2b406362017-12-15 13:33:47 -08001983void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001984{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001985 ATRACE_CALL();
1986 ALOGV("postComposition");
1987
Brian Anderson3546a3f2016-07-14 11:51:14 -07001988 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001989 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001990 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001991 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001992 }
1993
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001994 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001995 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001996
David Sodman73beded2017-11-15 11:56:06 -08001997 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001998 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08001999 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002000 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002001 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2002 ->getRenderSurface()
2003 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002004 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002005 } else {
2006 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2007 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002008
David Sodman73beded2017-11-15 11:56:06 -08002009 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002010 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2011 mPreviousPresentFences[0] = displayDevice
2012 ? getHwComposer().getPresentFence(*displayDevice->getId())
2013 : Fence::NO_FENCE;
2014 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002015 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002016
Ana Krulece588e312018-09-18 12:32:24 -07002017 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002018 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002019
Lloyd Piqueab039b52019-02-13 14:22:42 -08002020 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2021 // be sampled a little later than when we started doing work for this frame,
2022 // but that should be okay since updateCompositorTiming has snapping logic.
2023 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2024 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002025 CompositorTiming compositorTiming;
2026 {
David Sodman99974d22017-11-28 12:04:33 -08002027 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2028 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002029 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002030
Robert Carr2047fae2016-11-28 14:09:09 -08002031 mDrawingState.traverseInZOrder([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002032 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2033 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002034 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002035 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002036 }
Robert Carr2047fae2016-11-28 14:09:09 -08002037 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002038
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002039 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002040 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002041 }
2042
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002043 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002044 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2045 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002046 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002047 }
2048 }
2049
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002050 if (mAnimCompositionPending) {
2051 mAnimCompositionPending = false;
2052
Brian Anderson4e606e32017-03-16 15:34:57 -07002053 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002054 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002055 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002056 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002057 // The HWC doesn't support present fences, so use the refresh
2058 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002059 const nsecs_t presentTime =
2060 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002061 mAnimFrameTracker.setActualPresentTime(presentTime);
2062 }
2063 mAnimFrameTracker.advanceFrame();
2064 }
Dan Stozab90cf072015-03-05 11:05:59 -08002065
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002066 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002067 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002068 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002069 }
2070
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002071 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002072
Lloyd Pique32cbe282018-10-19 13:09:22 -07002073 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2074 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002075 return;
2076 }
2077
2078 nsecs_t currentTime = systemTime();
2079 if (mHasPoweredOff) {
2080 mHasPoweredOff = false;
2081 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002082 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002083 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002084 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2085 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002086 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002087 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002088 }
David Sodman4a36e932017-11-07 14:29:47 -08002089 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002090 }
David Sodman4a36e932017-11-07 14:29:47 -08002091 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002092
2093 {
2094 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002095 if (mTexturePool.size() < mTexturePoolSize) {
2096 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002097 const size_t offset = mTexturePool.size();
2098 mTexturePool.resize(mTexturePoolSize);
2099 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2100 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002101 } else if (mTexturePool.size() > mTexturePoolSize) {
2102 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2103 const size_t offset = mTexturePoolSize;
2104 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2105 mTexturePool.resize(mTexturePoolSize);
2106 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002107 }
2108 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002109
Ady Abrahambe0f9482019-04-24 15:41:53 -07002110 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002111 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002112
Kevin DuBois413287f2019-02-25 08:46:47 -08002113 if (mLumaSampling && mRegionSamplingThread) {
2114 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002115 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002116
2117 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2118 // side-effect of getTotalSize(), so we check that again here
2119 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002120 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002121 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2122 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002123}
2124
Vishnu Nair4351ad52019-02-11 14:13:02 -08002125void SurfaceFlinger::computeLayerBounds() {
2126 for (const auto& pair : mDisplays) {
2127 const auto& displayDevice = pair.second;
2128 const auto display = displayDevice->getCompositionDisplay();
2129 for (const auto& layer : mDrawingState.layersSortedByZ) {
2130 // only consider the layers on the given layer stack
2131 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002132 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002133 }
2134
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002135 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2136 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002137 }
2138 }
2139}
2140
David Sodmanfa9b2af2017-12-24 13:28:59 -08002141void SurfaceFlinger::postFrame()
2142{
2143 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002144 const auto display = getDefaultDisplayDeviceLocked();
2145 if (display && getHwComposer().isConnected(*display->getId())) {
2146 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002147 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2148 logFrameStats();
2149 }
2150 }
2151}
2152
Mathias Agopian87baae12012-07-31 12:38:26 -07002153void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002154{
Mathias Agopian841cde52012-03-01 15:44:37 -08002155 ATRACE_CALL();
2156
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002157 // here we keep a copy of the drawing state (that is the state that's
2158 // going to be overwritten by handleTransactionLocked()) outside of
2159 // mStateLock so that the side-effects of the State assignment
2160 // don't happen with mStateLock held (which can cause deadlocks).
2161 State drawingState(mDrawingState);
2162
Mathias Agopianca4d3602011-05-19 15:38:14 -07002163 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002164 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002165
Mathias Agopianca4d3602011-05-19 15:38:14 -07002166 // Here we're guaranteed that some transaction flags are set
2167 // so we can call handleTransactionLocked() unconditionally.
2168 // We call getTransactionFlags(), which will also clear the flags,
2169 // with mStateLock held to guarantee that mCurrentState won't change
2170 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002171
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002172 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002173 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002174 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002175
Mathias Agopianca4d3602011-05-19 15:38:14 -07002176 mDebugInTransaction = 0;
2177 invalidateHwcGeometry();
2178 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002179}
2180
Lloyd Piqueba04e622017-12-14 17:11:26 -08002181void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2182 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002183 const std::optional<DisplayIdentificationInfo> info =
2184 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002185
Dominik Laskowski075d3172018-05-24 15:50:06 -07002186 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002187 continue;
2188 }
2189
Lloyd Piqueba04e622017-12-14 17:11:26 -08002190 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002191 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002192 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002193 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2194 initScheduler(info->id);
2195 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002196 mPhysicalDisplayTokens[info->id] = new BBinder();
2197 DisplayDeviceState state;
2198 state.displayId = info->id;
2199 state.isSecure = true; // All physical displays are currently considered secure.
2200 state.displayName = info->name;
2201 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2202 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002203 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002204 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002205 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002206
Dominik Laskowski075d3172018-05-24 15:50:06 -07002207 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2208 if (index >= 0) {
2209 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2210 mInterceptor->saveDisplayDeletion(state.sequenceId);
2211 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002212 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002213 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002214 }
2215
2216 processDisplayChangesLocked();
2217 }
2218
2219 mPendingHotplugEvents.clear();
2220}
2221
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002222void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002223 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2224 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002225}
2226
Lloyd Pique99d3da52018-01-22 17:48:03 -08002227sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002228 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002229 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002230 const sp<IGraphicBufferProducer>& producer) {
2231 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002232 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002233 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002234 creationArgs.isSecure = state.isSecure;
2235 creationArgs.displaySurface = dispSurface;
2236 creationArgs.hasWideColorGamut = false;
2237 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002238 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002239
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002240 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002241 creationArgs.isPrimary = isInternalDisplay;
2242
2243 if (useColorManagement && displayId) {
2244 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002245 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002246 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002247 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002248 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002249
Dominik Laskowski7e045462018-05-30 13:02:02 -07002250 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002251 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002252 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002253 }
tangrobin6753a022018-08-10 10:58:54 +08002254 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002255
Dominik Laskowski075d3172018-05-24 15:50:06 -07002256 if (displayId) {
2257 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002258 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002259 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002260 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002261
Lloyd Pique90c115d2018-09-18 21:39:42 -07002262 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002263 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002264 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002265
Lloyd Pique99d3da52018-01-22 17:48:03 -08002266 // Make sure that composition can never be stalled by a virtual display
2267 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002268 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002269 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002270 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2271 }
2272
Dominik Laskowski718f9602019-11-09 20:01:35 -08002273 creationArgs.physicalOrientation =
2274 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002275
Lloyd Pique99d3da52018-01-22 17:48:03 -08002276 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002277 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002278
Lloyd Pique90c115d2018-09-18 21:39:42 -07002279 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002280
2281 if (maxFrameBufferAcquiredBuffers >= 3) {
2282 nativeWindowSurface->preallocateBuffers();
2283 }
2284
2285 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002286 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002287 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002288 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002289 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002290 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002291 display->getCompositionDisplay()->setColorProfile(
2292 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2293 RenderIntent::COLORIMETRIC,
2294 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002295 if (!state.isVirtual()) {
2296 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002297 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2298 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002299 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002300
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002301 display->setLayerStack(state.layerStack);
2302 display->setProjection(state.orientation, state.viewport, state.frame);
2303 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002304
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002305 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002306}
2307
Lloyd Pique347200f2017-12-14 17:00:15 -08002308void SurfaceFlinger::processDisplayChangesLocked() {
2309 // here we take advantage of Vector's copy-on-write semantics to
2310 // improve performance by skipping the transaction entirely when
2311 // know that the lists are identical
2312 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2313 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2314 if (!curr.isIdenticalTo(draw)) {
2315 mVisibleRegionsDirty = true;
2316 const size_t cc = curr.size();
2317 size_t dc = draw.size();
2318
2319 // find the displays that were removed
2320 // (ie: in drawing state but not in current state)
2321 // also handle displays that changed
2322 // (ie: displays that are in both lists)
2323 for (size_t i = 0; i < dc;) {
2324 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2325 if (j < 0) {
2326 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002327 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002328 // Save display ID before disconnecting.
2329 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002330 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002331
2332 if (!display->isVirtual()) {
2333 LOG_ALWAYS_FATAL_IF(!displayId);
2334 dispatchDisplayHotplugEvent(displayId->value, false);
2335 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002336 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002337
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002338 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002339 } else {
2340 // this display is in both lists. see if something changed.
2341 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002342 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002343 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2344 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2345 if (state_binder != draw_binder) {
2346 // changing the surface is like destroying and
2347 // recreating the DisplayDevice, so we just remove it
2348 // from the drawing state, so that it get re-added
2349 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002350 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002351 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002352 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002353 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002354 mDrawingState.displays.removeItemsAt(i);
2355 dc--;
2356 // at this point we must loop to the next item
2357 continue;
2358 }
2359
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002360 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002361 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002362 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002363 }
2364 if ((state.orientation != draw[i].orientation) ||
2365 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002366 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002367 }
2368 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002369 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002370 }
2371 }
2372 }
2373 ++i;
2374 }
2375
2376 // find displays that were added
2377 // (ie: in current state but not in drawing state)
2378 for (size_t i = 0; i < cc; i++) {
2379 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2380 const DisplayDeviceState& state(curr[i]);
2381
Lloyd Pique542307f2018-10-19 13:24:08 -07002382 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002383 sp<IGraphicBufferProducer> producer;
2384 sp<IGraphicBufferProducer> bqProducer;
2385 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002386 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002387
Dominik Laskowski075d3172018-05-24 15:50:06 -07002388 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002389 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002390 // Virtual displays without a surface are dormant:
2391 // they have external state (layer stack, projection,
2392 // etc.) but no internal state (i.e. a DisplayDevice).
2393 if (state.surface != nullptr) {
2394 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002395 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002396 int width = 0;
2397 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2398 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2399 int height = 0;
2400 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2401 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2402 int intFormat = 0;
2403 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2404 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002405 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002406
Dominik Laskowski075d3172018-05-24 15:50:06 -07002407 displayId =
2408 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002409 }
2410
2411 // TODO: Plumb requested format back up to consumer
2412
2413 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002414 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002415 bqProducer, bqConsumer,
2416 state.displayName);
2417
2418 dispSurface = vds;
2419 producer = vds;
2420 }
2421 } else {
2422 ALOGE_IF(state.surface != nullptr,
2423 "adding a supported display, but rendering "
2424 "surface is provided (%p), ignoring it",
2425 state.surface.get());
2426
Dominik Laskowski075d3172018-05-24 15:50:06 -07002427 displayId = state.displayId;
2428 LOG_ALWAYS_FATAL_IF(!displayId);
2429 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002430 producer = bqProducer;
2431 }
2432
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002433 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002434 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002435 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002436 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002437 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002438 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002439 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002440 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002441 }
2442 }
2443 }
2444 }
2445 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002446
2447 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002448}
2449
Mathias Agopian87baae12012-07-31 12:38:26 -07002450void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002451{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002452 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2453
Dan Stoza7dde5992015-05-22 09:51:44 -07002454 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002455 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2456 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002457 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002458
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002459 /*
2460 * Traversal of the children
2461 * (perform the transaction for each of them if needed)
2462 */
2463
Marissa Wall06255332019-03-27 13:48:27 -07002464 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002465 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002466 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002467 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002468
2469 const uint32_t flags = layer->doTransaction(0);
2470 if (flags & Layer::eVisibleRegion)
2471 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002472
2473 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002474 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002475 }
Robert Carr2047fae2016-11-28 14:09:09 -08002476 });
Marissa Wall06255332019-03-27 13:48:27 -07002477 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002478 }
2479
2480 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002481 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482 */
2483
Mathias Agopiane57f2922012-08-09 16:29:12 -07002484 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002485 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002486 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002487 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002488
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002489 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002490 // The transform hint might have changed for some layers
2491 // (either because a display has changed, or because a layer
2492 // as changed).
2493 //
2494 // Walk through all the layers in currentLayers,
2495 // and update their transform hint.
2496 //
2497 // If a layer is visible only on a single display, then that
2498 // display is used to calculate the hint, otherwise we use the
2499 // default display.
2500 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002501 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002502 // the hint is set before we acquire a buffer from the surface texture.
2503 //
2504 // NOTE: layer transactions have taken place already, so we use their
2505 // drawing state. However, SurfaceFlinger's own transaction has not
2506 // happened yet, so we must use the current state layer list
2507 // (soon to become the drawing state list).
2508 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002509 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002510 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002511 bool first = true;
2512 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002513 // NOTE: we rely on the fact that layers are sorted by
2514 // layerStack first (so we don't have to traverse the list
2515 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002516 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002517 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002518 currentlayerStack = layerStack;
2519 // figure out if this layerstack is mirrored
2520 // (more than one display) if so, pick the default display,
2521 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002522 hintDisplay = nullptr;
2523 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002524 if (display->getCompositionDisplay()
2525 ->belongsInOutput(layer->getLayerStack(),
2526 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002527 if (hintDisplay) {
2528 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002529 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002530 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002531 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002532 }
2533 }
2534 }
2535 }
Chet Haase91d25932013-04-11 15:24:55 -07002536
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002537 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002538 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2539 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002540
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002541 // could be null when this layer is using a layerStack
2542 // that is not visible on any display. Also can occur at
2543 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002544 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002545 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002546
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002547 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002548 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002549 if (hintDisplay) {
2550 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002551 }
Robert Carr2047fae2016-11-28 14:09:09 -08002552
2553 first = false;
2554 });
Mathias Agopian84300952012-11-21 16:02:13 -08002555 }
2556
2557
Mathias Agopian3559b072012-08-15 13:46:03 -07002558 /*
2559 * Perform our own transaction if needed
2560 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002561
2562 if (mLayersAdded) {
2563 mLayersAdded = false;
2564 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002565 mVisibleRegionsDirty = true;
2566 }
2567
2568 // some layers might have been removed, so
2569 // we need to update the regions they're exposing.
2570 if (mLayersRemoved) {
2571 mLayersRemoved = false;
2572 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002573 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002574 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002575 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002576 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002577 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002578 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002579 }
Robert Carr2047fae2016-11-28 14:09:09 -08002580 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581 }
2582
Vishnu Nairec0ab382019-02-13 15:32:56 -08002583 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002584 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002585}
2586
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002587void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002588 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002589 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002590 return;
2591 }
2592
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002593 if (mVisibleRegionsDirty || mInputInfoChanged) {
2594 mInputInfoChanged = false;
2595 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002596 } else if (mInputWindowCommands.syncInputWindows) {
2597 // If the caller requested to sync input windows, but there are no
2598 // changes to input windows, notify immediately.
2599 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002600 }
2601
Arthur Hung6cbb9752019-09-05 16:38:18 +08002602 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002603}
2604
2605void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002606 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002607
2608 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2609 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002610 // When calculating the screen bounds we ignore the transparent region since it may
2611 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002612 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002613 }
2614 });
chaviw291d88a2019-02-14 10:33:58 -08002615
2616 mInputFlinger->setInputWindows(inputHandles,
2617 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2618 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002619}
2620
Vishnu Nairec0ab382019-02-13 15:32:56 -08002621void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002622 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002623 mPendingInputWindowCommands.clear();
2624}
2625
Riley Andrews03414a12014-07-01 14:22:59 -07002626void SurfaceFlinger::updateCursorAsync()
2627{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002628 compositionengine::CompositionRefreshArgs refreshArgs;
2629 for (const auto& [_, display] : mDisplays) {
2630 if (display->getId()) {
2631 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002632 }
2633 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002634
2635 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002636}
2637
Ady Abraham2139f732019-11-13 18:56:40 -08002638void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
2639 Scheduler::ConfigEvent event) {
2640 Mutex::Autolock lock(mStateLock);
2641 changeRefreshRateLocked(refreshRate, event);
2642}
2643
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002644void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2645 if (mScheduler) {
2646 // In practice it's not allowed to hotplug in/out the primary display once it's been
2647 // connected during startup, but some tests do it, so just warn and return.
2648 ALOGW("Can't re-init scheduler");
2649 return;
2650 }
2651
Ady Abraham2139f732019-11-13 18:56:40 -08002652 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002653 mRefreshRateConfigs =
2654 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2655 getHwComposer().getConfigs(
2656 primaryDisplayId),
2657 currentConfig);
2658 mRefreshRateStats =
2659 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2660 currentConfig, HWC_POWER_MODE_OFF);
2661 mRefreshRateStats->setConfigMode(currentConfig);
2662
Ady Abraham9e16a482019-12-03 17:19:41 -08002663 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2664
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002665 // start the EventThread
2666 mScheduler =
2667 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002668 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002669 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002670 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002671 impl::EventThread::InterceptVSyncsCallback());
2672 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002673 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002674 [this](nsecs_t timestamp) {
2675 mInterceptor->saveVSyncEvent(timestamp);
2676 });
2677
2678 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2679 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002680 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002681
2682 mRegionSamplingThread =
2683 new RegionSamplingThread(*this, *mScheduler,
2684 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002685 // Dispatch a config change request for the primary display on scheduler
2686 // initialization, so that the EventThreads always contain a reference to a
2687 // prior configuration.
2688 //
2689 // This is a bit hacky, but this avoids a back-pointer into the main SF
2690 // classes from EventThread, and there should be no run-time binder cost
2691 // anyway since there are no connected apps at this point.
2692 const nsecs_t vsyncPeriod =
2693 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2694 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2695 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002696}
2697
Mathias Agopian4fec8732012-06-29 14:12:52 -07002698void SurfaceFlinger::commitTransaction()
2699{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002700 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002701
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002702 mTransactionPending = false;
2703 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002704 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002705}
2706
Lloyd Pique58e24a32019-08-01 15:50:14 -07002707void SurfaceFlinger::commitTransactionLocked() {
2708 if (!mLayersPendingRemoval.isEmpty()) {
2709 // Notify removed layers now that they can't be drawn from
2710 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002711 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002712
2713 // Ensure any buffers set to display on any children are released.
2714 if (l->isRemovedFromCurrentState()) {
2715 l->latchAndReleaseBuffer();
2716 }
2717
2718 // If the layer has been removed and has no parent, then it will not be reachable
2719 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2720 // ensure we can copy its current to drawing state.
2721 if (!l->getParent()) {
2722 mOffscreenLayers.emplace(l.get());
2723 }
2724 }
2725 mLayersPendingRemoval.clear();
2726 }
2727
2728 // If this transaction is part of a window animation then the next frame
2729 // we composite should be considered an animation as well.
2730 mAnimCompositionPending = mAnimTransactionPending;
2731
2732 mDrawingState = mCurrentState;
2733 // clear the "changed" flags in current state
2734 mCurrentState.colorMatrixChanged = false;
2735
2736 mDrawingState.traverseInZOrder([&](Layer* layer) {
2737 layer->commitChildList();
2738
2739 // If the layer can be reached when traversing mDrawingState, then the layer is no
2740 // longer offscreen. Remove the layer from the offscreenLayer set.
2741 if (mOffscreenLayers.count(layer)) {
2742 mOffscreenLayers.erase(layer);
2743 }
2744 });
2745
2746 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002747 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002748}
2749
Nataniel Borges2b796da2019-02-15 13:32:18 -08002750void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2751 if (mTracingEnabledChanged) {
2752 mTracingEnabled = mTracing.isEnabled();
2753 mTracingEnabledChanged = false;
2754 }
2755
2756 // Synchronize with Tracing thread
2757 std::unique_lock<std::mutex> lock;
2758 if (mTracingEnabled) {
2759 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2760 }
2761
2762 lockedOperation();
2763
2764 // Synchronize with Tracing thread
2765 if (mTracingEnabled) {
2766 lock.unlock();
2767 }
2768}
2769
chaviw74d90ad2019-04-26 14:45:26 -07002770void SurfaceFlinger::commitOffscreenLayers() {
2771 for (Layer* offscreenLayer : mOffscreenLayers) {
2772 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2773 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2774 if (!trFlags) return;
2775
2776 layer->doTransaction(0);
2777 layer->commitChildList();
2778 });
2779 }
2780}
2781
Chia-I Wuab0c3192017-08-01 11:29:00 -07002782void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002783 for (const auto& [token, displayDevice] : mDisplays) {
2784 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002785 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002786 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002787 }
2788 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002789}
2790
Dan Stoza6b9454d2014-11-07 16:00:59 -08002791bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792{
Ady Abraham09bd3922019-04-08 10:44:56 -07002793 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002794 ALOGV("handlePageFlip");
2795
Brian Andersond6927fb2016-07-23 23:37:30 -07002796 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002797
Mathias Agopian4fec8732012-06-29 14:12:52 -07002798 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002799 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002800 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002801
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002802 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2803
Eric Penner51c59cd2014-07-28 19:51:58 -07002804 // Store the set of layers that need updates. This set must not change as
2805 // buffers are being latched, as this could result in a deadlock.
2806 // Example: Two producers share the same command stream and:
2807 // 1.) Layer 0 is latched
2808 // 2.) Layer 0 gets a new frame
2809 // 2.) Layer 1 gets a new frame
2810 // 3.) Layer 1 is latched.
2811 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2812 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002813 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002814 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002815 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002816 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002817 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002818 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002819 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002820 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002821 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002822 } else {
2823 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002824 }
Robert Carr2047fae2016-11-28 14:09:09 -08002825 });
2826
chaviw49a108c2019-08-12 11:23:06 -07002827 // The client can continue submitting buffers for offscreen layers, but they will not
2828 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2829 // layers to ensure dequeueBuffer doesn't block indefinitely.
2830 for (Layer* offscreenLayer : mOffscreenLayers) {
2831 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2832 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2833 }
2834
Lloyd Piquef2c79392018-12-20 16:23:33 -08002835 if (!mLayersWithQueuedFrames.empty()) {
2836 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2837 // writes to Layer current state. See also b/119481871
2838 Mutex::Autolock lock(mStateLock);
2839
2840 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002841 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002842 mLayersPendingRefresh.push_back(layer);
2843 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002844 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002845 if (layer->isBufferLatched()) {
2846 newDataLatched = true;
2847 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002848 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002849 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002850
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002851 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002852
2853 // If we will need to wake up at some time in the future to deal with a
2854 // queued frame that shouldn't be displayed during this vsync period, wake
2855 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002856 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002857 signalLayerUpdate();
2858 }
2859
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002860 // enter boot animation on first buffer latch
2861 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2862 ALOGI("Enter boot animation");
2863 mBootStage = BootStage::BOOTANIMATION;
2864 }
2865
chaviw74b03172019-08-19 11:09:03 -07002866 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2867
Dan Stoza6b9454d2014-11-07 16:00:59 -08002868 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002869 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002870}
2871
Mathias Agopianad456f92011-01-13 17:53:01 -08002872void SurfaceFlinger::invalidateHwcGeometry()
2873{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002874 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002875}
2876
Robert Carrc0df3122019-04-11 13:18:21 -07002877status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2878 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2879 const sp<IBinder>& parentHandle,
2880 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002881 // add this layer to the current state list
2882 {
2883 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002884 sp<Layer> parent;
2885 if (parentHandle != nullptr) {
2886 parent = fromHandle(parentHandle);
2887 if (parent == nullptr) {
2888 return NAME_NOT_FOUND;
2889 }
2890 } else {
2891 parent = parentLayer;
2892 }
2893
Robert Carr1f0a16a2016-10-24 16:27:39 -07002894 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002895 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002896 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002897 return NO_MEMORY;
2898 }
Robert Carrc0df3122019-04-11 13:18:21 -07002899
2900 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2901
Robert Carrb89ea9d2018-12-10 13:01:14 -08002902 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002903 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002904 } else if (parent == nullptr) {
2905 lbc->onRemovedFromCurrentState();
2906 } else if (parent->isRemovedFromCurrentState()) {
2907 parent->addChild(lbc);
2908 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002909 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002910 parent->addChild(lbc);
2911 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002912
Yiwei Zhang243b3782018-05-15 17:40:04 -07002913 if (gbc != nullptr) {
2914 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2915 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2916 mMaxGraphicBufferProducerListSize,
2917 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2918 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002919 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002920 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002921 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002922 }
2923
Mathias Agopian96f08192010-06-02 23:28:45 -07002924 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002925 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002926
Dan Stoza7d89d062015-04-30 13:29:25 -07002927 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002928}
2929
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002930uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002931 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002932}
2933
Mathias Agopian3f844832013-08-07 21:24:32 -07002934uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002935 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002936}
2937
Mathias Agopian3f844832013-08-07 21:24:32 -07002938uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002939 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002940}
2941
2942uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002943 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002944 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002945 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002946 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002947 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002948 }
2949 return old;
2950}
2951
Marissa Wall713b63f2018-10-17 15:42:43 -07002952bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002953 // to prevent onHandleDestroyed from being called while the lock is held,
2954 // we must keep a copy of the transactions (specifically the composer
2955 // states) around outside the scope of the lock
2956 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002957 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002958 {
2959 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002960
Valerie Haufce31b82019-04-30 16:41:14 -07002961 auto it = mTransactionQueues.begin();
2962 while (it != mTransactionQueues.end()) {
2963 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002964
Valerie Haufce31b82019-04-30 16:41:14 -07002965 while (!transactionQueue.empty()) {
2966 const auto& transaction = transactionQueue.front();
2967 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002968 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002969 transaction.states)) {
2970 setTransactionFlags(eTransactionFlushNeeded);
2971 break;
2972 }
2973 transactions.push_back(transaction);
2974 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2975 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002976 transaction.buffer, transaction.postTime,
2977 transaction.privileged, transaction.hasListenerCallbacks,
2978 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002979 transactionQueue.pop();
2980 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002981 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002982
Valerie Haufce31b82019-04-30 16:41:14 -07002983 if (transactionQueue.empty()) {
2984 it = mTransactionQueues.erase(it);
2985 mTransactionCV.broadcast();
2986 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002987 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002988 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002989 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002990 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002991 return flushedATransaction;
2992}
2993
2994bool SurfaceFlinger::transactionFlushNeeded() {
2995 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07002996}
2997
chaviwca27f252018-02-06 16:46:39 -08002998
Marissa Wall17b4e452018-12-26 16:32:34 -08002999bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003000 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003001 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003002 if (!useCachedExpectedPresentTime)
3003 populateExpectedPresentTime();
3004
3005 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003006 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3007 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3008 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3009 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3010 return false;
3011 }
3012
Marissa Wall713b63f2018-10-17 15:42:43 -07003013 for (const ComposerState& state : states) {
3014 const layer_state_t& s = state.state;
3015 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3016 continue;
3017 }
3018 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003019 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003020 }
3021 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003022 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003023}
3024
Valerie Hau9dab9732019-08-20 09:29:25 -07003025void SurfaceFlinger::setTransactionState(
3026 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3027 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3028 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3029 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003030 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003031
Valerie Haubc6ddb12019-03-08 11:10:15 -08003032 const int64_t postTime = systemTime();
3033
Robert Carr14167e02019-02-13 13:50:55 -08003034 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3035
Mathias Agopian698c0872011-06-28 19:09:31 -07003036 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003037
Marissa Wall713b63f2018-10-17 15:42:43 -07003038 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003039 auto itr = mTransactionQueues.find(applyToken);
3040 // if this is an animation frame, wait until prior animation frame has
3041 // been applied by SF
3042 if (flags & eAnimation) {
3043 while (itr != mTransactionQueues.end()) {
3044 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3045 if (CC_UNLIKELY(err != NO_ERROR)) {
3046 ALOGW_IF(err == TIMED_OUT,
3047 "setTransactionState timed out "
3048 "waiting for animation frame to apply");
3049 break;
3050 }
3051 itr = mTransactionQueues.find(applyToken);
3052 }
3053 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003054
3055 // Expected present time is computed and cached on invalidate, so it may be stale.
3056 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3057 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003058 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003059 uncacheBuffer, postTime, privileged,
3060 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003061 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003062 return;
3063 }
3064
Valerie Haubc6ddb12019-03-08 11:10:15 -08003065 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003066 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3067 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003068}
3069
Valerie Hau9dab9732019-08-20 09:29:25 -07003070void SurfaceFlinger::applyTransactionState(
3071 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3072 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3073 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3074 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3075 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003076 uint32_t transactionFlags = 0;
3077
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003078 if (flags & eAnimation) {
3079 // For window updates that are part of an animation we must wait for
3080 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003081 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003082 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003083 if (CC_UNLIKELY(err != NO_ERROR)) {
3084 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003085 // caller after a few seconds.
3086 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3087 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003088 mAnimTransactionPending = false;
3089 break;
3090 }
3091 }
3092 }
3093
chaviwca27f252018-02-06 16:46:39 -08003094 for (const DisplayState& display : displays) {
3095 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003096 }
3097
Valerie Hau9dab9732019-08-20 09:29:25 -07003098 // start and end registration for listeners w/ no surface so they can get their callback. Note
3099 // that listeners with SurfaceControls will start registration during setClientStateLocked
3100 // below.
3101 for (const auto& listener : listenerCallbacks) {
3102 mTransactionCompletedThread.startRegistration(listener);
3103 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003104 }
3105
Valerie Hau9dab9732019-08-20 09:29:25 -07003106 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003107 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003108 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003109 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3110 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003111 }
3112
Valerie Hau9dab9732019-08-20 09:29:25 -07003113 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003114 mTransactionCompletedThread.endRegistration(listenerCallback);
3115 }
3116
Marissa Walle2ffb422018-10-12 11:33:52 -07003117 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003118 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003119 mTransactionCompletedThread.sendCallbacks();
3120 }
3121 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003122
chaviw273171b2018-12-26 11:46:30 -08003123 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3124
Marissa Wall947d34e2019-03-29 14:03:53 -07003125 if (uncacheBuffer.isValid()) {
3126 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003127 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003128 }
3129
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003130 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3131 // anyway. This can be used as a flush mechanism for previous async transactions.
3132 // Empty animation transaction can be used to simulate back-pressure, so also force a
3133 // transaction for empty animation transactions.
3134 if (transactionFlags == 0 &&
3135 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003136 transactionFlags = eTransactionNeeded;
3137 }
3138
Marissa Wall06255332019-03-27 13:48:27 -07003139 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3140 // so we don't have to wake up again next frame to preform an uneeded traversal.
3141 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3142 transactionFlags = transactionFlags & (~eTraversalNeeded);
3143 mTraversalNeededMainThread = true;
3144 }
3145
Mathias Agopian386aa982011-11-07 21:58:03 -08003146 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003147 if (mInterceptor->isEnabled()) {
3148 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003149 }
Irvel468051e2016-06-13 16:44:44 -07003150
Mathias Agopian386aa982011-11-07 21:58:03 -08003151 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003152 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3153 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003154 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003155
3156 // if this is a synchronous transaction, wait for it to take effect
3157 // before returning.
3158 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003159 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003160 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003161 if (flags & eAnimation) {
3162 mAnimTransactionPending = true;
3163 }
chaviw4fe36852019-04-15 16:25:49 -07003164 if (mPendingInputWindowCommands.syncInputWindows) {
3165 mPendingSyncInputWindows = true;
3166 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003167
3168 // applyTransactionState can be called by either the main SF thread or by
3169 // another process through setTransactionState. While a given process may wish
3170 // to wait on synchronous transactions, the main SF thread should never
3171 // be blocked. Therefore, we only wait if isMainThread is false.
3172 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003173 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3174 if (CC_UNLIKELY(err != NO_ERROR)) {
3175 // just in case something goes wrong in SF, return to the
3176 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003177 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3178 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003179 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003180 break;
3181 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003182 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003183 }
3184}
3185
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003186uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3187 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3188 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003189
Mathias Agopiane57f2922012-08-09 16:29:12 -07003190 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003191 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3192
3193 const uint32_t what = s.what;
3194 if (what & DisplayState::eSurfaceChanged) {
3195 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3196 state.surface = s.surface;
3197 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003198 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003199 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003200 if (what & DisplayState::eLayerStackChanged) {
3201 if (state.layerStack != s.layerStack) {
3202 state.layerStack = s.layerStack;
3203 flags |= eDisplayTransactionNeeded;
3204 }
3205 }
3206 if (what & DisplayState::eDisplayProjectionChanged) {
3207 if (state.orientation != s.orientation) {
3208 state.orientation = s.orientation;
3209 flags |= eDisplayTransactionNeeded;
3210 }
3211 if (state.frame != s.frame) {
3212 state.frame = s.frame;
3213 flags |= eDisplayTransactionNeeded;
3214 }
3215 if (state.viewport != s.viewport) {
3216 state.viewport = s.viewport;
3217 flags |= eDisplayTransactionNeeded;
3218 }
3219 }
3220 if (what & DisplayState::eDisplaySizeChanged) {
3221 if (state.width != s.width) {
3222 state.width = s.width;
3223 flags |= eDisplayTransactionNeeded;
3224 }
3225 if (state.height != s.height) {
3226 state.height = s.height;
3227 flags |= eDisplayTransactionNeeded;
3228 }
3229 }
3230
Mathias Agopiane57f2922012-08-09 16:29:12 -07003231 return flags;
3232}
3233
Robert Carr14167e02019-02-13 13:50:55 -08003234bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003235 IPCThreadState* ipc = IPCThreadState::self();
3236 const int pid = ipc->getCallingPid();
3237 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003238 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003239 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003240 return false;
3241 }
3242 return true;
3243}
3244
Marissa Wall3dad52d2019-03-22 14:03:19 -07003245uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003246 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3247 bool privileged,
3248 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003249 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003250
Valerie Hau9dab9732019-08-20 09:29:25 -07003251 for (auto& listener : s.listeners) {
3252 // note that startRegistration will not re-register if the listener has
3253 // already be registered for a prior surface control
3254 mTransactionCompletedThread.startRegistration(listener);
3255 listenerCallbacks.insert(listener);
3256 }
3257
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003258 sp<Layer> layer = nullptr;
3259 if (s.surface) {
3260 layer = fromHandle(s.surface);
3261 } else {
3262 // The client may provide us a null handle. Treat it as if the layer was removed.
3263 ALOGW("Attempt to set client state with a null layer handle");
3264 }
chaviw8b3871a2017-11-01 17:41:01 -07003265 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003266 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003267 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003268 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003269 }
chaviw8b3871a2017-11-01 17:41:01 -07003270 return 0;
3271 }
3272
chaviw8b3871a2017-11-01 17:41:01 -07003273 uint32_t flags = 0;
3274
Garfield Tan8a3083e2018-12-03 13:21:07 -08003275 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003276
3277 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3278 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003279 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003280 layer->pushPendingState();
3281 }
3282
chaviw8b3871a2017-11-01 17:41:01 -07003283 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003284 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003285 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003286 }
chaviw8b3871a2017-11-01 17:41:01 -07003287 }
3288 if (what & layer_state_t::eLayerChanged) {
3289 // NOTE: index needs to be calculated before we update the state
3290 const auto& p = layer->getParent();
3291 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003292 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003293 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003294 mCurrentState.layersSortedByZ.removeAt(idx);
3295 mCurrentState.layersSortedByZ.add(layer);
3296 // we need traversal (state changed)
3297 // AND transaction (list changed)
3298 flags |= eTransactionNeeded|eTraversalNeeded;
3299 }
chaviw8b3871a2017-11-01 17:41:01 -07003300 } else {
3301 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003302 flags |= eTransactionNeeded|eTraversalNeeded;
3303 }
3304 }
chaviw8b3871a2017-11-01 17:41:01 -07003305 }
3306 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003307 // NOTE: index needs to be calculated before we update the state
3308 const auto& p = layer->getParent();
3309 if (p == nullptr) {
3310 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3311 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3312 mCurrentState.layersSortedByZ.removeAt(idx);
3313 mCurrentState.layersSortedByZ.add(layer);
3314 // we need traversal (state changed)
3315 // AND transaction (list changed)
3316 flags |= eTransactionNeeded|eTraversalNeeded;
3317 }
3318 } else {
3319 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3320 flags |= eTransactionNeeded|eTraversalNeeded;
3321 }
chaviw8b3871a2017-11-01 17:41:01 -07003322 }
3323 }
3324 if (what & layer_state_t::eSizeChanged) {
3325 if (layer->setSize(s.w, s.h)) {
3326 flags |= eTraversalNeeded;
3327 }
3328 }
3329 if (what & layer_state_t::eAlphaChanged) {
3330 if (layer->setAlpha(s.alpha))
3331 flags |= eTraversalNeeded;
3332 }
3333 if (what & layer_state_t::eColorChanged) {
3334 if (layer->setColor(s.color))
3335 flags |= eTraversalNeeded;
3336 }
Peiyong Lind3788632018-09-18 16:01:31 -07003337 if (what & layer_state_t::eColorTransformChanged) {
3338 if (layer->setColorTransform(s.colorTransform)) {
3339 flags |= eTraversalNeeded;
3340 }
3341 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003342 if (what & layer_state_t::eBackgroundColorChanged) {
3343 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3344 flags |= eTraversalNeeded;
3345 }
3346 }
chaviw8b3871a2017-11-01 17:41:01 -07003347 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003348 // TODO: b/109894387
3349 //
3350 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3351 // rotation. To see the problem observe that if we have a square parent, and a child
3352 // of the same size, then we rotate the child 45 degrees around it's center, the child
3353 // must now be cropped to a non rectangular 8 sided region.
3354 //
3355 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3356 // private API, and the WindowManager only uses rotation in one case, which is on a top
3357 // level layer in which cropping is not an issue.
3358 //
3359 // However given that abuse of rotation matrices could lead to surfaces extending outside
3360 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3361 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3362 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003363 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003364 flags |= eTraversalNeeded;
3365 }
3366 if (what & layer_state_t::eTransparentRegionChanged) {
3367 if (layer->setTransparentRegionHint(s.transparentRegion))
3368 flags |= eTraversalNeeded;
3369 }
3370 if (what & layer_state_t::eFlagsChanged) {
3371 if (layer->setFlags(s.flags, s.mask))
3372 flags |= eTraversalNeeded;
3373 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003374 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003375 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003376 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003377 if (what & layer_state_t::eCornerRadiusChanged) {
3378 if (layer->setCornerRadius(s.cornerRadius))
3379 flags |= eTraversalNeeded;
3380 }
chaviw8b3871a2017-11-01 17:41:01 -07003381 if (what & layer_state_t::eLayerStackChanged) {
3382 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3383 // We only allow setting layer stacks for top level layers,
3384 // everything else inherits layer stack from its parent.
3385 if (layer->hasParent()) {
3386 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003387 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003388 } else if (idx < 0) {
3389 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003390 "that also does not appear in the top level layer list. Something"
3391 " has gone wrong.",
3392 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003393 } else if (layer->setLayerStack(s.layerStack)) {
3394 mCurrentState.layersSortedByZ.removeAt(idx);
3395 mCurrentState.layersSortedByZ.add(layer);
3396 // we need traversal (state changed)
3397 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003398 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003399 }
3400 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003401 if (what & layer_state_t::eDeferTransaction_legacy) {
3402 if (s.barrierHandle_legacy != nullptr) {
3403 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3404 } else if (s.barrierGbp_legacy != nullptr) {
3405 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003406 if (authenticateSurfaceTextureLocked(gbp)) {
3407 const auto& otherLayer =
3408 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003409 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003410 } else {
3411 ALOGE("Attempt to defer transaction to to an"
3412 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003413 }
3414 }
chaviw8b3871a2017-11-01 17:41:01 -07003415 // We don't trigger a traversal here because if no other state is
3416 // changed, we don't want this to cause any more work
3417 }
chaviw8b3871a2017-11-01 17:41:01 -07003418 if (what & layer_state_t::eReparentChildren) {
3419 if (layer->reparentChildren(s.reparentHandle)) {
3420 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003421 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003422 }
chaviw8b3871a2017-11-01 17:41:01 -07003423 if (what & layer_state_t::eDetachChildren) {
3424 layer->detachChildren();
3425 }
3426 if (what & layer_state_t::eOverrideScalingModeChanged) {
3427 layer->setOverrideScalingMode(s.overrideScalingMode);
3428 // 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 }
Marissa Wall61c58622018-07-18 10:12:20 -07003431 if (what & layer_state_t::eTransformChanged) {
3432 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3433 }
3434 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3435 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3436 flags |= eTraversalNeeded;
3437 }
3438 if (what & layer_state_t::eCropChanged) {
3439 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3440 }
Marissa Wall861616d2018-10-22 12:52:23 -07003441 if (what & layer_state_t::eFrameChanged) {
3442 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3443 }
Marissa Wall61c58622018-07-18 10:12:20 -07003444 if (what & layer_state_t::eAcquireFenceChanged) {
3445 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3446 }
3447 if (what & layer_state_t::eDataspaceChanged) {
3448 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3449 }
3450 if (what & layer_state_t::eHdrMetadataChanged) {
3451 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3452 }
3453 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3454 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3455 }
3456 if (what & layer_state_t::eApiChanged) {
3457 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3458 }
3459 if (what & layer_state_t::eSidebandStreamChanged) {
3460 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3461 }
Robert Carr720e5062018-07-30 17:45:14 -07003462 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003463 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003464 layer->setInputInfo(s.inputInfo);
3465 flags |= eTraversalNeeded;
3466 } else {
3467 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3468 }
Robert Carr720e5062018-07-30 17:45:14 -07003469 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003470 if (what & layer_state_t::eMetadataChanged) {
3471 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3472 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003473 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3474 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3475 flags |= eTraversalNeeded;
3476 }
3477 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003478 if (what & layer_state_t::eShadowRadiusChanged) {
3479 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3480 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003481 // This has to happen after we reparent children because when we reparent to null we remove
3482 // child layers from current state and remove its relative z. If the children are reparented in
3483 // the same transaction, then we have to make sure we reparent the children first so we do not
3484 // lose its relative z order.
3485 if (what & layer_state_t::eReparent) {
3486 bool hadParent = layer->hasParent();
3487 if (layer->reparent(s.parentHandleForChild)) {
3488 if (!hadParent) {
3489 mCurrentState.layersSortedByZ.remove(layer);
3490 }
3491 flags |= eTransactionNeeded | eTraversalNeeded;
3492 }
3493 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003494 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003495 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3496 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003497 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3498 }
3499 }
Marissa Wall78b72202019-03-15 14:58:34 -07003500 bool bufferChanged = what & layer_state_t::eBufferChanged;
3501 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3502 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003503 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003504 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003505 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3506 if (success) {
3507 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3508 success = ClientCache::getInstance()
3509 .registerErasedRecipient(s.cachedBuffer,
3510 wp<ClientCache::ErasedRecipient>(this));
3511 if (!success) {
3512 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3513 }
3514 }
Marissa Wall78b72202019-03-15 14:58:34 -07003515 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003516 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003517 } else if (bufferChanged) {
3518 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003519 }
Marissa Wall78b72202019-03-15 14:58:34 -07003520 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003521 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003522 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003523 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003524 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003525 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3526 // Do not put anything that updates layer state or modifies flags after
3527 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003528 return flags;
3529}
3530
chaviw273171b2018-12-26 11:46:30 -08003531uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3532 uint32_t flags = 0;
3533 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3534 flags |= eTraversalNeeded;
3535 }
3536
chaviwa911b102019-02-14 10:18:33 -08003537 if (inputWindowCommands.syncInputWindows) {
3538 flags |= eTraversalNeeded;
3539 }
3540
Vishnu Nairec0ab382019-02-13 15:32:56 -08003541 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003542 return flags;
3543}
3544
chaviwfe94a222019-08-21 13:52:59 -07003545status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3546 sp<IBinder>* outHandle) {
3547 if (!mirrorFromHandle) {
3548 return NAME_NOT_FOUND;
3549 }
3550
3551 sp<Layer> mirrorLayer;
3552 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003553 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003554
3555 {
3556 Mutex::Autolock _l(mStateLock);
3557 mirrorFrom = fromHandle(mirrorFromHandle);
3558 if (!mirrorFrom) {
3559 return NAME_NOT_FOUND;
3560 }
3561
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003562 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3563 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003564 if (result != NO_ERROR) {
3565 return result;
3566 }
3567
3568 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3569 }
3570
3571 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3572}
3573
Marissa Wall2d814fb2019-04-09 18:52:57 +00003574status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3575 uint32_t h, PixelFormat format, uint32_t flags,
3576 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003577 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003578 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3579 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003580 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003581 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003582 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003583 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003584 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003585
Robert Carrc0df3122019-04-11 13:18:21 -07003586 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3587 "Expected only one of parentLayer or parentHandle to be non-null. "
3588 "Programmer error?");
3589
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003590 status_t result = NO_ERROR;
3591
3592 sp<Layer> layer;
3593
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003594 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003595
Evan Roskya1f1e152019-01-24 16:17:46 -08003596 bool primaryDisplayOnly = false;
3597
3598 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3599 // TODO b/64227542
3600 if (metadata.has(METADATA_WINDOW_TYPE)) {
3601 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3602 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003603 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003604 primaryDisplayOnly = true;
3605 }
3606 }
3607
Mathias Agopian3165cc22012-08-08 19:42:09 -07003608 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003609 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003610 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3611 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003612
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003613 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003614 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003615 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003616 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003617 break;
chaviw13fdc492017-06-27 12:40:18 -07003618 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003619 // check if buffer size is set for color layer.
3620 if (w > 0 || h > 0) {
3621 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3622 int(w), int(h));
3623 return BAD_VALUE;
3624 }
3625
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003626 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3627 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003628 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003629 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003630 // check if buffer size is set for container layer.
3631 if (w > 0 || h > 0) {
3632 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3633 int(w), int(h));
3634 return BAD_VALUE;
3635 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003636 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3637 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003638 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003639 default:
3640 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003641 break;
3642 }
3643
Dan Stoza7d89d062015-04-30 13:29:25 -07003644 if (result != NO_ERROR) {
3645 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003646 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003647
Evan Roskya1f1e152019-01-24 16:17:46 -08003648 if (primaryDisplayOnly) {
3649 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003650 }
3651
Robert Carrb89ea9d2018-12-10 13:01:14 -08003652 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003653 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3654 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003655 if (result != NO_ERROR) {
3656 return result;
3657 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003658 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003659
3660 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003661 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003662}
3663
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003664std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3665 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003666
3667 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003668 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003669
Dan Stoza436ccf32018-06-21 12:10:12 -07003670 // Grab the state lock since we're accessing mCurrentState
3671 Mutex::Autolock lock(mStateLock);
3672
Cody Northropbc755282017-03-31 12:00:08 -06003673 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003674 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003675 while (matchFound) {
3676 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003677 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003678 if (layer->getName() == uniqueName) {
3679 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003680 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003681 }
3682 });
3683 }
3684
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003685 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003686 return uniqueName;
3687}
3688
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003689status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003690 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003691 LayerMetadata metadata, PixelFormat& format,
3692 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003693 sp<IGraphicBufferProducer>* gbp,
3694 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003695 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003696 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003697 case PIXEL_FORMAT_TRANSPARENT:
3698 case PIXEL_FORMAT_TRANSLUCENT:
3699 format = PIXEL_FORMAT_RGBA_8888;
3700 break;
3701 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003702 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003703 break;
3704 }
3705
chaviwb4c6e582019-08-16 14:35:07 -07003706 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003707 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003708 args.textureName = getNewTexture();
3709 {
3710 // Grab the SF state lock during this since it's the only safe way to access
3711 // RenderEngine when creating a BufferLayerConsumer
3712 // TODO: Check if this lock is still needed here
3713 Mutex::Autolock lock(mStateLock);
3714 layer = getFactory().createBufferQueueLayer(args);
3715 }
3716
Marissa Wallfd668622018-05-10 10:21:13 -07003717 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003718 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003719 *handle = layer->getHandle();
3720 *gbp = layer->getProducer();
3721 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003722 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003723
Marissa Wallfd668622018-05-10 10:21:13 -07003724 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003725 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003726}
3727
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003728status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003729 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003730 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003731 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003732 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003733 args.displayDevice = getDefaultDisplayDevice();
3734 args.textureName = getNewTexture();
3735 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003736 if (outTransformHint) {
3737 *outTransformHint = layer->getTransformHint();
3738 }
Marissa Wall61c58622018-07-18 10:12:20 -07003739 *handle = layer->getHandle();
3740 *outLayer = layer;
3741
3742 return NO_ERROR;
3743}
3744
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003745status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003746 uint32_t h, uint32_t flags, LayerMetadata metadata,
3747 sp<IBinder>* handle, sp<Layer>* outLayer) {
3748 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003749 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003750 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003751 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003752}
3753
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003754status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003755 uint32_t w, uint32_t h, uint32_t flags,
3756 LayerMetadata metadata, sp<IBinder>* handle,
3757 sp<Layer>* outLayer) {
3758 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003759 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003760 *handle = (*outLayer)->getHandle();
3761 return NO_ERROR;
3762}
3763
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003764void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003765 mLayersPendingRemoval.add(layer);
3766 mLayersRemoved = true;
3767 setTransactionFlags(eTransactionNeeded);
3768}
3769
Robert Carr695d5282018-12-18 15:27:58 -08003770void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003771{
Robert Carr2e102c92018-10-23 12:11:15 -07003772 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003773 // If a layer has a parent, we allow it to out-live it's handle
3774 // with the idea that the parent holds a reference and will eventually
3775 // be cleaned up. However no one cleans up the top-level so we do so
3776 // here.
3777 if (layer->getParent() == nullptr) {
3778 mCurrentState.layersSortedByZ.remove(layer);
3779 }
3780 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003781
3782 auto it = mLayersByLocalBinderToken.begin();
3783 while (it != mLayersByLocalBinderToken.end()) {
3784 if (it->second == layer) {
3785 it = mLayersByLocalBinderToken.erase(it);
3786 } else {
3787 it++;
3788 }
3789 }
3790
Robert Carr695d5282018-12-18 15:27:58 -08003791 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003792}
3793
Mathias Agopianb60314a2012-04-10 22:09:54 -07003794// ---------------------------------------------------------------------------
3795
Andy McFadden13a082e2012-08-24 10:16:42 -07003796void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003797 const auto display = getDefaultDisplayDeviceLocked();
3798 if (!display) return;
3799
3800 const sp<IBinder> token = display->getDisplayToken().promote();
3801 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003802
Jesse Hall01e29052013-02-19 16:13:35 -08003803 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003804 Vector<ComposerState> state;
3805 Vector<DisplayState> displays;
3806 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003807 d.what = DisplayState::eDisplayProjectionChanged |
3808 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003809 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003810 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003811 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003812 d.frame.makeInvalid();
3813 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003814 d.width = 0;
3815 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003816 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003817 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3818 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003819
Dominik Laskowskie9774092018-12-11 10:04:24 -08003820 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003821
Dominik Laskowski83b88212018-12-11 13:34:06 -08003822 const nsecs_t vsyncPeriod = getVsyncPeriod();
3823 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003824
Brian Andersond0010582017-03-07 13:20:31 -08003825 // Use phase of 0 since phase is not known.
3826 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003827 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003828 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003829}
3830
3831void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003832 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003833 postMessageAsync(
3834 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003835}
3836
Ady Abraham27c70212019-06-11 10:52:26 -07003837void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3838 if (mHWCVsyncState != enabled) {
3839 getHwComposer().setVsyncEnabled(displayId, enabled);
3840 mHWCVsyncState = enabled;
3841 }
3842}
3843
Dominik Laskowskie9774092018-12-11 10:04:24 -08003844void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003845 if (display->isVirtual()) {
3846 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003847 return;
3848 }
3849
Dominik Laskowski075d3172018-05-24 15:50:06 -07003850 const auto displayId = display->getId();
3851 LOG_ALWAYS_FATAL_IF(!displayId);
3852
Dominik Laskowski34157762018-10-31 13:07:19 -07003853 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003854
3855 int currentMode = display->getPowerMode();
3856 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003857 return;
3858 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003859
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003860 display->setPowerMode(mode);
3861
Lloyd Pique4dccc412018-01-22 17:21:36 -08003862 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003863 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003864 }
3865
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003866 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003867 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003868 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003869 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003870 mScheduler->onScreenAcquired(mAppConnectionHandle);
3871 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003872 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003873
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003874 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003875 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003876 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003877
3878 struct sched_param param = {0};
3879 param.sched_priority = 1;
3880 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3881 ALOGW("Couldn't set SCHED_FIFO on display on");
3882 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003883 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003884 // Turn off the display
3885 struct sched_param param = {0};
3886 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3887 ALOGW("Couldn't set SCHED_OTHER on display off");
3888 }
3889
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003890 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003891 mScheduler->disableHardwareVsync(true);
3892 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003893 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003894
Ady Abraham27c70212019-06-11 10:52:26 -07003895 // Make sure HWVsync is disabled before turning off the display
3896 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3897
Dominik Laskowski075d3172018-05-24 15:50:06 -07003898 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003899 mVisibleRegionsDirty = true;
3900 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003901 } else if (mode == HWC_POWER_MODE_DOZE ||
3902 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003903 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003904 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003905 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003906 mScheduler->onScreenAcquired(mAppConnectionHandle);
3907 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003908 }
3909 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3910 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003911 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003912 mScheduler->disableHardwareVsync(true);
3913 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003914 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003915 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003916 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003917 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003918 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003919 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003920
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003921 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003922 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003923 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003924 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003925 }
3926
Dominik Laskowski34157762018-10-31 13:07:19 -07003927 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003928}
3929
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003930void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003931 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003932 const auto display = getDisplayDevice(displayToken);
3933 if (!display) {
3934 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3935 displayToken.get());
3936 } else if (display->isVirtual()) {
3937 ALOGW("Attempt to set power mode %d for virtual display", mode);
3938 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003939 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003940 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003941 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003942}
3943
3944// ---------------------------------------------------------------------------
3945
Dominik Laskowskic2867142019-01-21 11:33:38 -08003946status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3947 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003948 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003949
Mathias Agopianbd115332013-04-18 16:41:04 -07003950 IPCThreadState* ipc = IPCThreadState::self();
3951 const int pid = ipc->getCallingPid();
3952 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003953
Mathias Agopianbd115332013-04-18 16:41:04 -07003954 if ((uid != AID_SHELL) &&
3955 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003956 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3957 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003958 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003959 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003960 // (this would indicate SF is stuck, but we want to be able to
3961 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003962 status_t err = mStateLock.timedLock(s2ns(1));
3963 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003964 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003965 StringAppendF(&result,
3966 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3967 "(no locks held)\n",
3968 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003969 }
3970
Dominik Laskowskic2867142019-01-21 11:33:38 -08003971 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003972 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003973 {"--dispsync"s,
3974 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003975 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003976 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3977 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3978 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3979 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3980 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3981 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003982 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003983 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3984 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003985
Dominik Laskowskic2867142019-01-21 11:33:38 -08003986 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003987
Dominik Laskowski46470112019-08-02 13:13:11 -07003988 const auto it = dumpers.find(flag);
3989 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003990 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07003991 } else if (!asProto) {
3992 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003993 }
3994
Mathias Agopian9795c422009-08-26 16:36:26 -07003995 if (locked) {
3996 mStateLock.unlock();
3997 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003998
Dominik Laskowski46470112019-08-02 13:13:11 -07003999 if (it == dumpers.end()) {
4000 const LayersProto layersProto = dumpProtoFromMainThread();
4001 if (asProto) {
4002 result.append(layersProto.SerializeAsString());
4003 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004004 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004005 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4006 result.append(LayerProtoParser::layerTreeToString(layerTree));
4007 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004008 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004009 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004010 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004011 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004012 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004013 return NO_ERROR;
4014}
4015
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004016status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4017 if (asProto && mTracing.isEnabled()) {
4018 mTracing.writeToFileAsync();
4019 }
4020
4021 return doDump(fd, DumpArgs(), asProto);
4022}
4023
Dominik Laskowskic2867142019-01-21 11:33:38 -08004024void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004025 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004026 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004027}
4028
Dominik Laskowskic2867142019-01-21 11:33:38 -08004029void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004030 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004031
Dominik Laskowskic2867142019-01-21 11:33:38 -08004032 if (args.size() > 1) {
4033 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004034 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004035 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004036 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004037 }
Robert Carr2047fae2016-11-28 14:09:09 -08004038 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004039 } else {
4040 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004041 }
4042}
4043
Dominik Laskowskic2867142019-01-21 11:33:38 -08004044void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004045 const bool clearAll = args.size() < 2;
4046 const auto name = clearAll ? String8() : String8(args[1]);
4047
Robert Carr2047fae2016-11-28 14:09:09 -08004048 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004049 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004050 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004051 }
Robert Carr2047fae2016-11-28 14:09:09 -08004052 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004053
Svetoslavd85084b2014-03-20 10:28:31 -07004054 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004055}
4056
Dominik Laskowskic2867142019-01-21 11:33:38 -08004057void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4058 mTimeStats->parseArgs(asProto, args, result);
4059}
4060
Jamie Gennis6547ff42013-07-16 20:12:42 -07004061// This should only be called from the main thread. Otherwise it would need
4062// the lock and should use mCurrentState rather than mDrawingState.
4063void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004064 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004065 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004066 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004067
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004068 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004069}
4070
Yiwei Zhang5434a782018-12-05 18:06:32 -08004071void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004072 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004073
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004074 if (isLayerTripleBufferingDisabled())
4075 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004076
Yiwei Zhang5434a782018-12-05 18:06:32 -08004077 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4078 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4079 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4080 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4081 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4082 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004083 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004084}
4085
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004086void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004087 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004088
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004089 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004090 result.append("\n");
4091
Ady Abraham9e16a482019-12-03 17:19:41 -08004092 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004093 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004094 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004095 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004096
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004097 HwcConfigIndexType defaultConfig;
4098 float minFps, maxFps;
4099 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004100 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004101 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004102 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004103 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004104 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4105 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004106
Ana Krulecc2870422019-01-29 19:00:58 -08004107 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004108}
4109
Yiwei Zhang5434a782018-12-05 18:06:32 -08004110void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4111 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004112 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4113 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004114 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004115 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004116 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004117 }
David Sodman4a36e932017-11-07 14:29:47 -08004118 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004119 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004120 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004121 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4122 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004123}
4124
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004125void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4126 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004127 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4128 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004129 for (const auto& segment : history) {
4130 if (!segment.usedThirdBuffer) {
4131 stats.twoBufferTime += segment.totalTime;
4132 }
4133 if (segment.occupancyAverage < 1.0f) {
4134 stats.doubleBufferedTime += segment.totalTime;
4135 } else if (segment.occupancyAverage < 2.0f) {
4136 stats.tripleBufferedTime += segment.totalTime;
4137 }
4138 ++stats.numSegments;
4139 stats.totalTime += segment.totalTime;
4140 }
4141}
4142
Yiwei Zhang5434a782018-12-05 18:06:32 -08004143void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4144 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004145
4146 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4147 const size_t count = currentLayers.size();
4148 for (size_t i=0 ; i<count ; i++) {
4149 currentLayers[i]->dumpFrameEvents(result);
4150 }
4151}
4152
Yiwei Zhang5434a782018-12-05 18:06:32 -08004153void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004154 result.append("Buffering stats:\n");
4155 result.append(" [Layer name] <Active time> <Two buffer> "
4156 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004157 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004158 typedef std::tuple<std::string, float, float, float> BufferTuple;
4159 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004160 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004161 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004162 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004163 if (stats.numSegments == 0) {
4164 continue;
4165 }
4166 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4167 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4168 stats.totalTime;
4169 float doubleBufferRatio = static_cast<float>(
4170 stats.doubleBufferedTime) / stats.totalTime;
4171 float tripleBufferRatio = static_cast<float>(
4172 stats.tripleBufferedTime) / stats.totalTime;
4173 sorted.insert({activeTime, {name, twoBufferRatio,
4174 doubleBufferRatio, tripleBufferRatio}});
4175 }
4176 for (const auto& sortedPair : sorted) {
4177 float activeTime = sortedPair.first;
4178 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004179 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4180 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004181 }
4182 result.append("\n");
4183}
4184
Yiwei Zhang5434a782018-12-05 18:06:32 -08004185void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004186 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004187 const auto displayId = display->getId();
4188 if (!displayId) {
4189 continue;
4190 }
4191 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004192 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004193 continue;
4194 }
4195
Yiwei Zhang5434a782018-12-05 18:06:32 -08004196 StringAppendF(&result,
4197 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4198 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004199 uint8_t port;
4200 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004201 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004202 result.append("no identification data\n");
4203 continue;
4204 }
4205
4206 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004207 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004208 continue;
4209 }
4210
4211 const auto edid = parseEdid(data);
4212 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004213 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004214 continue;
4215 }
4216
Yiwei Zhang5434a782018-12-05 18:06:32 -08004217 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004218 result.append(edid->displayName.data(), edid->displayName.length());
4219 result.append("\"\n");
4220 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004221}
4222
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004223void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4224 std::string& result) const {
4225 hwc2_display_t hwcDisplayId;
4226 uint8_t port;
4227 DisplayIdentificationData data;
4228
4229 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4230 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4231 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4232 }
4233}
4234
Yiwei Zhang5434a782018-12-05 18:06:32 -08004235void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004236 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004237 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4238 StringAppendF(&result, "DisplayColorSetting: %s\n",
4239 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004240
4241 // TODO: print out if wide-color mode is active or not
4242
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004243 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004244 const auto displayId = display->getId();
4245 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004246 continue;
4247 }
4248
Yiwei Zhang5434a782018-12-05 18:06:32 -08004249 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004250 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004251 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004252 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004253 }
4254
Lloyd Pique32cbe282018-10-19 13:09:22 -07004255 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004256 StringAppendF(&result, " Current color mode: %s (%d)\n",
4257 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004258 }
4259 result.append("\n");
4260}
4261
Vishnu Nair8406fd72019-07-30 11:29:31 -07004262LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004263 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004264 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4265 layer->writeToProto(layersProto, traceFlags);
4266 }
chaviw1d044282017-09-27 12:19:28 -07004267 return layersProto;
4268}
4269
Vishnu Nair0f085c62019-08-30 08:49:12 -07004270void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4271 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4272 // it.
4273 LayerProto* rootProto = layersProto.add_layers();
4274 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4275 rootProto->set_id(offscreenRootLayerId);
4276 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004277 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004278
4279 for (Layer* offscreenLayer : mOffscreenLayers) {
4280 // Add layer as child of the fake root
4281 rootProto->add_children(offscreenLayer->sequence);
4282
4283 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004284 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004285 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004286 }
4287}
4288
Vishnu Nair8406fd72019-07-30 11:29:31 -07004289LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4290 LayersProto layersProto;
4291 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4292 return layersProto;
4293}
4294
Vishnu Nair0f085c62019-08-30 08:49:12 -07004295void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4296 result.append("Offscreen Layers:\n");
4297 postMessageSync(new LambdaMessage([&]() {
4298 for (Layer* offscreenLayer : mOffscreenLayers) {
4299 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4300 layer->dumpCallingUidPid(result);
4301 });
4302 }
4303 }));
4304}
4305
Dominik Laskowskic2867142019-01-21 11:33:38 -08004306void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4307 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004308 Colorizer colorizer(colorize);
4309
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004310 // figure out if we're stuck somewhere
4311 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004312 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004313 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4314
4315 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004316 * Dump library configuration.
4317 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004318
4319 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004320 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004321 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004322 appendSfConfigString(result);
4323 appendUiConfigString(result);
4324 appendGuiConfigString(result);
4325 result.append("\n");
4326
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004327 result.append("\nDisplay identification data:\n");
4328 dumpDisplayIdentificationData(result);
4329
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004330 result.append("\nWide-Color information:\n");
4331 dumpWideColorInfo(result);
4332
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004333 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004334 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004335 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004336 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004337 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004338
Andy McFadden41d67d72014-04-25 16:58:34 -07004339 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004340 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004341 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004342 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004343 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004344
Dan Stozab90cf072015-03-05 11:05:59 -08004345 dumpStaticScreenStats(result);
4346 result.append("\n");
4347
Alec Mouri40189b02019-03-05 15:07:54 -08004348 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4349 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4350 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004351
Dan Stozae77c7662016-05-13 11:37:28 -07004352 dumpBufferingStats(result);
4353
Andy McFadden4803b742012-09-24 19:07:20 -07004354 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004355 * Dump the visible layer list
4356 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004357 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004358 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004359 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4360 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004361 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004362
Chia-I Wu2f884132018-09-13 15:17:58 -07004363 {
Lloyd Pique207def92019-02-28 16:09:52 -08004364 StringAppendF(&result, "Composition layers\n");
4365 mDrawingState.traverseInZOrder([&](Layer* layer) {
4366 auto compositionLayer = layer->getCompositionLayer();
4367 if (compositionLayer) compositionLayer->dump(result);
4368 });
4369 }
4370
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004371 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004372 * Dump Display state
4373 */
4374
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004375 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004376 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004377 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004378 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004379 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004380 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004381 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004382
4383 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004384 * Dump CompositionEngine state
4385 */
4386
4387 mCompositionEngine->dump(result);
4388
4389 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004390 * Dump SurfaceFlinger global state
4391 */
4392
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004393 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004394 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004395 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004396
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004397 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004398
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004399 DebugEGLImageTracker::getInstance()->dump(result);
4400
Dominik Laskowski075d3172018-05-24 15:50:06 -07004401 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004402 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4403 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004404 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4405 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004406 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004407 StringAppendF(&result,
4408 " transaction-flags : %08x\n"
4409 " gpu_to_cpu_unsupported : %d\n",
4410 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004411
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004412 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004413 displayId && getHwComposer().isConnected(*displayId)) {
4414 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004415 StringAppendF(&result,
4416 " refresh-rate : %f fps\n"
4417 " x-dpi : %f\n"
4418 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004419 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4420 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004421 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004422
Yiwei Zhang5434a782018-12-05 18:06:32 -08004423 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004424
Dan Stozae22aec72016-08-01 13:20:59 -07004425 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004426 * Tracing state
4427 */
4428 mTracing.dump(result);
4429 result.append("\n");
4430
4431 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004432 * HWC layer minidump
4433 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004434 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004435 const auto displayId = display->getId();
4436 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004437 continue;
4438 }
4439
Yiwei Zhang5434a782018-12-05 18:06:32 -08004440 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004441 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004442 const sp<DisplayDevice> displayDevice = display;
4443 mCurrentState.traverseInZOrder(
4444 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004445 result.append("\n");
4446 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004447
4448 /*
4449 * Dump HWComposer state
4450 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004451 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004452 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004453 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004454 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004455 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004456 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004457
4458 /*
4459 * Dump gralloc state
4460 */
4461 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4462 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004463
4464 /*
4465 * Dump VrFlinger state if in use.
4466 */
4467 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4468 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004469 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004470 result.append("\n");
4471 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004472
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004473 result.append(mTimeStats->miniDump());
4474 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004475}
4476
Chia-I Wu28f320b2018-05-03 11:02:56 -07004477void SurfaceFlinger::updateColorMatrixLocked() {
4478 mat4 colorMatrix;
4479 if (mGlobalSaturationFactor != 1.0f) {
4480 // Rec.709 luma coefficients
4481 float3 luminance{0.213f, 0.715f, 0.072f};
4482 luminance *= 1.0f - mGlobalSaturationFactor;
4483 mat4 saturationMatrix = mat4(
4484 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4485 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4486 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4487 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4488 );
4489 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4490 } else {
4491 colorMatrix = mClientColorMatrix * mDaltonizer();
4492 }
4493
4494 if (mCurrentState.colorMatrix != colorMatrix) {
4495 mCurrentState.colorMatrix = colorMatrix;
4496 mCurrentState.colorMatrixChanged = true;
4497 setTransactionFlags(eTransactionNeeded);
4498 }
4499}
4500
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004501status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004502#pragma clang diagnostic push
4503#pragma clang diagnostic error "-Wswitch-enum"
4504 switch (static_cast<ISurfaceComposerTag>(code)) {
4505 // These methods should at minimum make sure that the client requested
4506 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004507 case BOOT_FINISHED:
4508 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004509 case CREATE_DISPLAY:
4510 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004511 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004512 case GET_ANIMATION_FRAME_STATS:
4513 case GET_HDR_CAPABILITIES:
4514 case SET_ACTIVE_CONFIG:
Ana Krulec0782b882019-10-15 17:34:54 -07004515 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004516 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004517 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004518 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4519 case SET_AUTO_LOW_LATENCY_MODE:
4520 case GET_GAME_CONTENT_TYPE_SUPPORT:
4521 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004522 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004523 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004524 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004525 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004526 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004527 case NOTIFY_POWER_HINT:
4528 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004529 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4530 IPCThreadState* ipc = IPCThreadState::self();
4531 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4532 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004533 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004534 }
Robert Carr1db73f62016-12-21 12:58:51 -08004535 return OK;
4536 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004537 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004538 IPCThreadState* ipc = IPCThreadState::self();
4539 const int pid = ipc->getCallingPid();
4540 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004541 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4542 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004543 return PERMISSION_DENIED;
4544 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004545 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004546 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004547 // Used by apps to hook Choreographer to SurfaceFlinger.
4548 case CREATE_DISPLAY_EVENT_CONNECTION:
4549 // The following calls are currently used by clients that do not
4550 // request necessary permissions. However, they do not expose any secret
4551 // information, so it is OK to pass them.
4552 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004553 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004554 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004555 case GET_PHYSICAL_DISPLAY_IDS:
4556 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004557 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004558 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004559 case GET_DISPLAY_CONFIGS:
4560 case GET_DISPLAY_STATS:
4561 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4562 // Calling setTransactionState is safe, because you need to have been
4563 // granted a reference to Client* and Handle* to do anything with it.
4564 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004565 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004566 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004567 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004568 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004569 case IS_WIDE_COLOR_DISPLAY:
4570 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4571 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004572 return OK;
4573 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004574 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004575 case CAPTURE_SCREEN:
4576 case ADD_REGION_SAMPLING_LISTENER:
4577 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004578 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004579 IPCThreadState* ipc = IPCThreadState::self();
4580 const int pid = ipc->getCallingPid();
4581 const int uid = ipc->getCallingUid();
4582 if ((uid != AID_GRAPHICS) &&
4583 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4584 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4585 return PERMISSION_DENIED;
4586 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004587 return OK;
4588 }
4589 // The following codes are deprecated and should never be allowed to access SF.
4590 case CONNECT_DISPLAY_UNUSED:
4591 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4592 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4593 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004594 }
chaviw93df2ea2019-04-30 16:45:12 -07004595 case CAPTURE_SCREEN_BY_ID: {
4596 IPCThreadState* ipc = IPCThreadState::self();
4597 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004598 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004599 return OK;
4600 }
4601 return PERMISSION_DENIED;
4602 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004603 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004604
4605 // These codes are used for the IBinder protocol to either interrogate the recipient
4606 // side of the transaction for its canonical interface descriptor or to dump its state.
4607 // We let them pass by default.
4608 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4609 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4610 code == IBinder::SYSPROPS_TRANSACTION) {
4611 return OK;
4612 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004613 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004614 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004615 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004616 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4617 return OK;
4618 }
4619 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4620 return PERMISSION_DENIED;
4621#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004622}
4623
Ana Krulec13be8ad2018-08-21 02:43:56 +00004624status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4625 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004626 status_t credentialCheck = CheckTransactCodeCredentials(code);
4627 if (credentialCheck != OK) {
4628 return credentialCheck;
4629 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004630
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004631 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4632 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004633 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004634 IPCThreadState* ipc = IPCThreadState::self();
4635 const int uid = ipc->getCallingUid();
4636 if (CC_UNLIKELY(uid != AID_SYSTEM
4637 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004638 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004639 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004640 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004641 return PERMISSION_DENIED;
4642 }
4643 int n;
4644 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004645 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004646 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004647 return NO_ERROR;
4648 case 1002: // SHOW_UPDATES
4649 n = data.readInt32();
4650 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004651 invalidateHwcGeometry();
4652 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004653 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004654 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004655 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004656 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004657 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004658 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004659 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004660 setTransactionFlags(
4661 eTransactionNeeded|
4662 eDisplayTransactionNeeded|
4663 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004664 return NO_ERROR;
4665 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004666 case 1006:{ // send empty update
4667 signalRefresh();
4668 return NO_ERROR;
4669 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004670 case 1008: // toggle use of hw composer
4671 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004672 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004673 invalidateHwcGeometry();
4674 repaintEverything();
4675 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004676 case 1009: // toggle use of transform hint
4677 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004678 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004679 invalidateHwcGeometry();
4680 repaintEverything();
4681 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004682 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004683 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004684 reply->writeInt32(0);
4685 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004686 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004687 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004688 return NO_ERROR;
4689 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004690 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004691 if (!display) {
4692 return NAME_NOT_FOUND;
4693 }
4694
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004695 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004696 return NO_ERROR;
4697 }
4698 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004699 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004700 // daltonize
4701 n = data.readInt32();
4702 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004703 case 1:
4704 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4705 break;
4706 case 2:
4707 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4708 break;
4709 case 3:
4710 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4711 break;
4712 default:
4713 mDaltonizer.setType(ColorBlindnessType::None);
4714 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004715 }
4716 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004717 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004718 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004719 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004720 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004721
4722 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004723 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004724 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004725 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004726 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004727 // apply a color matrix
4728 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004729 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004730 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004731 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004732 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004733 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004734 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004735 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004736 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004737 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004738 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004739
4740 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4741 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004742 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004743 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4744 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4745 }
4746
Chia-I Wu28f320b2018-05-03 11:02:56 -07004747 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004748 return NO_ERROR;
4749 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004750 case 1016: { // Unused.
4751 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004752 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004753 case 1017: {
4754 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004755 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004756 return NO_ERROR;
4757 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004758 case 1018: { // Modify Choreographer's phase offset
4759 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004760 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004761 return NO_ERROR;
4762 }
4763 case 1019: { // Modify SurfaceFlinger's phase offset
4764 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004765 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004766 return NO_ERROR;
4767 }
Irvel468051e2016-06-13 16:44:44 -07004768 case 1020: { // Layer updates interceptor
4769 n = data.readInt32();
4770 if (n) {
4771 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004772 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004773 }
4774 else{
4775 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004776 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004777 }
4778 return NO_ERROR;
4779 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004780 case 1021: { // Disable HWC virtual displays
4781 n = data.readInt32();
4782 mUseHwcVirtualDisplays = !n;
4783 return NO_ERROR;
4784 }
Romain Guy0147a172017-06-01 13:53:56 -07004785 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004786 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004787 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004788
Chia-I Wu28f320b2018-05-03 11:02:56 -07004789 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004790 return NO_ERROR;
4791 }
Romain Guy54f154a2017-10-24 21:40:32 +01004792 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004793 int32_t colorMode;
4794
Chia-I Wu0d711262018-05-21 15:19:35 -07004795 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004796 if (data.readInt32(&colorMode) == NO_ERROR) {
4797 mForceColorMode = static_cast<ColorMode>(colorMode);
4798 }
Romain Guy54f154a2017-10-24 21:40:32 +01004799 invalidateHwcGeometry();
4800 repaintEverything();
4801 return NO_ERROR;
4802 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004803 // Deprecate, use 1030 to check whether the device is color managed.
4804 case 1024: {
4805 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004806 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004807 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004808 n = data.readInt32();
4809 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004810 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004811 Mutex::Autolock lock(mStateLock);
4812 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004813 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004814 reply->writeInt32(NO_ERROR);
4815 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004816 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004817 bool writeFile = false;
4818 {
4819 Mutex::Autolock lock(mStateLock);
4820 mTracingEnabledChanged = true;
4821 writeFile = mTracing.disable();
4822 }
4823
4824 if (writeFile) {
4825 reply->writeInt32(mTracing.writeToFile());
4826 } else {
4827 reply->writeInt32(NO_ERROR);
4828 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004829 }
4830 return NO_ERROR;
4831 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004832 case 1026: { // Get layer tracing status
4833 reply->writeBool(mTracing.isEnabled());
4834 return NO_ERROR;
4835 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004836 // Is a DisplayColorSetting supported?
4837 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004838 const auto display = getDefaultDisplayDevice();
4839 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004840 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004841 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004842
4843 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4844 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004845 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004846 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004847 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004848 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004849 reply->writeBool(true);
4850 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004851 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004852 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004853 break;
4854 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004855 reply->writeBool(
4856 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004857 break;
4858 }
4859 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004860 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004861 // Is VrFlinger active?
4862 case 1028: {
4863 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004864 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004865 return NO_ERROR;
4866 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004867 // Set buffer size for SF tracing (value in KB)
4868 case 1029: {
4869 n = data.readInt32();
4870 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4871 ALOGW("Invalid buffer size: %d KB", n);
4872 reply->writeInt32(BAD_VALUE);
4873 return BAD_VALUE;
4874 }
4875
4876 ALOGD("Updating trace buffer to %d KB", n);
4877 mTracing.setBufferSize(n * 1024);
4878 reply->writeInt32(NO_ERROR);
4879 return NO_ERROR;
4880 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004881 // Is device color managed?
4882 case 1030: {
4883 reply->writeBool(useColorManagement);
4884 return NO_ERROR;
4885 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004886 // Override default composition data space
4887 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4888 // && adb shell stop zygote && adb shell start zygote
4889 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4890 // adb shell stop zygote && adb shell start zygote
4891 case 1031: {
4892 Mutex::Autolock _l(mStateLock);
4893 n = data.readInt32();
4894 if (n) {
4895 n = data.readInt32();
4896 if (n) {
4897 Dataspace dataspace = static_cast<Dataspace>(n);
4898 if (!validateCompositionDataspace(dataspace)) {
4899 return BAD_VALUE;
4900 }
4901 mDefaultCompositionDataspace = dataspace;
4902 }
4903 n = data.readInt32();
4904 if (n) {
4905 Dataspace dataspace = static_cast<Dataspace>(n);
4906 if (!validateCompositionDataspace(dataspace)) {
4907 return BAD_VALUE;
4908 }
4909 mWideColorGamutCompositionDataspace = dataspace;
4910 }
4911 } else {
4912 // restore composition data space.
4913 mDefaultCompositionDataspace = defaultCompositionDataspace;
4914 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4915 }
4916 return NO_ERROR;
4917 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004918 // Set trace flags
4919 case 1033: {
4920 n = data.readUint32();
4921 ALOGD("Updating trace flags to 0x%x", n);
4922 mTracing.setTraceFlags(n);
4923 reply->writeInt32(NO_ERROR);
4924 return NO_ERROR;
4925 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004926 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004927 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004928 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004929 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08004930 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
4931 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08004932 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004933 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004934 } else {
4935 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004936 }
4937 return NO_ERROR;
4938 }
Ady Abraham34392f72019-04-10 11:29:27 -07004939 case 1035: {
4940 n = data.readInt32();
4941 mDebugDisplayConfigSetByBackdoor = false;
4942 if (n >= 0) {
4943 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004944 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07004945 if (result != NO_ERROR) {
4946 return result;
4947 }
4948 mDebugDisplayConfigSetByBackdoor = true;
4949 }
4950 return NO_ERROR;
4951 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004952 }
4953 }
4954 return err;
4955}
4956
Steven Thomas6d8110b2017-08-31 18:24:21 -07004957void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004958 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004959 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004960}
4961
Ana Krulec7d1d6832018-12-27 11:10:09 -08004962void SurfaceFlinger::repaintEverythingForHWC() {
4963 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004964 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004965}
4966
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004967// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4968class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004969public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004970 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4971 ~WindowDisconnector() {
4972 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004973 }
4974
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004975private:
4976 ANativeWindow* mWindow;
4977 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004978};
4979
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004980status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07004981 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08004982 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
4983 const Rect& sourceCrop, uint32_t reqWidth,
4984 uint32_t reqHeight, bool useIdentityTransform,
4985 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004986 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004987
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004988 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004989
Dominik Laskowski718f9602019-11-09 20:01:35 -08004990 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
4991 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
4992 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
4993 renderAreaRotation = ui::Transform::ROT_0;
4994 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07004995
Chia-I Wu20261cb2018-08-23 12:55:44 -07004996 sp<DisplayDevice> display;
4997 {
4998 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004999
Chia-I Wu20261cb2018-08-23 12:55:44 -07005000 display = getDisplayDeviceLocked(displayToken);
5001 if (!display) return BAD_VALUE;
5002
Chia-I Wucb023152018-08-28 12:57:23 -07005003 // set the requested width/height to the logical display viewport size
5004 // by default
5005 if (reqWidth == 0 || reqHeight == 0) {
5006 reqWidth = uint32_t(display->getViewport().width());
5007 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005008 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005009 }
5010
Peiyong Lin0e003c92018-09-17 11:09:51 -07005011 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005012 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005013
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005014 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5015 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005016 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005017 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005018}
5019
chaviw93df2ea2019-04-30 16:45:12 -07005020static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5021 switch (colorMode) {
5022 case ColorMode::DISPLAY_P3:
5023 case ColorMode::BT2100_PQ:
5024 case ColorMode::BT2100_HLG:
5025 case ColorMode::DISPLAY_BT2020:
5026 return Dataspace::DISPLAY_P3;
5027 default:
5028 return Dataspace::V0_SRGB;
5029 }
5030}
5031
5032const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5033 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5034 if (displayToken) {
5035 return getDisplayDeviceLocked(displayToken);
5036 }
5037 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5038 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005039 return getDisplayByLayerStack(displayOrLayerStack);
5040}
5041
5042const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005043 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005044 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005045 return display;
5046 }
5047 }
5048 return nullptr;
5049}
5050
5051status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5052 sp<GraphicBuffer>* outBuffer) {
5053 sp<DisplayDevice> display;
5054 uint32_t width;
5055 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005056 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005057 {
5058 Mutex::Autolock _l(mStateLock);
5059 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5060 if (!display) {
5061 return BAD_VALUE;
5062 }
5063
5064 width = uint32_t(display->getViewport().width());
5065 height = uint32_t(display->getViewport().height());
5066
Dominik Laskowski718f9602019-11-09 20:01:35 -08005067 const auto orientation = display->getOrientation();
5068 captureOrientation = ui::Transform::toRotationFlags(orientation);
5069
5070 switch (captureOrientation) {
5071 case ui::Transform::ROT_90:
5072 captureOrientation = ui::Transform::ROT_270;
5073 break;
5074
5075 case ui::Transform::ROT_270:
5076 captureOrientation = ui::Transform::ROT_90;
5077 break;
5078
5079 case ui::Transform::ROT_INVALID:
5080 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5081 captureOrientation = ui::Transform::ROT_0;
5082 break;
5083
5084 default:
5085 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005086 }
chaviw93df2ea2019-04-30 16:45:12 -07005087 *outDataspace =
5088 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5089 }
5090
5091 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5092 false /* captureSecureLayers */);
5093
5094 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5095 std::placeholders::_1);
5096 bool ignored = false;
5097 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5098 false /* useIdentityTransform */,
5099 ignored /* outCapturedSecureLayers */);
5100}
5101
Robert Carr866455f2019-04-02 16:28:26 -07005102status_t SurfaceFlinger::captureLayers(
5103 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5104 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5105 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5106 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005107 ATRACE_CALL();
5108
5109 class LayerRenderArea : public RenderArea {
5110 public:
Robert Carr578038f2018-03-09 12:25:24 -08005111 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005112 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005113 bool childrenOnly, const Rect& displayViewport)
5114 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005115 mLayer(layer),
5116 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005117 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005118 mFlinger(flinger),
5119 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005120 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005121 Rect getBounds() const override {
5122 const Layer::State& layerState(mLayer->getDrawingState());
5123 return mLayer->getBufferSize(layerState);
5124 }
Marissa Wall61c58622018-07-18 10:12:20 -07005125 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005126 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005127 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005128 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005129 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005130 }
chaviwa76b2712017-09-20 12:02:26 -07005131 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005132 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005133 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005134 Rect getSourceCrop() const override {
5135 if (mCrop.isEmpty()) {
5136 return getBounds();
5137 } else {
5138 return mCrop;
5139 }
5140 }
Robert Carr578038f2018-03-09 12:25:24 -08005141 class ReparentForDrawing {
5142 public:
5143 const sp<Layer>& oldParent;
5144 const sp<Layer>& newParent;
5145
Vishnu Nair4351ad52019-02-11 14:13:02 -08005146 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5147 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005148 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005149 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005150 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5151 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005152 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005153 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005154 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005155 };
5156
5157 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005158 const Rect sourceCrop = getSourceCrop();
5159 // no need to check rotation because there is none
5160 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5161 sourceCrop.height() != getReqHeight();
5162
Robert Carr578038f2018-03-09 12:25:24 -08005163 if (!mChildrenOnly) {
5164 mTransform = mLayer->getTransform().inverse();
5165 drawLayers();
5166 } else {
5167 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005168 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5169 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005170 // In the "childrenOnly" case we reparent the children to a screenshot
5171 // layer which has no properties set and which does not draw.
5172 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005173 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5174 "Screenshot Parent"s, w, h, 0,
5175 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005176
Vishnu Nair4351ad52019-02-11 14:13:02 -08005177 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005178 drawLayers();
5179 }
5180 }
chaviwa76b2712017-09-20 12:02:26 -07005181
chaviwa76b2712017-09-20 12:02:26 -07005182 private:
chaviw7206d492017-11-10 16:16:12 -08005183 const sp<Layer> mLayer;
5184 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005185
Peiyong Linefefaac2018-08-17 12:27:51 -07005186 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005187 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005188
5189 SurfaceFlinger* mFlinger;
5190 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005191 };
5192
Robert Carrc0df3122019-04-11 13:18:21 -07005193 int reqWidth = 0;
5194 int reqHeight = 0;
5195 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005196 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005197 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005198 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005199 {
5200 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005201
Robert Carrc0df3122019-04-11 13:18:21 -07005202 parent = fromHandle(layerHandleBinder);
5203 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5204 ALOGE("captureLayers called with an invalid or removed parent");
5205 return NAME_NOT_FOUND;
5206 }
5207
5208 const int uid = IPCThreadState::self()->getCallingUid();
5209 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5210 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5211 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5212 return PERMISSION_DENIED;
5213 }
5214
Vishnu Nairefc42e22019-12-03 17:36:12 -08005215 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005216 if (sourceCrop.width() <= 0) {
5217 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005218 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005219 }
5220
5221 if (sourceCrop.height() <= 0) {
5222 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005223 crop.bottom = parentSourceBounds.getHeight();
5224 }
5225
5226 if (crop.isEmpty() || frameScale <= 0.0f) {
5227 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5228 // crop was not specified, or an invalid frame scale was provided.
5229 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005230 }
5231 reqWidth = crop.width() * frameScale;
5232 reqHeight = crop.height() * frameScale;
5233
5234 for (const auto& handle : excludeHandles) {
5235 sp<Layer> excludeLayer = fromHandle(handle);
5236 if (excludeLayer != nullptr) {
5237 excludeLayers.emplace(excludeLayer);
5238 } else {
5239 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5240 return NAME_NOT_FOUND;
5241 }
5242 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005243
5244 auto display = getDisplayByLayerStack(parent->getLayerStack());
5245 if (!display) {
5246 return BAD_VALUE;
5247 }
5248
5249 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005250 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005251
Chia-I Wu20261cb2018-08-23 12:55:44 -07005252 // really small crop or frameScale
5253 if (reqWidth <= 0) {
5254 reqWidth = 1;
5255 }
5256 if (reqHeight <= 0) {
5257 reqHeight = 1;
5258 }
5259
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005260 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5261 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005262 auto traverseLayers = [parent, childrenOnly,
5263 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005264 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5265 if (!layer->isVisible()) {
5266 return;
Robert Carr578038f2018-03-09 12:25:24 -08005267 } else if (childrenOnly && layer == parent.get()) {
5268 return;
chaviwa76b2712017-09-20 12:02:26 -07005269 }
Robert Carr866455f2019-04-02 16:28:26 -07005270
5271 sp<Layer> p = layer;
5272 while (p != nullptr) {
5273 if (excludeLayers.count(p) != 0) {
5274 return;
5275 }
5276 p = p->getParent();
5277 }
5278
chaviwa76b2712017-09-20 12:02:26 -07005279 visitor(layer);
5280 });
5281 };
Robert Carr108b2c72019-04-02 16:32:58 -07005282
5283 bool outCapturedSecureLayers = false;
5284 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5285 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005286}
5287
5288status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5289 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005290 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005291 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005292 bool useIdentityTransform,
5293 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005294 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005295
Peiyong Lin0e003c92018-09-17 11:09:51 -07005296 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005297 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5298 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005299 *outBuffer =
5300 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5301 static_cast<android_pixel_format>(reqPixelFormat), 1,
5302 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005303
Robert Carr108b2c72019-04-02 16:32:58 -07005304 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5305 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005306}
5307
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005308status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5309 TraverseLayersFunction traverseLayers,
5310 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005311 bool useIdentityTransform,
5312 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005313 // This mutex protects syncFd and captureResult for communication of the return values from the
5314 // main thread back to this Binder thread
5315 std::mutex captureMutex;
5316 std::condition_variable captureCondition;
5317 std::unique_lock<std::mutex> captureLock(captureMutex);
5318 int syncFd = -1;
5319 std::optional<status_t> captureResult;
5320
Robert Carr03480e22018-01-04 16:02:06 -08005321 const int uid = IPCThreadState::self()->getCallingUid();
5322 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5323
Dominik Laskowski8c001672018-05-30 16:52:06 -07005324 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005325 // If there is a refresh pending, bug out early and tell the binder thread to try again
5326 // after the refresh.
5327 if (mRefreshPending) {
5328 ATRACE_NAME("Skipping screenshot for now");
5329 std::unique_lock<std::mutex> captureLock(captureMutex);
5330 captureResult = std::make_optional<status_t>(EAGAIN);
5331 captureCondition.notify_one();
5332 return;
5333 }
5334
5335 status_t result = NO_ERROR;
5336 int fd = -1;
5337 {
5338 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005339 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005340 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005341 useIdentityTransform, forSystem, &fd,
5342 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005343 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005344 }
5345
5346 {
5347 std::unique_lock<std::mutex> captureLock(captureMutex);
5348 syncFd = fd;
5349 captureResult = std::make_optional<status_t>(result);
5350 captureCondition.notify_one();
5351 }
5352 });
5353
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005354 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005355 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005356 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005357 while (*captureResult == EAGAIN) {
5358 captureResult.reset();
5359 result = postMessageAsync(message);
5360 if (result != NO_ERROR) {
5361 return result;
5362 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005363 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005364 }
5365 result = *captureResult;
5366 }
5367
5368 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005369 sync_wait(syncFd, -1);
5370 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005371 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005372
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005373 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005374}
5375
chaviwa76b2712017-09-20 12:02:26 -07005376void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005377 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005378 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5379 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005380 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005381
chaviwa76b2712017-09-20 12:02:26 -07005382 const auto reqWidth = renderArea.getReqWidth();
5383 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005384 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005385 const auto transform = renderArea.getTransform();
5386 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005387 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005388
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005389 renderengine::DisplaySettings clientCompositionDisplay;
5390 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005391
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005392 // assume that bounds are never offset, and that they are the same as the
5393 // buffer bounds.
5394 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005395 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005396 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005397
5398 // Now take into account the rotation flag. We append a transform that
5399 // rotates the layer stack about the origin, then translate by buffer
5400 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005401 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005402 int displacementX = 0;
5403 int displacementY = 0;
5404 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5405 switch (rotation) {
5406 case ui::Transform::ROT_90:
5407 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005408 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005409 break;
5410 case ui::Transform::ROT_180:
5411 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005412 displacementY = renderArea.getBounds().getWidth();
5413 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005414 break;
5415 case ui::Transform::ROT_270:
5416 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005417 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005418 break;
5419 default:
5420 break;
5421 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005422
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005423 // We need to transform the clipping window into the right spot.
5424 // First, rotate the clipping rectangle by the rotation hint to get the
5425 // right orientation
5426 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5427 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5428 const vec4 rotClipTL = rotMatrix * clipTL;
5429 const vec4 rotClipBR = rotMatrix * clipBR;
5430 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5431 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5432 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5433 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5434
5435 // Now reposition the clipping rectangle with the displacement vector
5436 // computed above.
5437 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005438 clientCompositionDisplay.clip =
5439 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5440 newClipRight + displacementX, newClipBottom + displacementY);
5441
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005442 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005443 clientCompositionDisplay.globalTransform =
5444 clipTransform * clientCompositionDisplay.globalTransform;
5445
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005446 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5447 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005448
chaviw50da5042018-04-09 13:49:37 -07005449 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005450
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005451 renderengine::LayerSettings fillLayer;
5452 fillLayer.source.buffer.buffer = nullptr;
5453 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5454 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5455 fillLayer.alpha = half(alpha);
5456 clientCompositionLayers.push_back(fillLayer);
5457
5458 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005459 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005460 const bool supportProtectedContent = false;
5461 Region clip(renderArea.getBounds());
5462 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5463 clip,
5464 useIdentityTransform,
5465 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5466 renderArea.isSecure(),
5467 supportProtectedContent,
5468 clearRegion,
5469 };
5470 auto result = layer->prepareClientComposition(targetSettings);
5471 if (result) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005472 std::optional<renderengine::LayerSettings> shadowLayer =
5473 layer->prepareShadowClientComposition(*result, displayViewport,
5474 clientCompositionDisplay.outputDataspace);
5475 if (shadowLayer) {
5476 clientCompositionLayers.push_back(*shadowLayer);
5477 }
Lloyd Piquef16688f2019-02-19 17:47:57 -08005478 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005479 }
chaviwa76b2712017-09-20 12:02:26 -07005480 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005481
5482 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005483 // Use an empty fence for the buffer fence, since we just created the buffer so
5484 // there is no need for synchronization with the GPU.
5485 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005486 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005487 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005488 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005489 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005490
5491 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005492}
5493
chaviwa76b2712017-09-20 12:02:26 -07005494status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5495 TraverseLayersFunction traverseLayers,
5496 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005497 bool useIdentityTransform, bool forSystem,
5498 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005499 ATRACE_CALL();
5500
chaviwa76b2712017-09-20 12:02:26 -07005501 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005502 outCapturedSecureLayers =
5503 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005504 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005505
Robert Carr03480e22018-01-04 16:02:06 -08005506 // We allow the system server to take screenshots of secure layers for
5507 // use in situations like the Screen-rotation animation and place
5508 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005509 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005510 ALOGW("FB is protected: PERMISSION_DENIED");
5511 return PERMISSION_DENIED;
5512 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005513 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005514 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005515}
5516
chaviw95ef3c42019-02-14 10:55:09 -08005517void SurfaceFlinger::setInputWindowsFinished() {
5518 Mutex::Autolock _l(mStateLock);
5519
5520 mPendingSyncInputWindows = false;
5521 mTransactionCV.broadcast();
5522}
chaviw5f21a5e2019-02-14 10:00:34 -08005523
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005524// ---------------------------------------------------------------------------
5525
Dan Stoza412903f2017-04-27 13:42:17 -07005526void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5527 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005528}
5529
Dan Stoza412903f2017-04-27 13:42:17 -07005530void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5531 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005532}
5533
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005534void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005535 const LayerVector::Visitor& visitor) {
5536 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005537 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005538 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005539 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005540 continue;
5541 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005542 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005543 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005544 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005545 return;
5546 }
chaviwa76b2712017-09-20 12:02:26 -07005547 if (!layer->isVisible()) {
5548 return;
5549 }
5550 visitor(layer);
5551 });
5552 }
5553}
5554
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005555status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5556 HwcConfigIndexType defaultConfig,
5557 float minRefreshRate,
5558 float maxRefreshRate) {
5559 Mutex::Autolock lock(mStateLock);
5560
Dominik Laskowski22488f62019-03-28 09:53:04 -07005561 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005562 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5563 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5564 // it should go thru setDesiredActiveConfig, similar to primary display.
5565 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5566 const auto displayId = display->getId();
5567 LOG_ALWAYS_FATAL_IF(!displayId);
5568
5569 HWC2::VsyncPeriodChangeConstraints constraints;
5570 constraints.desiredTimeNanos = systemTime();
5571 constraints.seamlessRequired = false;
5572
5573 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005574 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5575 constraints, &timeline) < 0) {
5576 return BAD_VALUE;
5577 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005578 if (timeline.refreshRequired) {
5579 repaintEverythingForHWC();
5580 }
5581
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005582 auto configId = HwcConfigIndexType(defaultConfig);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005583 display->setActiveConfig(configId);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005584 const nsecs_t vsyncPeriod =
5585 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).vsyncPeriod;
5586 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, configId,
5587 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005588 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005589 }
5590
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005591 if (mDebugDisplayConfigSetByBackdoor) {
5592 // ignore this request as config is overridden by backdoor
5593 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005594 }
5595
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005596 bool policyChanged;
5597 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5598 &policyChanged) < 0) {
5599 return BAD_VALUE;
5600 }
5601 if (!policyChanged) {
5602 return NO_ERROR;
5603 }
5604
5605 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5606 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005607
5608 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5609 // that listeners that care about a change in allowed configs can get the notification.
5610 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005611 const nsecs_t vsyncPeriod =
5612 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005613 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005614 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005615
Ady Abraham2139f732019-11-13 18:56:40 -08005616 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5617 auto configId = mScheduler->getPreferredConfigId();
5618 auto preferredRefreshRate = configId
5619 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5620 : mRefreshRateConfigs->getMinRefreshRateByPolicy();
5621 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5622 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5623 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5624 ALOGV("switching to Scheduler preferred config %d",
5625 preferredRefreshRate.configId.value());
5626 setDesiredActiveConfig(
5627 {preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
5628 } else {
5629 // Set the highest allowed config
5630 setDesiredActiveConfig({mRefreshRateConfigs->getMaxRefreshRateByPolicy().configId,
5631 Scheduler::ConfigEvent::Changed});
5632 }
5633 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005634 ALOGV("switching to config %d", defaultConfig.value());
5635 setDesiredActiveConfig({defaultConfig, Scheduler::ConfigEvent::Changed});
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005636 }
5637
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005638 return NO_ERROR;
5639}
5640
Ana Krulec0782b882019-10-15 17:34:54 -07005641status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005642 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005643 float maxRefreshRate) {
5644 ATRACE_CALL();
5645
5646 if (!displayToken) {
5647 return BAD_VALUE;
5648 }
5649
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005650 status_t result = NO_ERROR;
5651
Ana Krulec234bb162019-11-10 22:55:55 +01005652 postMessageSync(new LambdaMessage([&]() {
5653 const auto display = getDisplayDeviceLocked(displayToken);
5654 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005655 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005656 ALOGE("Attempt to set desired display configs for invalid display token %p",
5657 displayToken.get());
5658 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005659 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005660 ALOGW("Attempt to set desired display configs for virtual display");
5661 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005662 result =
5663 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5664 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005665 }
5666 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005667
5668 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005669}
5670
5671status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005672 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005673 float* outMinRefreshRate,
5674 float* outMaxRefreshRate) {
5675 ATRACE_CALL();
5676
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005677 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005678 return BAD_VALUE;
5679 }
5680
5681 Mutex::Autolock lock(mStateLock);
5682 const auto display = getDisplayDeviceLocked(displayToken);
5683 if (!display) {
5684 return NAME_NOT_FOUND;
5685 }
5686
5687 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005688 HwcConfigIndexType defaultConfig;
5689 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5690 *outDefaultConfig = defaultConfig.value();
5691 return NO_ERROR;
5692 } else if (display->isVirtual()) {
5693 return BAD_VALUE;
5694 } else {
5695 const auto displayId = display->getId();
5696 if (!displayId) {
5697 return BAD_VALUE;
5698 }
5699 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5700 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5701 *outMinRefreshRate = 1e9f / vsyncPeriod;
5702 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5703 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005704 }
Ana Krulec0782b882019-10-15 17:34:54 -07005705}
5706
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005707void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005708 mFlinger->setInputWindowsFinished();
5709}
5710
Robert Carrc0df3122019-04-11 13:18:21 -07005711sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005712 BBinder* b = nullptr;
5713 if (handle) {
5714 b = handle->localBinder();
5715 }
Robert Carrc0df3122019-04-11 13:18:21 -07005716 if (b == nullptr) {
5717 return nullptr;
5718 }
5719 auto it = mLayersByLocalBinderToken.find(b);
5720 if (it != mLayersByLocalBinderToken.end()) {
5721 return it->second.promote();
5722 }
5723 return nullptr;
5724}
5725
Dominik Laskowski75848362019-11-11 17:57:20 -08005726void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005727 mNumLayers++;
5728 mScheduler->registerLayer(layer);
5729}
5730
5731void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5732 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005733 removeFromOffscreenLayers(layer);
5734}
5735
5736// WARNING: ONLY CALL THIS FROM LAYER DTOR
5737// Here we add children in the current state to offscreen layers and remove the
5738// layer itself from the offscreen layer list. Since
5739// this is the dtor, it is safe to access the current state. This keeps us
5740// from dangling children layers such that they are not reachable from the
5741// Drawing state nor the offscreen layer list
5742// See b/141111965
5743void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5744 for (auto& child : layer->getCurrentChildren()) {
5745 mOffscreenLayers.emplace(child.get());
5746 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005747 mOffscreenLayers.erase(layer);
5748}
5749
Alec Mouri4545a8a2019-08-08 20:05:32 -07005750void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5751 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5752}
5753
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005754status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5755 float lightPosY, float lightPosZ,
5756 float lightRadius) {
5757 Mutex::Autolock _l(mStateLock);
5758 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5759 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5760 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5761 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5762 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5763
5764 // these values are overridden when calculating the shadow settings for a layer.
5765 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5766 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005767 return NO_ERROR;
5768}
5769
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005770} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005771
Mathias Agopian3f844832013-08-07 21:24:32 -07005772#if defined(__gl_h_)
5773#error "don't include gl/gl.h in this file"
5774#endif
5775
5776#if defined(__gl2_h_)
5777#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005778#endif
Ady Abrahamb0dbdaa2020-01-06 16:19:42 -08005779
5780// TODO(b/129481165): remove the #pragma below and fix conversion issues
5781#pragma clang diagnostic pop // ignored "-Wconversion"