blob: 86e73c2481dfb23b235c2fae2198724dd7ee42bf [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
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080041#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070042#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070043#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080044#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070049#include <gui/DebugEGLImageTracker.h>
50
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070087#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070098#include "FrameTracer/FrameTracer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -070099#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700100#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700101#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700102#include "Scheduler/EventControlThread.h"
103#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700104#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700105#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700106#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800107#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700108
Mathias Agopianff2ed702013-09-01 21:36:12 -0700109#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700110
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700111#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800112#include "android-base/stringprintf.h"
113
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800115#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
116#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700117#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900118#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119
chaviw1d044282017-09-27 12:19:28 -0700120#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900121#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700124
Jaesoo Lee43518572017-01-23 19:03:16 +0900125using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900126using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900127using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800128
Ady Abraham8532d012019-05-08 14:50:56 -0700129using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800130using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700131using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700132using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800133using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700134using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700135using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900136
Steven Thomasb02664d2017-07-26 18:48:28 -0700137namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700138
139#pragma clang diagnostic push
140#pragma clang diagnostic error "-Wswitch-enum"
141
142bool isWideColorMode(const ColorMode colorMode) {
143 switch (colorMode) {
144 case ColorMode::DISPLAY_P3:
145 case ColorMode::ADOBE_RGB:
146 case ColorMode::DCI_P3:
147 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700148 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700149 case ColorMode::BT2100_PQ:
150 case ColorMode::BT2100_HLG:
151 return true;
152 case ColorMode::NATIVE:
153 case ColorMode::STANDARD_BT601_625:
154 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
155 case ColorMode::STANDARD_BT601_525:
156 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
157 case ColorMode::STANDARD_BT709:
158 case ColorMode::SRGB:
159 return false;
160 }
161 return false;
162}
163
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700164ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
165 switch (rotation) {
166 case ISurfaceComposer::eRotateNone:
167 return ui::Transform::ROT_0;
168 case ISurfaceComposer::eRotate90:
169 return ui::Transform::ROT_90;
170 case ISurfaceComposer::eRotate180:
171 return ui::Transform::ROT_180;
172 case ISurfaceComposer::eRotate270:
173 return ui::Transform::ROT_270;
174 }
175 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
176 return ui::Transform::ROT_0;
177}
178
Peiyong Linfca547f2018-07-09 13:03:33 -0700179#pragma clang diagnostic pop
180
Steven Thomasb02664d2017-07-26 18:48:28 -0700181class ConditionalLock {
182public:
183 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
184 if (lock) {
185 mMutex.lock();
186 }
187 }
188 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
189private:
190 Mutex& mMutex;
191 bool mLocked;
192};
Peiyong Linfca547f2018-07-09 13:03:33 -0700193
Peiyong Lin9d846a52018-11-05 13:18:20 -0800194// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
195bool validateCompositionDataspace(Dataspace dataspace) {
196 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
197}
198
Steven Thomasb02664d2017-07-26 18:48:28 -0700199} // namespace anonymous
200
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201// ---------------------------------------------------------------------------
202
Mathias Agopian99b49842011-06-27 16:05:52 -0700203const String16 sHardwareTest("android.permission.HARDWARE_TEST");
204const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
205const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
206const String16 sDump("android.permission.DUMP");
207
208// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700209int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700210bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800211uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800212bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800213bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800214int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600215bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700216int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700217bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700218bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700219Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
220ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
221Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
222ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700223
Kalle Raitaa099a242017-01-11 11:17:29 -0800224std::string getHwcServiceName() {
225 char value[PROPERTY_VALUE_MAX] = {};
226 property_get("debug.sf.hwc_service_name", value, "default");
227 ALOGI("Using HWComposer service: '%s'", value);
228 return std::string(value);
229}
230
231bool useTrebleTestingOverride() {
232 char value[PROPERTY_VALUE_MAX] = {};
233 property_get("debug.sf.treble_testing_override", value, "false");
234 ALOGI("Treble testing override: '%s'", value);
235 return std::string(value) == "true";
236}
237
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800238std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
239 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800240 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700241 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800242 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700243 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800244 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Enhanced");
246 default:
247 return std::string("Unknown ") +
248 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800249 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800250}
251
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700252SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800253
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700254SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
255 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700256 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700257 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700258 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700259 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700260 mCompositionEngine(mFactory.createCompositionEngine()),
261 mPhaseOffsets(mFactory.createPhaseOffsets()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800262
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700263SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800264 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800265
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900266 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800267
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900268 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700269
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900270 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700271
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900272 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800273
Steven Thomas050b2c82017-03-06 11:45:16 -0800274 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800276
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800278
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900279 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700280
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900281 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600282
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900283 mDefaultCompositionDataspace =
284 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700285 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
286 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900287 defaultCompositionDataspace = mDefaultCompositionDataspace;
288 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
289 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
290 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
291 wideColorGamutCompositionPixelFormat =
292 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700293
Yichi Chenda901bf2019-06-28 14:58:27 +0800294 mColorSpaceAgnosticDataspace =
295 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
300 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
301 switch (tmpPrimaryDisplayOrientation) {
302 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700303 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800304 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900305 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700306 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800307 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700309 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800310 break;
311 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700312 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800313 break;
314 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700315 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800316
Sundong Ahn85131bd2019-02-18 15:51:53 +0900317 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800318
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800319 // debugging stuff...
320 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700321
Mathias Agopianb4b17302013-03-20 18:36:41 -0700322 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700323 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700324
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800325 property_get("debug.sf.showupdates", value, "0");
326 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700327
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700328 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000329
330 // DDMS debugging deprecated (b/120782499)
331 property_get("debug.sf.ddms", value, "0");
332 int debugDdms = atoi(value);
333 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700334
335 property_get("debug.sf.disable_backpressure", value, "0");
336 mPropagateBackpressure = !atoi(value);
337 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700338
Ady Abrahamadb9a992019-09-19 21:21:55 +0000339 property_get("debug.sf.enable_gl_backpressure", value, "0");
340 mPropagateBackpressureClientComposition = atoi(value);
341 ALOGI_IF(mPropagateBackpressureClientComposition,
342 "Enabling backpressure propagation for Client Composition");
343
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800344 property_get("debug.sf.enable_hwc_vds", value, "0");
345 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800346 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800347
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800348 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800349 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800350 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700351
Yiwei Zhang243b3782018-05-15 17:40:04 -0700352 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700353 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
354 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
355
Ana Krulece5a06e02019-03-06 17:09:03 -0800356 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800357 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800358
359 int int_value = atoi(value);
360 if (int_value) {
361 mUseSmart90ForVideo = true;
362 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800363
Dan Stozaec460082018-12-17 15:35:09 -0800364 property_get("debug.sf.luma_sampling", value, "1");
365 mLumaSampling = atoi(value);
366
Romain Guy11d63f42017-07-20 12:47:14 -0700367 // We should be reading 'persist.sys.sf.color_saturation' here
368 // but since /data may be encrypted, we need to wait until after vold
369 // comes online to attempt to read the property. The property is
370 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800371
372 if (useTrebleTestingOverride()) {
373 // Without the override SurfaceFlinger cannot connect to HIDL
374 // services that are not listed in the manifests. Considered
375 // deriving the setting from the set service name, but it
376 // would be brittle if the name that's not 'default' is used
377 // for production purposes later on.
378 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
379 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380}
381
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800382void SurfaceFlinger::onFirstRef()
383{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800384 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800385}
386
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700387SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388
Dan Stozac7014012014-02-14 15:03:43 -0800389void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800390{
391 // the window manager died on us. prepare its eulogy.
392
Andy McFadden13a082e2012-08-24 10:16:42 -0700393 // restore initial conditions (default device unblank, etc)
394 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800395
396 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700397 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800398}
399
Robert Carr1db73f62016-12-21 12:58:51 -0800400static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700401 status_t err = client->initCheck();
402 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800403 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800404 }
Robert Carr1db73f62016-12-21 12:58:51 -0800405 return nullptr;
406}
407
408sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
409 return initClient(new Client(this));
410}
411
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700412sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
413 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700414{
415 class DisplayToken : public BBinder {
416 sp<SurfaceFlinger> flinger;
417 virtual ~DisplayToken() {
418 // no more references, this display must be terminated
419 Mutex::Autolock _l(flinger->mStateLock);
420 flinger->mCurrentState.displays.removeItem(this);
421 flinger->setTransactionFlags(eDisplayTransactionNeeded);
422 }
423 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700424 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700425 : flinger(flinger) {
426 }
427 };
428
429 sp<BBinder> token = new DisplayToken(this);
430
431 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700432 // Display ID is assigned when virtual display is allocated by HWC.
433 DisplayDeviceState state;
434 state.isSecure = secure;
435 state.displayName = displayName;
436 mCurrentState.displays.add(token, state);
437 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 return token;
439}
440
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700441void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700442 Mutex::Autolock _l(mStateLock);
443
Dominik Laskowski075d3172018-05-24 15:50:06 -0700444 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
445 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700446 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700447 return;
448 }
449
Dominik Laskowski075d3172018-05-24 15:50:06 -0700450 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
451 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700452 ALOGE("destroyDisplay called for non-virtual display");
453 return;
454 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700455 mInterceptor->saveDisplayDeletion(state.sequenceId);
456 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700457 setTransactionFlags(eDisplayTransactionNeeded);
458}
459
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800460std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
461 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700462
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800463 const auto internalDisplayId = getInternalDisplayIdLocked();
464 if (!internalDisplayId) {
465 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700466 }
467
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800468 std::vector<PhysicalDisplayId> displayIds;
469 displayIds.reserve(mPhysicalDisplayTokens.size());
470 displayIds.push_back(internalDisplayId->value);
471
472 for (const auto& [id, token] : mPhysicalDisplayTokens) {
473 if (id != *internalDisplayId) {
474 displayIds.push_back(id.value);
475 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700476 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800478 return displayIds;
479}
480
481sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
482 Mutex::Autolock lock(mStateLock);
483 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484}
485
Ady Abraham37965d42018-11-01 13:43:32 -0700486status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
487 if (!outGetColorManagement) {
488 return BAD_VALUE;
489 }
490 *outGetColorManagement = useColorManagement;
491 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700492}
493
Lloyd Pique441d5042018-10-18 16:49:51 -0700494HWComposer& SurfaceFlinger::getHwComposer() const {
495 return mCompositionEngine->getHwComposer();
496}
497
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700498renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
499 return mCompositionEngine->getRenderEngine();
500}
501
Lloyd Pique70d91362018-10-18 16:02:55 -0700502compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
503 return *mCompositionEngine.get();
504}
505
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800506void SurfaceFlinger::bootFinished()
507{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700508 if (mStartPropertySetThread->join() != NO_ERROR) {
509 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800510 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800511 const nsecs_t now = systemTime();
512 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000513 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700514
Mikael Pessa90092f42019-08-26 17:22:04 -0700515 mFrameTracer->initialize();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700516
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700517 // wait patiently for the window manager death
518 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700519 mWindowManager = defaultServiceManager()->getService(name);
520 if (mWindowManager != 0) {
521 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700522 }
Robert Carr720e5062018-07-30 17:45:14 -0700523 sp<IBinder> input(defaultServiceManager()->getService(
524 String16("inputflinger")));
525 if (input == nullptr) {
526 ALOGE("Failed to link to input service");
527 } else {
528 mInputFlinger = interface_cast<IInputFlinger>(input);
529 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700530
Steven Thomas050b2c82017-03-06 11:45:16 -0800531 if (mVrFlinger) {
532 mVrFlinger->OnBootFinished();
533 }
534
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700536 // formerly we would just kill the process, but we now ask it to exit so it
537 // can choose where to stop the animation.
538 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700539
540 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
541 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
542 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700543
Ana Krulecbd6654b2019-02-15 15:18:15 -0800544 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800545 readPersistentProperties();
546 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800547
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700548 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
549 // set the refresh rate according to the policy
550 const auto& performanceRefreshRate =
551 mRefreshRateConfigs->getRefreshRateFromType(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800552
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700553 if (isDisplayConfigAllowed(performanceRefreshRate.configId)) {
554 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
555 } else {
556 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
557 }
Ana Krulecbd6654b2019-02-15 15:18:15 -0800558 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800559 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800560}
561
Dan Stoza436ccf32018-06-21 12:10:12 -0700562uint32_t SurfaceFlinger::getNewTexture() {
563 {
564 std::lock_guard lock(mTexturePoolMutex);
565 if (!mTexturePool.empty()) {
566 uint32_t name = mTexturePool.back();
567 mTexturePool.pop_back();
568 ATRACE_INT("TexturePoolSize", mTexturePool.size());
569 return name;
570 }
571
572 // The pool was too small, so increase it for the future
573 ++mTexturePoolSize;
574 }
575
576 // The pool was empty, so we need to get a new texture name directly using a
577 // blocking call to the main thread
578 uint32_t name = 0;
579 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
580 return name;
581}
582
Mathias Agopian3f844832013-08-07 21:24:32 -0700583void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700584 std::lock_guard lock(mTexturePoolMutex);
585 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
586 // to actually delete this or not based on mTexturePoolSize
587 mTexturePool.push_back(texture);
588 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700589}
590
Wei Wangf9b05ee2017-07-19 20:59:39 -0700591// Do not call property_set on main thread which will be blocked by init
592// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700593void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700594 ALOGI( "SurfaceFlinger's main thread ready to run. "
595 "Initializing graphics H/W...");
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700596 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900597
Steven Thomasb02664d2017-07-26 18:48:28 -0700598 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800599
Steven Thomasb02664d2017-07-26 18:48:28 -0700600 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700601 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700602 renderEngineFeature |= (useColorManagement ?
603 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700604 renderEngineFeature |= (useContextPriority ?
605 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700606 renderEngineFeature |=
607 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
608 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700609
610 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800611 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700612 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700613 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800614 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700615
616 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
617 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700618 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
619 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800620 // Process any initial hotplug and resulting display changes.
621 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700622 const auto display = getDefaultDisplayDeviceLocked();
623 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700624 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700625 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800626
Steven Thomas050b2c82017-03-06 11:45:16 -0800627 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700628 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700629 // This callback is called from the vr flinger dispatch thread. We
630 // need to call signalTransaction(), which requires holding
631 // mStateLock when we're not on the main thread. Acquiring
632 // mStateLock from the vr flinger dispatch thread might trigger a
633 // deadlock in surface flinger (see b/66916578), so post a message
634 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700635 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700636 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
637 mVrFlingerRequestsDisplay = requestDisplay;
638 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700639 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800640 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700641 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
642 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700643 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700644 .value_or(0),
645 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800646 if (!mVrFlinger) {
647 ALOGE("Failed to start vrflinger");
648 }
649 }
650
Mathias Agopian92a979a2012-08-02 18:32:23 -0700651 // initialize our drawing state
652 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700653
Andy McFadden13a082e2012-08-24 10:16:42 -0700654 // set initial conditions (e.g. unblank default device)
655 initializeDisplays();
656
Steven Thomas137d4bc2019-07-25 16:55:14 -0700657 char primeShaderCache[PROPERTY_VALUE_MAX];
658 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
659 if (atoi(primeShaderCache)) {
660 getRenderEngine().primeCache();
661 }
Dan Stoza4e637772016-07-28 13:31:51 -0700662
Wei Wangf9b05ee2017-07-19 20:59:39 -0700663 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700664
665 const bool presentFenceReliable =
666 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
667 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700668
669 if (mStartPropertySetThread->Start() != NO_ERROR) {
670 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800671 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800672
Dan Stoza9e56aa02015-11-02 13:00:03 -0800673 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700674}
675
Romain Guy11d63f42017-07-20 12:47:14 -0700676void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700677 Mutex::Autolock _l(mStateLock);
678
Romain Guy11d63f42017-07-20 12:47:14 -0700679 char value[PROPERTY_VALUE_MAX];
680
681 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800682 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700683 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800684 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100685
686 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700687 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800688
689 property_get("persist.sys.sf.color_mode", value, "0");
690 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700691}
692
Mathias Agopiana67e4182012-06-19 17:26:12 -0700693void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800694 // Start boot animation service by setting a property mailbox
695 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700696 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800697 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698 if (mStartPropertySetThread->join() != NO_ERROR) {
699 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800700 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700701}
702
Mathias Agopian875d8e12013-06-07 15:35:48 -0700703size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700704 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700705}
706
Mathias Agopian875d8e12013-06-07 15:35:48 -0700707size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700708 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700709}
710
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800711// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800712
Jamie Gennis582270d2011-08-17 18:19:00 -0700713bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800714 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800715 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800716 return authenticateSurfaceTextureLocked(bufferProducer);
717}
718
719bool SurfaceFlinger::authenticateSurfaceTextureLocked(
720 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800721 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800722 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800723}
724
Brian Anderson6b376712017-04-04 10:51:39 -0700725status_t SurfaceFlinger::getSupportedFrameTimestamps(
726 std::vector<FrameEvent>* outSupported) const {
727 *outSupported = {
728 FrameEvent::REQUESTED_PRESENT,
729 FrameEvent::ACQUIRE,
730 FrameEvent::LATCH,
731 FrameEvent::FIRST_REFRESH_START,
732 FrameEvent::LAST_REFRESH_START,
733 FrameEvent::GPU_COMPOSITION_DONE,
734 FrameEvent::DEQUEUE_READY,
735 FrameEvent::RELEASE,
736 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700737 ConditionalLock _l(mStateLock,
738 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700739 if (!getHwComposer().hasCapability(
740 HWC2::Capability::PresentFenceIsNotReliable)) {
741 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
742 }
743 return NO_ERROR;
744}
745
Dominik Laskowski22488f62019-03-28 09:53:04 -0700746status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
747 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700748 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700749 return BAD_VALUE;
750 }
751
Dominik Laskowski22488f62019-03-28 09:53:04 -0700752 Mutex::Autolock lock(mStateLock);
753
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800754 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700755 if (!displayId) {
756 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700757 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700758
Mathias Agopian8b736f12012-08-13 17:54:26 -0700759 // TODO: Not sure if display density should handled by SF any longer
760 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700761 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700762 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700763 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800764 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700765 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700766 }
767 return density;
768 }
769 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700770 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700771 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700772 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700773 return getDensityFromProperty("ro.sf.lcd_density"); }
774 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700775
Dan Stoza7f7da322014-05-02 15:26:25 -0700776 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700777
Dominik Laskowski075d3172018-05-24 15:50:06 -0700778 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700779 DisplayInfo info = DisplayInfo();
780
Dan Stoza9e56aa02015-11-02 13:00:03 -0800781 float xdpi = hwConfig->getDpiX();
782 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700783
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700784 info.w = hwConfig->getWidth();
785 info.h = hwConfig->getHeight();
786 // Default display viewport to display width and height
787 info.viewportW = info.w;
788 info.viewportH = info.h;
789
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800790 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700791 // The density of the device is provided by a build property
792 float density = Density::getBuildDensity() / 160.0f;
793 if (density == 0) {
794 // the build doesn't provide a density -- this is wrong!
795 // use xdpi instead
796 ALOGE("ro.sf.lcd_density must be defined as a build property");
797 density = xdpi / 160.0f;
798 }
799 if (Density::getEmuDensity()) {
800 // if "qemu.sf.lcd_density" is specified, it overrides everything
801 xdpi = ydpi = density = Density::getEmuDensity();
802 density /= 160.0f;
803 }
804 info.density = density;
805
806 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700807 const auto display = getDefaultDisplayDeviceLocked();
808 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700809
810 // This is for screenrecord
811 const Rect viewport = display->getViewport();
812 if (viewport.isValid()) {
813 info.viewportW = uint32_t(viewport.getWidth());
814 info.viewportH = uint32_t(viewport.getHeight());
815 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700816 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700817 } else {
818 // TODO: where should this value come from?
819 static const int TV_DENSITY = 213;
820 info.density = TV_DENSITY / 160.0f;
821 info.orientation = 0;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700822
823 const auto display = getDisplayDeviceLocked(displayToken);
824 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 }
826
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 info.xdpi = xdpi;
828 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800829 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700830 const auto refreshRateType =
831 mRefreshRateConfigs->getRefreshRateTypeFromHwcConfigId(hwConfig->getId());
Ady Abraham796beb02019-04-11 15:23:07 -0700832 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
833 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800834
Andy McFadden91b2ca82014-06-13 14:04:23 -0700835 // This is how far in advance a buffer must be queued for
836 // presentation at a given time. If you want a buffer to appear
837 // on the screen at time N, you must submit the buffer before
838 // (N - presentationDeadline).
839 //
840 // Normally it's one full refresh period (to give SF a chance to
841 // latch the buffer), but this can be reduced by configuring a
842 // DispSync offset. Any additional delays introduced by the hardware
843 // composer or panel must be accounted for here.
844 //
845 // We add an additional 1ms to allow for processing time and
846 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700847 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700848
849 // All non-virtual displays are currently considered secure.
850 info.secure = true;
851
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800852 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700853 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800854 std::swap(info.w, info.h);
855 }
856
Michael Wright28f24d02016-07-12 13:30:53 -0700857 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700858 }
859
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 return NO_ERROR;
861}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700862
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700863status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
864 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700865 return BAD_VALUE;
866 }
867
Ana Krulecc2870422019-01-29 19:00:58 -0800868 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700869 return NO_ERROR;
870}
871
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700872int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
873 const auto display = getDisplayDevice(displayToken);
874 if (!display) {
875 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800876 return BAD_VALUE;
877 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700878
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700879 return display->getActiveConfig();
Dan Stoza7f7da322014-05-02 15:26:25 -0700880}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700881
Ady Abraham03b02dd2019-03-21 15:40:11 -0700882void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800883 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800884
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800885 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800886 // config twice. However event generation config might have changed so we need to update it
887 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800888 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700889 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
890 mDesiredActiveConfig = info;
891 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800892
893 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800894 // This will trigger HWC refresh without resetting the idle timer.
895 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700896 // Start receiving vsync samples now, so that we can detect a period
897 // switch.
898 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700899 // As we called to set period, we will call to onRefreshRateChangeCompleted once
900 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700901 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700902 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700903 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800904 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800905 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700906
907 if (mRefreshRateOverlay) {
908 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
909 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800910}
911
912status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
913 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800914
915 std::vector<int32_t> allowedConfig;
916 allowedConfig.push_back(mode);
917
918 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800919}
920
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800921void SurfaceFlinger::setActiveConfigInternal() {
922 ATRACE_CALL();
923
Dominik Laskowski22488f62019-03-28 09:53:04 -0700924 const auto display = getDefaultDisplayDeviceLocked();
925 if (!display) {
926 return;
927 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800928
Dominik Laskowski22488f62019-03-28 09:53:04 -0700929 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700930 mRefreshRateConfigs->setCurrentConfig(mUpcomingActiveConfig.configId);
931 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700932
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800933 display->setActiveConfig(mUpcomingActiveConfig.configId);
934
Alec Mouri754c98a2019-03-18 18:53:42 -0700935 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700936 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800937 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700938
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800939 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800940 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
941 mUpcomingActiveConfig.configId);
942 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800943}
944
Ady Abraham53852a52019-05-28 18:07:44 -0700945void SurfaceFlinger::desiredActiveConfigChangeDone() {
946 std::lock_guard<std::mutex> lock(mActiveConfigLock);
947 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
948 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700949
950 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
951 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700952 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700953}
954
Dominik Laskowski22488f62019-03-28 09:53:04 -0700955bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800956 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800957 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700958 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800959 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700960 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800961 return true;
962 }
963
964 // We received the present fence from the HWC, so we assume it successfully updated
965 // the config, hence we update SF.
966 mCheckPendingFence = false;
967 setActiveConfigInternal();
968 }
969
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800970 // Store the local variable to release the lock.
971 ActiveConfigInfo desiredActiveConfig;
972 {
973 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800974 if (!mDesiredActiveConfigChanged) {
975 return false;
976 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800977 desiredActiveConfig = mDesiredActiveConfig;
978 }
979
Dominik Laskowski22488f62019-03-28 09:53:04 -0700980 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800981 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
982 // display is not valid or we are already in the requested mode
983 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -0700984 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800985 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800986 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800987
Ady Abraham838de062019-02-04 10:24:03 -0800988 // Desired active config was set, it is different than the config currently in use, however
989 // allowed configs might have change by the time we process the refresh.
990 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -0700991 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -0700992 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -0800993 return false;
994 }
Alec Mouri7f015182019-07-11 13:56:22 -0700995
Ady Abrahamb838aed2019-02-12 15:30:16 -0800996 mUpcomingActiveConfig = desiredActiveConfig;
997 const auto displayId = display->getId();
998 LOG_ALWAYS_FATAL_IF(!displayId);
999
1000 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1001 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1002
1003 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001004 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001005 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001006 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001007}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001008
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001009status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1010 Vector<ColorMode>* outColorModes) {
1011 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001012 return BAD_VALUE;
1013 }
1014
Peiyong Lina52f0292018-03-14 17:26:31 -07001015 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001016 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001017 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001018 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1019
1020 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1021 if (!displayId) {
1022 return NAME_NOT_FOUND;
1023 }
1024
Dominik Laskowski075d3172018-05-24 15:50:06 -07001025 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001026 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001027 }
Michael Wright28f24d02016-07-12 13:30:53 -07001028 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001029
1030 // If it's built-in display and the configuration claims it's not wide color capable,
1031 // filter out all wide color modes. The typical reason why this happens is that the
1032 // hardware is not good enough to support GPU composition of wide color, and thus the
1033 // OEMs choose to disable this capability.
1034 if (isInternalDisplay && !hasWideColorDisplay) {
1035 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1036 isWideColorMode);
1037 } else {
1038 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1039 }
Michael Wright28f24d02016-07-12 13:30:53 -07001040
1041 return NO_ERROR;
1042}
1043
Daniel Solomon42d04562019-01-20 21:03:19 -08001044status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1045 ui::DisplayPrimaries &primaries) {
1046 if (!displayToken) {
1047 return BAD_VALUE;
1048 }
1049
1050 // Currently we only support this API for a single internal display.
1051 if (getInternalDisplayToken() != displayToken) {
1052 return BAD_VALUE;
1053 }
1054
1055 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1056 return NO_ERROR;
1057}
1058
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001059ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1060 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001061 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001062 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001063 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001064}
1065
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001066status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001067 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001068 Vector<ColorMode> modes;
1069 getDisplayColorModes(displayToken, &modes);
1070 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1071 if (mode < ColorMode::NATIVE || !exists) {
1072 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1073 decodeColorMode(mode).c_str(), mode, displayToken.get());
1074 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001075 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001076 const auto display = getDisplayDevice(displayToken);
1077 if (!display) {
1078 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1079 decodeColorMode(mode).c_str(), mode, displayToken.get());
1080 } else if (display->isVirtual()) {
1081 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1082 decodeColorMode(mode).c_str(), mode);
1083 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001084 display->getCompositionDisplay()->setColorProfile(
1085 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1086 RenderIntent::COLORIMETRIC,
1087 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001088 }
1089 }));
1090
Michael Wright28f24d02016-07-12 13:30:53 -07001091 return NO_ERROR;
1092}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001093
Svetoslavd85084b2014-03-20 10:28:31 -07001094status_t SurfaceFlinger::clearAnimationFrameStats() {
1095 Mutex::Autolock _l(mStateLock);
1096 mAnimFrameTracker.clearStats();
1097 return NO_ERROR;
1098}
1099
1100status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1101 Mutex::Autolock _l(mStateLock);
1102 mAnimFrameTracker.getStats(outStats);
1103 return NO_ERROR;
1104}
1105
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001106status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1107 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001108 Mutex::Autolock _l(mStateLock);
1109
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001110 const auto display = getDisplayDeviceLocked(displayToken);
1111 if (!display) {
1112 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001113 return BAD_VALUE;
1114 }
1115
Peiyong Linfb069302018-04-25 14:34:31 -07001116 // At this point the DisplayDeivce should already be set up,
1117 // meaning the luminance information is already queried from
1118 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001119 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001120 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1121 capabilities.getDesiredMaxLuminance(),
1122 capabilities.getDesiredMaxAverageLuminance(),
1123 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001124
1125 return NO_ERROR;
1126}
1127
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001128status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1129 ui::PixelFormat* outFormat,
1130 ui::Dataspace* outDataspace,
1131 uint8_t* outComponentMask) const {
1132 if (!outFormat || !outDataspace || !outComponentMask) {
1133 return BAD_VALUE;
1134 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001135 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001136 if (!display || !display->getId()) {
1137 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1138 return BAD_VALUE;
1139 }
1140 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1141 outDataspace, outComponentMask);
1142}
1143
Kevin DuBois74e53772018-11-19 10:52:38 -08001144status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1145 bool enable, uint8_t componentMask,
1146 uint64_t maxFrames) const {
1147 const auto display = getDisplayDevice(displayToken);
1148 if (!display || !display->getId()) {
1149 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1150 return BAD_VALUE;
1151 }
1152
1153 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1154 componentMask, maxFrames);
1155}
1156
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001157status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1158 uint64_t maxFrames, uint64_t timestamp,
1159 DisplayedFrameStats* outStats) const {
1160 const auto display = getDisplayDevice(displayToken);
1161 if (!display || !display->getId()) {
1162 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1163 return BAD_VALUE;
1164 }
1165
1166 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1167 outStats);
1168}
1169
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001170status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1171 if (!outSupported) {
1172 return BAD_VALUE;
1173 }
1174 *outSupported = getRenderEngine().supportsProtectedContent();
1175 return NO_ERROR;
1176}
1177
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001178status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1179 bool* outIsWideColorDisplay) const {
1180 if (!displayToken || !outIsWideColorDisplay) {
1181 return BAD_VALUE;
1182 }
1183 Mutex::Autolock _l(mStateLock);
1184 const auto display = getDisplayDeviceLocked(displayToken);
1185 if (!display) {
1186 return BAD_VALUE;
1187 }
Peiyong Linff84a152019-05-17 18:36:19 -07001188
1189 // Use hasWideColorDisplay to override built-in display.
1190 const auto displayId = display->getId();
1191 if (displayId && displayId == getInternalDisplayIdLocked()) {
1192 *outIsWideColorDisplay = hasWideColorDisplay;
1193 return NO_ERROR;
1194 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001195 *outIsWideColorDisplay = display->hasWideColorGamut();
1196 return NO_ERROR;
1197}
1198
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001199status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001200 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001201 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001202
Dominik Laskowski6505f792019-09-18 11:10:05 -07001203 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1204 mEventQueue->setEventConnection(
1205 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001206 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001207 }));
1208
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001209 return NO_ERROR;
1210}
1211
1212status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001213 Mutex::Autolock lock(mStateLock);
1214 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001215}
1216
Lloyd Pique755e3192018-01-31 16:46:15 -08001217status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1218 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001219 // Try to acquire a lock for 1s, fail gracefully
1220 const status_t err = mStateLock.timedLock(s2ns(1));
1221 const bool locked = (err == NO_ERROR);
1222 if (!locked) {
1223 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1224 return TIMED_OUT;
1225 }
1226
1227 outLayers->clear();
1228 mCurrentState.traverseInZOrder([&](Layer* layer) {
1229 outLayers->push_back(layer->getLayerDebugInfo());
1230 });
1231
1232 mStateLock.unlock();
1233 return NO_ERROR;
1234}
1235
Peiyong Linc6780972018-10-28 15:24:08 -07001236status_t SurfaceFlinger::getCompositionPreference(
1237 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1238 Dataspace* outWideColorGamutDataspace,
1239 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001240 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001241 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001242 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001243 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001244 return NO_ERROR;
1245}
1246
Dan Stozaec460082018-12-17 15:35:09 -08001247status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1248 const sp<IBinder>& stopLayerHandle,
1249 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001250 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001251 return BAD_VALUE;
1252 }
1253 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001254 return NO_ERROR;
1255}
1256
Dan Stozaec460082018-12-17 15:35:09 -08001257status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001258 if (!listener) {
1259 return BAD_VALUE;
1260 }
Dan Stozaec460082018-12-17 15:35:09 -08001261 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001262 return NO_ERROR;
1263}
Dan Gittik57e63c52019-01-18 16:37:54 +00001264
1265status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1266 bool* outSupport) const {
1267 if (!displayToken || !outSupport) {
1268 return BAD_VALUE;
1269 }
1270 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1271 if (!displayId) {
1272 return NAME_NOT_FOUND;
1273 }
1274 *outSupport =
1275 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1276 return NO_ERROR;
1277}
1278
1279status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1280 float brightness) const {
1281 if (!displayToken) {
1282 return BAD_VALUE;
1283 }
1284 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1285 if (!displayId) {
1286 return NAME_NOT_FOUND;
1287 }
1288 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1289}
1290
Ady Abraham8532d012019-05-08 14:50:56 -07001291status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1292 PowerHint powerHint = static_cast<PowerHint>(hintId);
1293
1294 if (powerHint == PowerHint::INTERACTION) {
1295 mScheduler->notifyTouchEvent();
1296 }
1297
1298 return NO_ERROR;
1299}
1300
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001301// ----------------------------------------------------------------------------
1302
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001303sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001304 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001305 const auto& handle =
1306 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001307
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001308 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001309}
1310
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001311// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001312
1313void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001314 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001315}
1316
1317void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001318 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001319 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001320}
1321
1322void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001323 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001324 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001325}
1326
1327void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001328 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001329 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001330}
1331
1332status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001333 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001334 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001335}
1336
1337status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001338 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001339 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001340 if (res == NO_ERROR) {
1341 msg->wait();
1342 }
1343 return res;
1344}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001345
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001346void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001347 do {
1348 waitForEvent();
1349 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001350}
1351
Dominik Laskowski83b88212018-12-11 13:34:06 -08001352nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001353 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001354 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1355 return 0;
1356 }
1357
1358 const auto config = getHwComposer().getActiveConfig(*displayId);
1359 return config ? config->getVsyncPeriod() : 0;
1360}
1361
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001362void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1363 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001364 ATRACE_NAME("SF onVsync");
1365
Steven Thomas3cfac282017-02-06 12:29:30 -08001366 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001367 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001368 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001369 return;
1370 }
1371
Dominik Laskowski075d3172018-05-24 15:50:06 -07001372 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001373 return;
1374 }
1375
Dominik Laskowski075d3172018-05-24 15:50:06 -07001376 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001377 // For now, we don't do anything with external display vsyncs.
1378 return;
1379 }
1380
Alec Mourif8e689c2019-05-20 18:32:22 -07001381 bool periodFlushed = false;
1382 mScheduler->addResyncSample(timestamp, &periodFlushed);
1383 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001384 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001385 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001386}
1387
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001388void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001389 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1390 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001391}
1392
Ady Abraham261614e2019-07-10 17:53:12 -07001393bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001394 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001395}
1396
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001397void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001398 const auto display = getDefaultDisplayDeviceLocked();
1399 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001400 return;
1401 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001402 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001403
Ana Krulec7d1d6832018-12-27 11:10:09 -08001404 // Don't do any updating if the current fps is the same as the new one.
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001405 const auto& refreshRateConfig = mRefreshRateConfigs->getRefreshRateFromType(refreshRate);
1406 const int desiredConfigId = refreshRateConfig.configId;
Alec Mouri0a1cc962019-03-14 12:33:02 -07001407
Dominik Laskowski22488f62019-03-28 09:53:04 -07001408 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001409 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1410 return;
1411 }
1412
Dominik Laskowski22488f62019-03-28 09:53:04 -07001413 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001414}
1415
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001416void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001417 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001418 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001419 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001420
Lloyd Piqueba04e622017-12-14 17:11:26 -08001421 // Ignore events that do not have the right sequenceId.
1422 if (sequenceId != getBE().mComposerSequenceId) {
1423 return;
1424 }
1425
Steven Thomasb02664d2017-07-26 18:48:28 -07001426 // Only lock if we're not on the main thread. This function is normally
1427 // called on a hwbinder thread, but for the primary display it's called on
1428 // the main thread with the state lock already held, so don't attempt to
1429 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001430 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001431
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001432 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001433
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001434 if (std::this_thread::get_id() == mMainThreadId) {
1435 // Process all pending hot plug events immediately if we are on the main thread.
1436 processDisplayHotplugEventsLocked();
1437 }
1438
Lloyd Piqueba04e622017-12-14 17:11:26 -08001439 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001440}
1441
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001442void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001443 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001444 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001445 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001446 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001447 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001448}
1449
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001450void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001451 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001452
1453 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1454 // display power state.
1455 postMessageAsync(new LambdaMessage(
1456 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1457}
1458
1459void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1460 ATRACE_CALL();
1461
Ady Abraham27c70212019-06-11 10:52:26 -07001462 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1463
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001464 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001465 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1466 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001467 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001468 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001469 }
Mathias Agopian86303202012-07-24 22:46:10 -07001470}
1471
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001472// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001473void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001474 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001475 // Clear the drawing state so that the logic inside of
1476 // handleTransactionLocked will fire. It will determine the delta between
1477 // mCurrentState and mDrawingState and re-apply all changes when we make the
1478 // transition.
1479 mDrawingState.displays.clear();
1480 mDisplays.clear();
1481}
1482
Steven Thomas050b2c82017-03-06 11:45:16 -08001483void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001484 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001485 if (!mVrFlinger)
1486 return;
1487 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001488 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001489 return;
1490 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001491
Lloyd Pique441d5042018-10-18 16:49:51 -07001492 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001493 ALOGE("Vr flinger is only supported for remote hardware composer"
1494 " service connections. Ignoring request to transition to vr"
1495 " flinger.");
1496 mVrFlingerRequestsDisplay = false;
1497 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001498 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001499
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001500 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001501
Steven Thomas0123ac62018-07-12 11:32:34 -07001502 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001503 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001504
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001505 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001506
1507 // Clear out all the output layers from the composition engine for all
1508 // displays before destroying the hardware composer interface. This ensures
1509 // any HWC layers are destroyed through that interface before it becomes
1510 // invalid.
1511 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001512 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001513 }
1514
Steven Thomas0123ac62018-07-12 11:32:34 -07001515 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1516 // called below. Clear the reference now so we don't accidentally use it
1517 // later.
1518 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001519
Steven Thomasb02664d2017-07-26 18:48:28 -07001520 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001521 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001522 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001523
Steven Thomasb02664d2017-07-26 18:48:28 -07001524 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001525 // Delete the current instance before creating the new one
1526 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1527 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1528 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1529 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001530
Lloyd Pique441d5042018-10-18 16:49:51 -07001531 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001532 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001533
1534 if (vrFlingerRequestsDisplay) {
1535 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001536 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001537
1538 mVisibleRegionsDirty = true;
1539 invalidateHwcGeometry();
1540
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001541 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001542 display = getDefaultDisplayDeviceLocked();
1543 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001544 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001545
Steven Thomasb02664d2017-07-26 18:48:28 -07001546 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001547 const nsecs_t vsyncPeriod = getVsyncPeriod();
1548 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001549
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001550 // The present fences returned from vr_hwc are not an accurate
1551 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001552 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001553
Steven Thomasb02664d2017-07-26 18:48:28 -07001554 // Use phase of 0 since phase is not known.
1555 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001556 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001557 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001558
Ana Krulecc2870422019-01-29 19:00:58 -08001559 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001560
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001561 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001562 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001563}
1564
Ady Abraham11579302019-09-19 12:35:58 -07001565bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1566 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001567 // We are storing the last 2 present fences. If sf's phase offset is to be
1568 // woken up before the actual vsync but targeting the next vsync, we need to check
1569 // fence N-2
1570 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001571 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001572 ? mPreviousPresentFences[0]
1573 : mPreviousPresentFences[1];
1574
Ady Abraham11579302019-09-19 12:35:58 -07001575 if (fence == Fence::NO_FENCE) {
1576 return false;
1577 }
1578
1579 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1580 fence->wait(graceTimeMs);
1581 }
1582
1583 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001584}
1585
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001586void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001587 DisplayStatInfo stats;
1588 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001589 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001590 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001591 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001592 mPhaseOffsets->getOffsetThresholdForNextVsync()
1593 ? presentTime
1594 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001595}
1596
Dominik Laskowski22488f62019-03-28 09:53:04 -07001597void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001598 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001599 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001600 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001601 // calculate the expected present time once and use the cached
1602 // value throughout this frame to make sure all layers are
1603 // seeing this same value.
1604 populateExpectedPresentTime();
1605
Ady Abraham11579302019-09-19 12:35:58 -07001606 // When Backpressure propagation is enabled we want to give a small grace period
1607 // for the present fence to fire instead of just giving up on this frame to handle cases
1608 // where present fence is just about to get signaled.
1609 const int graceTimeForPresentFenceMs =
1610 (mPropagateBackpressure &&
1611 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1612 ? 1
1613 : 0;
1614 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1615 previousFrameMissed(
1616 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001617 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1618 mHadDeviceComposition && frameMissed};
1619 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1620 mHadClientComposition && frameMissed};
1621
Alec Mouricc0fc602019-02-26 21:45:19 -08001622 if (frameMissed) {
1623 mFrameMissedCount++;
1624 mTimeStats->incrementMissedFrames();
1625 }
1626
Alec Mouri40189b02019-03-05 15:07:54 -08001627 if (hwcFrameMissed) {
1628 mHwcFrameMissedCount++;
1629 }
1630
1631 if (gpuFrameMissed) {
1632 mGpuFrameMissedCount++;
1633 }
1634
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001635 if (mUseSmart90ForVideo) {
1636 // This call is made each time SF wakes up and creates a new frame. It is part
1637 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001638 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001639 }
1640
Ady Abrahamb838aed2019-02-12 15:30:16 -08001641 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001642 break;
1643 }
1644
Ady Abrahamadb9a992019-09-19 21:21:55 +00001645 if (frameMissed && mPropagateBackpressure) {
1646 if ((hwcFrameMissed && !gpuFrameMissed) ||
1647 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001648 signalLayerUpdate();
1649 break;
1650 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001651 }
Dan Stoza50182882016-07-08 12:02:20 -07001652
Steven Thomas050b2c82017-03-06 11:45:16 -08001653 // Now that we're going to make it to the handleMessageTransaction()
1654 // call below it's safe to call updateVrFlinger(), which will
1655 // potentially trigger a display handoff.
1656 updateVrFlinger();
1657
Dan Stoza6b9454d2014-11-07 16:00:59 -08001658 bool refreshNeeded = handleMessageTransaction();
1659 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001660
1661 updateCursorAsync();
1662 updateInputFlinger();
1663
Dan Stoza58784442014-12-02 16:58:17 -08001664 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001665 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001666 // Signal a refresh if a transaction modified the window state,
1667 // a new buffer was latched, or if HWC has requested a full
1668 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001669 signalRefresh();
1670 }
1671 break;
1672 }
1673 case MessageQueue::REFRESH: {
1674 handleMessageRefresh();
1675 break;
1676 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001677 }
1678}
1679
Dan Stoza6b9454d2014-11-07 16:00:59 -08001680bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001681 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001682 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001683
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001684 bool flushedATransaction = flushTransactionQueues();
1685
1686 bool runHandleTransaction = transactionFlags &&
1687 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1688
1689 if (runHandleTransaction) {
1690 handleTransaction(eTransactionMask);
1691 } else {
1692 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001693 }
1694
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001695 if (transactionFlushNeeded()) {
1696 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001697 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001698
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001699 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001700}
1701
Mathias Agopian4fec8732012-06-29 14:12:52 -07001702void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001703 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001704
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001705 mRefreshPending = false;
1706
Lloyd Piqueab039b52019-02-13 14:22:42 -08001707 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001708 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001709 for (const auto& [_, display] : mDisplays) {
1710 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1711 }
1712 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1713 auto compositionLayer = layer->getCompositionLayer();
1714 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1715 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001716 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1717 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1718 auto compositionLayer = layer->getCompositionLayer();
1719 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
1720 }
1721
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001722 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001723 refreshArgs.outputColorSetting = useColorManagement
1724 ? mDisplayColorSetting
1725 : compositionengine::OutputColorSetting::kUnmanaged;
1726 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1727 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001728
1729 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1730 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001731
1732 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1733 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1734 mDrawingState.colorMatrixChanged = false;
1735 }
1736
1737 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1738
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001739 if (mDebugRegion != 0) {
1740 refreshArgs.devOptFlashDirtyRegionsDelay =
1741 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1742 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001743
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001744 mGeometryInvalid = false;
1745
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001746 mCompositionEngine->present(refreshArgs);
1747
David Sodmanfa9b2af2017-12-24 13:28:59 -08001748 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001749 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001750
Lloyd Pique66d68602019-02-13 14:23:31 -08001751 mHadClientComposition =
1752 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1753 auto& displayDevice = tokenDisplayPair.second;
1754 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1755 });
1756 mHadDeviceComposition =
1757 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1758 auto& displayDevice = tokenDisplayPair.second;
1759 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1760 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001761
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001762 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001763
David Sodman7e4ae112018-02-09 15:02:28 -08001764 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001765 if (mVisibleRegionsDirty) {
1766 mVisibleRegionsDirty = false;
1767 if (mTracingEnabled) {
1768 mTracing.notify("visibleRegionsDirty");
1769 }
1770 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001771
1772 if (mCompositionEngine->needsAnotherUpdate()) {
1773 signalLayerUpdate();
1774 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001775}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001776
David Sodmanfa9b2af2017-12-24 13:28:59 -08001777
1778bool SurfaceFlinger::handleMessageInvalidate() {
1779 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001780 bool refreshNeeded = handlePageFlip();
1781
Vishnu Nair4351ad52019-02-11 14:13:02 -08001782 if (mVisibleRegionsDirty) {
1783 computeLayerBounds();
1784 }
1785
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001786 for (auto& layer : mLayersPendingRefresh) {
1787 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001788 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001789 invalidateLayerStack(layer, visibleReg);
1790 }
1791 mLayersPendingRefresh.clear();
1792 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001793}
1794
Ana Krulece588e312018-09-18 12:32:24 -07001795void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1796 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001797 // Update queue of past composite+present times and determine the
1798 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001799 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001800 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001801 while (!getBE().mCompositePresentTimes.empty()) {
1802 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001803 // Cached values should have been updated before calling this method,
1804 // which helps avoid duplicate syscalls.
1805 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1806 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1807 break;
1808 }
1809 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001810 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001811 }
1812
1813 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001814 while (getBE().mCompositePresentTimes.size() > 16) {
1815 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001816 }
1817
Ana Krulece588e312018-09-18 12:32:24 -07001818 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001819}
1820
Ana Krulece588e312018-09-18 12:32:24 -07001821void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1822 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001823 // Integer division and modulo round toward 0 not -inf, so we need to
1824 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001825 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1826 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1827 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001828
Ana Krulec757f63a2019-01-25 10:46:18 -08001829 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001830 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001831 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001832 }
1833
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001834 // Snap the latency to a value that removes scheduling jitter from the
1835 // composition and present times, which often have >1ms of jitter.
1836 // Reducing jitter is important if an app attempts to extrapolate
1837 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001838 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001839 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001840 nsecs_t bias = stats.vsyncPeriod / 2;
1841 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1842 nsecs_t snappedCompositeToPresentLatency =
1843 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001844
David Sodman99974d22017-11-28 12:04:33 -08001845 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001846 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1847 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001848 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001849}
1850
David Sodman2b406362017-12-15 13:33:47 -08001851void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001852{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001853 ATRACE_CALL();
1854 ALOGV("postComposition");
1855
Brian Anderson3546a3f2016-07-14 11:51:14 -07001856 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001857 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001858 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001859 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001860 }
1861
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001862 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001863 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001864
David Sodman73beded2017-11-15 11:56:06 -08001865 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001866 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08001867 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001868 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001869 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1870 ->getRenderSurface()
1871 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001872 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001873 } else {
1874 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1875 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001876
David Sodman73beded2017-11-15 11:56:06 -08001877 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001878 mPreviousPresentFences[1] = mPreviousPresentFences[0];
1879 mPreviousPresentFences[0] = displayDevice
1880 ? getHwComposer().getPresentFence(*displayDevice->getId())
1881 : Fence::NO_FENCE;
1882 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08001883 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001884
Ana Krulece588e312018-09-18 12:32:24 -07001885 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08001886 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001887
Lloyd Piqueab039b52019-02-13 14:22:42 -08001888 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
1889 // be sampled a little later than when we started doing work for this frame,
1890 // but that should be okay since updateCompositorTiming has snapping logic.
1891 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
1892 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001893 CompositorTiming compositorTiming;
1894 {
David Sodman99974d22017-11-28 12:04:33 -08001895 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1896 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001897 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001898
Robert Carr2047fae2016-11-28 14:09:09 -08001899 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001900 bool frameLatched =
1901 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
1902 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001903 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001904 recordBufferingStats(layer->getName().string(),
1905 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001906 }
Robert Carr2047fae2016-11-28 14:09:09 -08001907 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001908
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001909 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001910 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001911 }
1912
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001913 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001914 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1915 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001916 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001917 }
1918 }
1919
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001920 if (mAnimCompositionPending) {
1921 mAnimCompositionPending = false;
1922
Brian Anderson4e606e32017-03-16 15:34:57 -07001923 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001924 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001925 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07001926 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001927 // The HWC doesn't support present fences, so use the refresh
1928 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07001929 const nsecs_t presentTime =
1930 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001931 mAnimFrameTracker.setActualPresentTime(presentTime);
1932 }
1933 mAnimFrameTracker.advanceFrame();
1934 }
Dan Stozab90cf072015-03-05 11:05:59 -08001935
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001936 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001937 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001938 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001939 }
1940
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001941 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001942
Lloyd Pique32cbe282018-10-19 13:09:22 -07001943 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1944 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001945 return;
1946 }
1947
1948 nsecs_t currentTime = systemTime();
1949 if (mHasPoweredOff) {
1950 mHasPoweredOff = false;
1951 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001952 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001953 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001954 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1955 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001956 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001957 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001958 }
David Sodman4a36e932017-11-07 14:29:47 -08001959 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001960 }
David Sodman4a36e932017-11-07 14:29:47 -08001961 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001962
1963 {
1964 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07001965 if (mTexturePool.size() < mTexturePoolSize) {
1966 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07001967 const size_t offset = mTexturePool.size();
1968 mTexturePool.resize(mTexturePoolSize);
1969 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1970 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07001971 } else if (mTexturePool.size() > mTexturePoolSize) {
1972 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
1973 const size_t offset = mTexturePoolSize;
1974 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
1975 mTexturePool.resize(mTexturePoolSize);
1976 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07001977 }
1978 }
Marissa Walle2ffb422018-10-12 11:33:52 -07001979
Ady Abrahambe0f9482019-04-24 15:41:53 -07001980 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07001981 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08001982
Kevin DuBois413287f2019-02-25 08:46:47 -08001983 if (mLumaSampling && mRegionSamplingThread) {
1984 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08001985 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07001986
1987 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
1988 // side-effect of getTotalSize(), so we check that again here
1989 if (ATRACE_ENABLED()) {
1990 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
1991 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001992}
1993
Vishnu Nair4351ad52019-02-11 14:13:02 -08001994void SurfaceFlinger::computeLayerBounds() {
1995 for (const auto& pair : mDisplays) {
1996 const auto& displayDevice = pair.second;
1997 const auto display = displayDevice->getCompositionDisplay();
1998 for (const auto& layer : mDrawingState.layersSortedByZ) {
1999 // only consider the layers on the given layer stack
2000 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002001 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002002 }
2003
2004 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2005 }
2006 }
2007}
2008
David Sodmanfa9b2af2017-12-24 13:28:59 -08002009void SurfaceFlinger::postFrame()
2010{
2011 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002012 const auto display = getDefaultDisplayDeviceLocked();
2013 if (display && getHwComposer().isConnected(*display->getId())) {
2014 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002015 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2016 logFrameStats();
2017 }
2018 }
2019}
2020
Mathias Agopian87baae12012-07-31 12:38:26 -07002021void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002022{
Mathias Agopian841cde52012-03-01 15:44:37 -08002023 ATRACE_CALL();
2024
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002025 // here we keep a copy of the drawing state (that is the state that's
2026 // going to be overwritten by handleTransactionLocked()) outside of
2027 // mStateLock so that the side-effects of the State assignment
2028 // don't happen with mStateLock held (which can cause deadlocks).
2029 State drawingState(mDrawingState);
2030
Mathias Agopianca4d3602011-05-19 15:38:14 -07002031 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002032 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002033
Mathias Agopianca4d3602011-05-19 15:38:14 -07002034 // Here we're guaranteed that some transaction flags are set
2035 // so we can call handleTransactionLocked() unconditionally.
2036 // We call getTransactionFlags(), which will also clear the flags,
2037 // with mStateLock held to guarantee that mCurrentState won't change
2038 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002039
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002040 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002041 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002042 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002043
Mathias Agopianca4d3602011-05-19 15:38:14 -07002044 mDebugInTransaction = 0;
2045 invalidateHwcGeometry();
2046 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002047}
2048
Lloyd Piqueba04e622017-12-14 17:11:26 -08002049void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2050 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002051 const std::optional<DisplayIdentificationInfo> info =
2052 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002053
Dominik Laskowski075d3172018-05-24 15:50:06 -07002054 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002055 continue;
2056 }
2057
Lloyd Piqueba04e622017-12-14 17:11:26 -08002058 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002059 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002060 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002061 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2062 initScheduler(info->id);
2063 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002064 mPhysicalDisplayTokens[info->id] = new BBinder();
2065 DisplayDeviceState state;
2066 state.displayId = info->id;
2067 state.isSecure = true; // All physical displays are currently considered secure.
2068 state.displayName = info->name;
2069 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2070 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002071 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002072 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002073 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002074
Dominik Laskowski075d3172018-05-24 15:50:06 -07002075 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2076 if (index >= 0) {
2077 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2078 mInterceptor->saveDisplayDeletion(state.sequenceId);
2079 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002080 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002081 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002082 }
2083
2084 processDisplayChangesLocked();
2085 }
2086
2087 mPendingHotplugEvents.clear();
2088}
2089
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002090void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002091 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2092 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002093}
2094
Lloyd Pique99d3da52018-01-22 17:48:03 -08002095sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002096 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002097 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002098 const sp<IGraphicBufferProducer>& producer) {
2099 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002100 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002101 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002102 creationArgs.isSecure = state.isSecure;
2103 creationArgs.displaySurface = dispSurface;
2104 creationArgs.hasWideColorGamut = false;
2105 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002106 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002107
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002108 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002109 creationArgs.isPrimary = isInternalDisplay;
2110
2111 if (useColorManagement && displayId) {
2112 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002113 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002114 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002115 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002116 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002117
Dominik Laskowski7e045462018-05-30 13:02:02 -07002118 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002119 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002120 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002121 }
tangrobin6753a022018-08-10 10:58:54 +08002122 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002123
Dominik Laskowski075d3172018-05-24 15:50:06 -07002124 if (displayId) {
2125 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002126 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002127 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002128 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002129
Lloyd Pique90c115d2018-09-18 21:39:42 -07002130 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002131 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002132 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002133
Lloyd Pique99d3da52018-01-22 17:48:03 -08002134 // Make sure that composition can never be stalled by a virtual display
2135 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002136 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002137 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002138 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2139 }
2140
Dominik Laskowski075d3172018-05-24 15:50:06 -07002141 creationArgs.displayInstallOrientation =
2142 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002143
Lloyd Pique99d3da52018-01-22 17:48:03 -08002144 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002145 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002146
Lloyd Pique90c115d2018-09-18 21:39:42 -07002147 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002148
2149 if (maxFrameBufferAcquiredBuffers >= 3) {
2150 nativeWindowSurface->preallocateBuffers();
2151 }
2152
2153 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002154 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002155 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002156 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002157 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002158 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002159 display->getCompositionDisplay()->setColorProfile(
2160 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2161 RenderIntent::COLORIMETRIC,
2162 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002163 if (!state.isVirtual()) {
2164 LOG_ALWAYS_FATAL_IF(!displayId);
2165 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002166 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002167
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002168 display->setLayerStack(state.layerStack);
2169 display->setProjection(state.orientation, state.viewport, state.frame);
2170 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002171
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002172 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002173}
2174
Lloyd Pique347200f2017-12-14 17:00:15 -08002175void SurfaceFlinger::processDisplayChangesLocked() {
2176 // here we take advantage of Vector's copy-on-write semantics to
2177 // improve performance by skipping the transaction entirely when
2178 // know that the lists are identical
2179 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2180 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2181 if (!curr.isIdenticalTo(draw)) {
2182 mVisibleRegionsDirty = true;
2183 const size_t cc = curr.size();
2184 size_t dc = draw.size();
2185
2186 // find the displays that were removed
2187 // (ie: in drawing state but not in current state)
2188 // also handle displays that changed
2189 // (ie: displays that are in both lists)
2190 for (size_t i = 0; i < dc;) {
2191 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2192 if (j < 0) {
2193 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002194 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002195 // Save display ID before disconnecting.
2196 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002197 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002198
2199 if (!display->isVirtual()) {
2200 LOG_ALWAYS_FATAL_IF(!displayId);
2201 dispatchDisplayHotplugEvent(displayId->value, false);
2202 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002203 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002204
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002205 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002206 } else {
2207 // this display is in both lists. see if something changed.
2208 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002209 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002210 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2211 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2212 if (state_binder != draw_binder) {
2213 // changing the surface is like destroying and
2214 // recreating the DisplayDevice, so we just remove it
2215 // from the drawing state, so that it get re-added
2216 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002217 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002218 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002219 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002220 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002221 mDrawingState.displays.removeItemsAt(i);
2222 dc--;
2223 // at this point we must loop to the next item
2224 continue;
2225 }
2226
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002227 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002228 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002229 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002230 }
2231 if ((state.orientation != draw[i].orientation) ||
2232 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002233 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002234 }
2235 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002236 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002237 }
2238 }
2239 }
2240 ++i;
2241 }
2242
2243 // find displays that were added
2244 // (ie: in current state but not in drawing state)
2245 for (size_t i = 0; i < cc; i++) {
2246 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2247 const DisplayDeviceState& state(curr[i]);
2248
Lloyd Pique542307f2018-10-19 13:24:08 -07002249 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002250 sp<IGraphicBufferProducer> producer;
2251 sp<IGraphicBufferProducer> bqProducer;
2252 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002253 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002254
Dominik Laskowski075d3172018-05-24 15:50:06 -07002255 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002256 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002257 // Virtual displays without a surface are dormant:
2258 // they have external state (layer stack, projection,
2259 // etc.) but no internal state (i.e. a DisplayDevice).
2260 if (state.surface != nullptr) {
2261 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002262 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002263 int width = 0;
2264 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2265 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2266 int height = 0;
2267 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2268 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2269 int intFormat = 0;
2270 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2271 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002272 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002273
Dominik Laskowski075d3172018-05-24 15:50:06 -07002274 displayId =
2275 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002276 }
2277
2278 // TODO: Plumb requested format back up to consumer
2279
2280 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002281 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002282 bqProducer, bqConsumer,
2283 state.displayName);
2284
2285 dispSurface = vds;
2286 producer = vds;
2287 }
2288 } else {
2289 ALOGE_IF(state.surface != nullptr,
2290 "adding a supported display, but rendering "
2291 "surface is provided (%p), ignoring it",
2292 state.surface.get());
2293
Dominik Laskowski075d3172018-05-24 15:50:06 -07002294 displayId = state.displayId;
2295 LOG_ALWAYS_FATAL_IF(!displayId);
2296 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002297 producer = bqProducer;
2298 }
2299
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002300 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002301 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002302 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002303 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002304 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002305 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002306 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002307 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002308 }
2309 }
2310 }
2311 }
2312 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002313
2314 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002315}
2316
Mathias Agopian87baae12012-07-31 12:38:26 -07002317void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002318{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002319 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2320
Dan Stoza7dde5992015-05-22 09:51:44 -07002321 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002322 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2323 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002324 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002325
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002326 /*
2327 * Traversal of the children
2328 * (perform the transaction for each of them if needed)
2329 */
2330
Marissa Wall06255332019-03-27 13:48:27 -07002331 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002332 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002333 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002334 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335
2336 const uint32_t flags = layer->doTransaction(0);
2337 if (flags & Layer::eVisibleRegion)
2338 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002339
2340 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002341 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002342 }
Robert Carr2047fae2016-11-28 14:09:09 -08002343 });
Marissa Wall06255332019-03-27 13:48:27 -07002344 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002345 }
2346
2347 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002348 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002349 */
2350
Mathias Agopiane57f2922012-08-09 16:29:12 -07002351 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002352 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002353 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002354 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002355
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002356 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002357 // The transform hint might have changed for some layers
2358 // (either because a display has changed, or because a layer
2359 // as changed).
2360 //
2361 // Walk through all the layers in currentLayers,
2362 // and update their transform hint.
2363 //
2364 // If a layer is visible only on a single display, then that
2365 // display is used to calculate the hint, otherwise we use the
2366 // default display.
2367 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002368 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002369 // the hint is set before we acquire a buffer from the surface texture.
2370 //
2371 // NOTE: layer transactions have taken place already, so we use their
2372 // drawing state. However, SurfaceFlinger's own transaction has not
2373 // happened yet, so we must use the current state layer list
2374 // (soon to become the drawing state list).
2375 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002376 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002377 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002378 bool first = true;
2379 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002380 // NOTE: we rely on the fact that layers are sorted by
2381 // layerStack first (so we don't have to traverse the list
2382 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002383 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002384 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002385 currentlayerStack = layerStack;
2386 // figure out if this layerstack is mirrored
2387 // (more than one display) if so, pick the default display,
2388 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002389 hintDisplay = nullptr;
2390 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002391 if (display->getCompositionDisplay()
2392 ->belongsInOutput(layer->getLayerStack(),
2393 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002394 if (hintDisplay) {
2395 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002396 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002397 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002398 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002399 }
2400 }
2401 }
2402 }
Chet Haase91d25932013-04-11 15:24:55 -07002403
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002404 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002405 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2406 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002407
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002408 // could be null when this layer is using a layerStack
2409 // that is not visible on any display. Also can occur at
2410 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002411 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002412 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002413
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002414 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002415 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002416 if (hintDisplay) {
2417 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002418 }
Robert Carr2047fae2016-11-28 14:09:09 -08002419
2420 first = false;
2421 });
Mathias Agopian84300952012-11-21 16:02:13 -08002422 }
2423
2424
Mathias Agopian3559b072012-08-15 13:46:03 -07002425 /*
2426 * Perform our own transaction if needed
2427 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002428
2429 if (mLayersAdded) {
2430 mLayersAdded = false;
2431 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002432 mVisibleRegionsDirty = true;
2433 }
2434
2435 // some layers might have been removed, so
2436 // we need to update the regions they're exposing.
2437 if (mLayersRemoved) {
2438 mLayersRemoved = false;
2439 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002440 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002441 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002442 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002443 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002444 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002445 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002446 }
Robert Carr2047fae2016-11-28 14:09:09 -08002447 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002448 }
2449
Vishnu Nairec0ab382019-02-13 15:32:56 -08002450 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002451 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002452}
2453
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002454void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002455 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002456 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002457 return;
2458 }
2459
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002460 if (mVisibleRegionsDirty || mInputInfoChanged) {
2461 mInputInfoChanged = false;
2462 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002463 } else if (mInputWindowCommands.syncInputWindows) {
2464 // If the caller requested to sync input windows, but there are no
2465 // changes to input windows, notify immediately.
2466 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002467 }
2468
Arthur Hung6cbb9752019-09-05 16:38:18 +08002469 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002470}
2471
2472void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002473 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002474
2475 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2476 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002477 // When calculating the screen bounds we ignore the transparent region since it may
2478 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002479 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002480 }
2481 });
chaviw291d88a2019-02-14 10:33:58 -08002482
2483 mInputFlinger->setInputWindows(inputHandles,
2484 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2485 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002486}
2487
Vishnu Nairec0ab382019-02-13 15:32:56 -08002488void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002489 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002490 mPendingInputWindowCommands.clear();
2491}
2492
Riley Andrews03414a12014-07-01 14:22:59 -07002493void SurfaceFlinger::updateCursorAsync()
2494{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002495 compositionengine::CompositionRefreshArgs refreshArgs;
2496 for (const auto& [_, display] : mDisplays) {
2497 if (display->getId()) {
2498 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002499 }
2500 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002501
2502 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002503}
2504
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002505void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2506 if (mScheduler) {
2507 // In practice it's not allowed to hotplug in/out the primary display once it's been
2508 // connected during startup, but some tests do it, so just warn and return.
2509 ALOGW("Can't re-init scheduler");
2510 return;
2511 }
2512
2513 int currentConfig = getHwComposer().getActiveConfigIndex(primaryDisplayId);
2514 mRefreshRateConfigs =
2515 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2516 getHwComposer().getConfigs(
2517 primaryDisplayId),
2518 currentConfig);
2519 mRefreshRateStats =
2520 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2521 currentConfig, HWC_POWER_MODE_OFF);
2522 mRefreshRateStats->setConfigMode(currentConfig);
2523
2524 // start the EventThread
2525 mScheduler =
2526 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
2527 *mRefreshRateConfigs);
2528 mAppConnectionHandle =
2529 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
2530 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2531 impl::EventThread::InterceptVSyncsCallback());
2532 mSfConnectionHandle =
2533 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
2534 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2535 [this](nsecs_t timestamp) {
2536 mInterceptor->saveVSyncEvent(timestamp);
2537 });
2538
2539 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2540 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
2541 mPhaseOffsets->getCurrentOffsets());
2542
2543 mRegionSamplingThread =
2544 new RegionSamplingThread(*this, *mScheduler,
2545 RegionSamplingThread::EnvironmentTimingTunables());
2546
2547 mScheduler->setChangeRefreshRateCallback(
2548 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
2549 Mutex::Autolock lock(mStateLock);
2550 setRefreshRateTo(type, event);
2551 });
2552}
2553
Mathias Agopian4fec8732012-06-29 14:12:52 -07002554void SurfaceFlinger::commitTransaction()
2555{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002556 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002557
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002558 mTransactionPending = false;
2559 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002560 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002561}
2562
Lloyd Pique58e24a32019-08-01 15:50:14 -07002563void SurfaceFlinger::commitTransactionLocked() {
2564 if (!mLayersPendingRemoval.isEmpty()) {
2565 // Notify removed layers now that they can't be drawn from
2566 for (const auto& l : mLayersPendingRemoval) {
2567 recordBufferingStats(l->getName().string(), l->getOccupancyHistory(true));
2568
2569 // Ensure any buffers set to display on any children are released.
2570 if (l->isRemovedFromCurrentState()) {
2571 l->latchAndReleaseBuffer();
2572 }
2573
2574 // If the layer has been removed and has no parent, then it will not be reachable
2575 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2576 // ensure we can copy its current to drawing state.
2577 if (!l->getParent()) {
2578 mOffscreenLayers.emplace(l.get());
2579 }
2580 }
2581 mLayersPendingRemoval.clear();
2582 }
2583
2584 // If this transaction is part of a window animation then the next frame
2585 // we composite should be considered an animation as well.
2586 mAnimCompositionPending = mAnimTransactionPending;
2587
2588 mDrawingState = mCurrentState;
2589 // clear the "changed" flags in current state
2590 mCurrentState.colorMatrixChanged = false;
2591
2592 mDrawingState.traverseInZOrder([&](Layer* layer) {
2593 layer->commitChildList();
2594
2595 // If the layer can be reached when traversing mDrawingState, then the layer is no
2596 // longer offscreen. Remove the layer from the offscreenLayer set.
2597 if (mOffscreenLayers.count(layer)) {
2598 mOffscreenLayers.erase(layer);
2599 }
2600 });
2601
2602 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002603 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002604}
2605
Nataniel Borges2b796da2019-02-15 13:32:18 -08002606void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2607 if (mTracingEnabledChanged) {
2608 mTracingEnabled = mTracing.isEnabled();
2609 mTracingEnabledChanged = false;
2610 }
2611
2612 // Synchronize with Tracing thread
2613 std::unique_lock<std::mutex> lock;
2614 if (mTracingEnabled) {
2615 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2616 }
2617
2618 lockedOperation();
2619
2620 // Synchronize with Tracing thread
2621 if (mTracingEnabled) {
2622 lock.unlock();
2623 }
2624}
2625
chaviw74d90ad2019-04-26 14:45:26 -07002626void SurfaceFlinger::commitOffscreenLayers() {
2627 for (Layer* offscreenLayer : mOffscreenLayers) {
2628 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2629 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2630 if (!trFlags) return;
2631
2632 layer->doTransaction(0);
2633 layer->commitChildList();
2634 });
2635 }
2636}
2637
Chia-I Wuab0c3192017-08-01 11:29:00 -07002638void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002639 for (const auto& [token, displayDevice] : mDisplays) {
2640 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002641 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002642 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002643 }
2644 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002645}
2646
Dan Stoza6b9454d2014-11-07 16:00:59 -08002647bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002648{
Ady Abraham09bd3922019-04-08 10:44:56 -07002649 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002650 ALOGV("handlePageFlip");
2651
Brian Andersond6927fb2016-07-23 23:37:30 -07002652 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002653
Mathias Agopian4fec8732012-06-29 14:12:52 -07002654 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002655 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002656 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002657
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002658 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2659
Eric Penner51c59cd2014-07-28 19:51:58 -07002660 // Store the set of layers that need updates. This set must not change as
2661 // buffers are being latched, as this could result in a deadlock.
2662 // Example: Two producers share the same command stream and:
2663 // 1.) Layer 0 is latched
2664 // 2.) Layer 0 gets a new frame
2665 // 2.) Layer 1 gets a new frame
2666 // 3.) Layer 1 is latched.
2667 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2668 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002669 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002670 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002671 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002672 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002673 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002674 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002675 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002676 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002677 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002678 } else {
2679 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002680 }
Robert Carr2047fae2016-11-28 14:09:09 -08002681 });
2682
chaviw49a108c2019-08-12 11:23:06 -07002683 // The client can continue submitting buffers for offscreen layers, but they will not
2684 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2685 // layers to ensure dequeueBuffer doesn't block indefinitely.
2686 for (Layer* offscreenLayer : mOffscreenLayers) {
2687 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2688 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2689 }
2690
Lloyd Piquef2c79392018-12-20 16:23:33 -08002691 if (!mLayersWithQueuedFrames.empty()) {
2692 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2693 // writes to Layer current state. See also b/119481871
2694 Mutex::Autolock lock(mStateLock);
2695
2696 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002697 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002698 mLayersPendingRefresh.push_back(layer);
2699 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002700 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002701 if (layer->isBufferLatched()) {
2702 newDataLatched = true;
2703 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002704 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002705 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002706
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002707 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002708
2709 // If we will need to wake up at some time in the future to deal with a
2710 // queued frame that shouldn't be displayed during this vsync period, wake
2711 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002712 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002713 signalLayerUpdate();
2714 }
2715
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002716 // enter boot animation on first buffer latch
2717 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2718 ALOGI("Enter boot animation");
2719 mBootStage = BootStage::BOOTANIMATION;
2720 }
2721
chaviw74b03172019-08-19 11:09:03 -07002722 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2723
Dan Stoza6b9454d2014-11-07 16:00:59 -08002724 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002725 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002726}
2727
Mathias Agopianad456f92011-01-13 17:53:01 -08002728void SurfaceFlinger::invalidateHwcGeometry()
2729{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002730 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002731}
2732
Robert Carrc0df3122019-04-11 13:18:21 -07002733status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2734 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2735 const sp<IBinder>& parentHandle,
2736 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002737 // add this layer to the current state list
2738 {
2739 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002740 sp<Layer> parent;
2741 if (parentHandle != nullptr) {
2742 parent = fromHandle(parentHandle);
2743 if (parent == nullptr) {
2744 return NAME_NOT_FOUND;
2745 }
2746 } else {
2747 parent = parentLayer;
2748 }
2749
Robert Carr1f0a16a2016-10-24 16:27:39 -07002750 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002751 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002752 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002753 return NO_MEMORY;
2754 }
Robert Carrc0df3122019-04-11 13:18:21 -07002755
2756 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2757
Robert Carrb89ea9d2018-12-10 13:01:14 -08002758 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002759 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002760 } else if (parent == nullptr) {
2761 lbc->onRemovedFromCurrentState();
2762 } else if (parent->isRemovedFromCurrentState()) {
2763 parent->addChild(lbc);
2764 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002765 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002766 parent->addChild(lbc);
2767 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002768
Yiwei Zhang243b3782018-05-15 17:40:04 -07002769 if (gbc != nullptr) {
2770 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2771 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2772 mMaxGraphicBufferProducerListSize,
2773 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2774 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002775 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002776 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002777 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002778 }
2779
Mathias Agopian96f08192010-06-02 23:28:45 -07002780 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002781 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002782
Dan Stoza7d89d062015-04-30 13:29:25 -07002783 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002784}
2785
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002786uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002787 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002788}
2789
Mathias Agopian3f844832013-08-07 21:24:32 -07002790uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002791 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002792}
2793
Mathias Agopian3f844832013-08-07 21:24:32 -07002794uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002795 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002796}
2797
2798uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002799 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002800 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002801 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002803 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002804 }
2805 return old;
2806}
2807
Marissa Wall713b63f2018-10-17 15:42:43 -07002808bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002809 // to prevent onHandleDestroyed from being called while the lock is held,
2810 // we must keep a copy of the transactions (specifically the composer
2811 // states) around outside the scope of the lock
2812 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002813 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002814 {
2815 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002816
Valerie Haufce31b82019-04-30 16:41:14 -07002817 auto it = mTransactionQueues.begin();
2818 while (it != mTransactionQueues.end()) {
2819 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002820
Valerie Haufce31b82019-04-30 16:41:14 -07002821 while (!transactionQueue.empty()) {
2822 const auto& transaction = transactionQueue.front();
2823 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002824 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002825 transaction.states)) {
2826 setTransactionFlags(eTransactionFlushNeeded);
2827 break;
2828 }
2829 transactions.push_back(transaction);
2830 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2831 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002832 transaction.buffer, transaction.postTime,
2833 transaction.privileged, transaction.hasListenerCallbacks,
2834 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002835 transactionQueue.pop();
2836 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002837 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002838
Valerie Haufce31b82019-04-30 16:41:14 -07002839 if (transactionQueue.empty()) {
2840 it = mTransactionQueues.erase(it);
2841 mTransactionCV.broadcast();
2842 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002843 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002844 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002845 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002846 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002847 return flushedATransaction;
2848}
2849
2850bool SurfaceFlinger::transactionFlushNeeded() {
2851 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07002852}
2853
chaviwca27f252018-02-06 16:46:39 -08002854
Marissa Wall17b4e452018-12-26 16:32:34 -08002855bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002856 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08002857 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002858 if (!useCachedExpectedPresentTime)
2859 populateExpectedPresentTime();
2860
2861 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08002862 // Do not present if the desiredPresentTime has not passed unless it is more than one second
2863 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
2864 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
2865 desiredPresentTime < expectedPresentTime + s2ns(1)) {
2866 return false;
2867 }
2868
Marissa Wall713b63f2018-10-17 15:42:43 -07002869 for (const ComposerState& state : states) {
2870 const layer_state_t& s = state.state;
2871 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
2872 continue;
2873 }
2874 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08002875 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07002876 }
2877 }
Marissa Wall17b4e452018-12-26 16:32:34 -08002878 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002879}
2880
Valerie Hau9dab9732019-08-20 09:29:25 -07002881void SurfaceFlinger::setTransactionState(
2882 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2883 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
2884 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
2885 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002886 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08002887
Valerie Haubc6ddb12019-03-08 11:10:15 -08002888 const int64_t postTime = systemTime();
2889
Robert Carr14167e02019-02-13 13:50:55 -08002890 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
2891
Mathias Agopian698c0872011-06-28 19:09:31 -07002892 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07002893
Marissa Wall713b63f2018-10-17 15:42:43 -07002894 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07002895 auto itr = mTransactionQueues.find(applyToken);
2896 // if this is an animation frame, wait until prior animation frame has
2897 // been applied by SF
2898 if (flags & eAnimation) {
2899 while (itr != mTransactionQueues.end()) {
2900 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2901 if (CC_UNLIKELY(err != NO_ERROR)) {
2902 ALOGW_IF(err == TIMED_OUT,
2903 "setTransactionState timed out "
2904 "waiting for animation frame to apply");
2905 break;
2906 }
2907 itr = mTransactionQueues.find(applyToken);
2908 }
2909 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002910
2911 // Expected present time is computed and cached on invalidate, so it may be stale.
2912 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
2913 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08002914 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002915 uncacheBuffer, postTime, privileged,
2916 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002917 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002918 return;
2919 }
2920
Valerie Haubc6ddb12019-03-08 11:10:15 -08002921 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002922 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
2923 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07002924}
2925
Valerie Hau9dab9732019-08-20 09:29:25 -07002926void SurfaceFlinger::applyTransactionState(
2927 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2928 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
2929 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
2930 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
2931 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07002932 uint32_t transactionFlags = 0;
2933
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002934 if (flags & eAnimation) {
2935 // For window updates that are part of an animation we must wait for
2936 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07002937 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002938 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002939 if (CC_UNLIKELY(err != NO_ERROR)) {
2940 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002941 // caller after a few seconds.
2942 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2943 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002944 mAnimTransactionPending = false;
2945 break;
2946 }
2947 }
2948 }
2949
chaviwca27f252018-02-06 16:46:39 -08002950 for (const DisplayState& display : displays) {
2951 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002952 }
2953
Valerie Hau9dab9732019-08-20 09:29:25 -07002954 // start and end registration for listeners w/ no surface so they can get their callback. Note
2955 // that listeners with SurfaceControls will start registration during setClientStateLocked
2956 // below.
2957 for (const auto& listener : listenerCallbacks) {
2958 mTransactionCompletedThread.startRegistration(listener);
2959 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07002960 }
2961
Valerie Hau9dab9732019-08-20 09:29:25 -07002962 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07002963 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08002964 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07002965 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
2966 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07002967 }
2968
Valerie Hau9dab9732019-08-20 09:29:25 -07002969 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07002970 mTransactionCompletedThread.endRegistration(listenerCallback);
2971 }
2972
Marissa Walle2ffb422018-10-12 11:33:52 -07002973 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07002974 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07002975 mTransactionCompletedThread.sendCallbacks();
2976 }
2977 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08002978
chaviw273171b2018-12-26 11:46:30 -08002979 transactionFlags |= addInputWindowCommands(inputWindowCommands);
2980
Marissa Wall947d34e2019-03-29 14:03:53 -07002981 if (uncacheBuffer.isValid()) {
2982 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07002983 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07002984 }
2985
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002986 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2987 // anyway. This can be used as a flush mechanism for previous async transactions.
2988 // Empty animation transaction can be used to simulate back-pressure, so also force a
2989 // transaction for empty animation transactions.
2990 if (transactionFlags == 0 &&
2991 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07002992 transactionFlags = eTransactionNeeded;
2993 }
2994
Marissa Wall06255332019-03-27 13:48:27 -07002995 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
2996 // so we don't have to wake up again next frame to preform an uneeded traversal.
2997 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
2998 transactionFlags = transactionFlags & (~eTraversalNeeded);
2999 mTraversalNeededMainThread = true;
3000 }
3001
Mathias Agopian386aa982011-11-07 21:58:03 -08003002 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003003 if (mInterceptor->isEnabled()) {
3004 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003005 }
Irvel468051e2016-06-13 16:44:44 -07003006
Mathias Agopian386aa982011-11-07 21:58:03 -08003007 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003008 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3009 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003010 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003011
3012 // if this is a synchronous transaction, wait for it to take effect
3013 // before returning.
3014 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003015 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003016 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003017 if (flags & eAnimation) {
3018 mAnimTransactionPending = true;
3019 }
chaviw4fe36852019-04-15 16:25:49 -07003020 if (mPendingInputWindowCommands.syncInputWindows) {
3021 mPendingSyncInputWindows = true;
3022 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003023
3024 // applyTransactionState can be called by either the main SF thread or by
3025 // another process through setTransactionState. While a given process may wish
3026 // to wait on synchronous transactions, the main SF thread should never
3027 // be blocked. Therefore, we only wait if isMainThread is false.
3028 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003029 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3030 if (CC_UNLIKELY(err != NO_ERROR)) {
3031 // just in case something goes wrong in SF, return to the
3032 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003033 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3034 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003035 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003036 break;
3037 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003038 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003039 }
3040}
3041
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003042uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3043 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3044 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003045
Mathias Agopiane57f2922012-08-09 16:29:12 -07003046 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003047 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3048
3049 const uint32_t what = s.what;
3050 if (what & DisplayState::eSurfaceChanged) {
3051 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3052 state.surface = s.surface;
3053 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003054 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003055 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003056 if (what & DisplayState::eLayerStackChanged) {
3057 if (state.layerStack != s.layerStack) {
3058 state.layerStack = s.layerStack;
3059 flags |= eDisplayTransactionNeeded;
3060 }
3061 }
3062 if (what & DisplayState::eDisplayProjectionChanged) {
3063 if (state.orientation != s.orientation) {
3064 state.orientation = s.orientation;
3065 flags |= eDisplayTransactionNeeded;
3066 }
3067 if (state.frame != s.frame) {
3068 state.frame = s.frame;
3069 flags |= eDisplayTransactionNeeded;
3070 }
3071 if (state.viewport != s.viewport) {
3072 state.viewport = s.viewport;
3073 flags |= eDisplayTransactionNeeded;
3074 }
3075 }
3076 if (what & DisplayState::eDisplaySizeChanged) {
3077 if (state.width != s.width) {
3078 state.width = s.width;
3079 flags |= eDisplayTransactionNeeded;
3080 }
3081 if (state.height != s.height) {
3082 state.height = s.height;
3083 flags |= eDisplayTransactionNeeded;
3084 }
3085 }
3086
Mathias Agopiane57f2922012-08-09 16:29:12 -07003087 return flags;
3088}
3089
Robert Carr14167e02019-02-13 13:50:55 -08003090bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003091 IPCThreadState* ipc = IPCThreadState::self();
3092 const int pid = ipc->getCallingPid();
3093 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003094 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003095 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003096 return false;
3097 }
3098 return true;
3099}
3100
Marissa Wall3dad52d2019-03-22 14:03:19 -07003101uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003102 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3103 bool privileged,
3104 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003105 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003106
Valerie Hau9dab9732019-08-20 09:29:25 -07003107 for (auto& listener : s.listeners) {
3108 // note that startRegistration will not re-register if the listener has
3109 // already be registered for a prior surface control
3110 mTransactionCompletedThread.startRegistration(listener);
3111 listenerCallbacks.insert(listener);
3112 }
3113
Vishnu Nairf03652d2019-07-16 17:56:56 -07003114 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003115 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003116 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003117 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003118 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003119 }
chaviw8b3871a2017-11-01 17:41:01 -07003120 return 0;
3121 }
3122
chaviw8b3871a2017-11-01 17:41:01 -07003123 uint32_t flags = 0;
3124
Garfield Tan8a3083e2018-12-03 13:21:07 -08003125 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003126
3127 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3128 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003129 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003130 layer->pushPendingState();
3131 }
3132
chaviw8b3871a2017-11-01 17:41:01 -07003133 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003134 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003135 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003136 }
chaviw8b3871a2017-11-01 17:41:01 -07003137 }
3138 if (what & layer_state_t::eLayerChanged) {
3139 // NOTE: index needs to be calculated before we update the state
3140 const auto& p = layer->getParent();
3141 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003142 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003143 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003144 mCurrentState.layersSortedByZ.removeAt(idx);
3145 mCurrentState.layersSortedByZ.add(layer);
3146 // we need traversal (state changed)
3147 // AND transaction (list changed)
3148 flags |= eTransactionNeeded|eTraversalNeeded;
3149 }
chaviw8b3871a2017-11-01 17:41:01 -07003150 } else {
3151 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003152 flags |= eTransactionNeeded|eTraversalNeeded;
3153 }
3154 }
chaviw8b3871a2017-11-01 17:41:01 -07003155 }
3156 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003157 // NOTE: index needs to be calculated before we update the state
3158 const auto& p = layer->getParent();
3159 if (p == nullptr) {
3160 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3161 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3162 mCurrentState.layersSortedByZ.removeAt(idx);
3163 mCurrentState.layersSortedByZ.add(layer);
3164 // we need traversal (state changed)
3165 // AND transaction (list changed)
3166 flags |= eTransactionNeeded|eTraversalNeeded;
3167 }
3168 } else {
3169 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3170 flags |= eTransactionNeeded|eTraversalNeeded;
3171 }
chaviw8b3871a2017-11-01 17:41:01 -07003172 }
3173 }
3174 if (what & layer_state_t::eSizeChanged) {
3175 if (layer->setSize(s.w, s.h)) {
3176 flags |= eTraversalNeeded;
3177 }
3178 }
3179 if (what & layer_state_t::eAlphaChanged) {
3180 if (layer->setAlpha(s.alpha))
3181 flags |= eTraversalNeeded;
3182 }
3183 if (what & layer_state_t::eColorChanged) {
3184 if (layer->setColor(s.color))
3185 flags |= eTraversalNeeded;
3186 }
Peiyong Lind3788632018-09-18 16:01:31 -07003187 if (what & layer_state_t::eColorTransformChanged) {
3188 if (layer->setColorTransform(s.colorTransform)) {
3189 flags |= eTraversalNeeded;
3190 }
3191 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003192 if (what & layer_state_t::eBackgroundColorChanged) {
3193 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3194 flags |= eTraversalNeeded;
3195 }
3196 }
chaviw8b3871a2017-11-01 17:41:01 -07003197 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003198 // TODO: b/109894387
3199 //
3200 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3201 // rotation. To see the problem observe that if we have a square parent, and a child
3202 // of the same size, then we rotate the child 45 degrees around it's center, the child
3203 // must now be cropped to a non rectangular 8 sided region.
3204 //
3205 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3206 // private API, and the WindowManager only uses rotation in one case, which is on a top
3207 // level layer in which cropping is not an issue.
3208 //
3209 // However given that abuse of rotation matrices could lead to surfaces extending outside
3210 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3211 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3212 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003213 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003214 flags |= eTraversalNeeded;
3215 }
3216 if (what & layer_state_t::eTransparentRegionChanged) {
3217 if (layer->setTransparentRegionHint(s.transparentRegion))
3218 flags |= eTraversalNeeded;
3219 }
3220 if (what & layer_state_t::eFlagsChanged) {
3221 if (layer->setFlags(s.flags, s.mask))
3222 flags |= eTraversalNeeded;
3223 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003224 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003225 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003226 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003227 if (what & layer_state_t::eCornerRadiusChanged) {
3228 if (layer->setCornerRadius(s.cornerRadius))
3229 flags |= eTraversalNeeded;
3230 }
chaviw8b3871a2017-11-01 17:41:01 -07003231 if (what & layer_state_t::eLayerStackChanged) {
3232 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3233 // We only allow setting layer stacks for top level layers,
3234 // everything else inherits layer stack from its parent.
3235 if (layer->hasParent()) {
3236 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3237 layer->getName().string());
3238 } else if (idx < 0) {
3239 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3240 "that also does not appear in the top level layer list. Something"
3241 " has gone wrong.", layer->getName().string());
3242 } else if (layer->setLayerStack(s.layerStack)) {
3243 mCurrentState.layersSortedByZ.removeAt(idx);
3244 mCurrentState.layersSortedByZ.add(layer);
3245 // we need traversal (state changed)
3246 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003247 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003248 }
3249 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003250 if (what & layer_state_t::eDeferTransaction_legacy) {
3251 if (s.barrierHandle_legacy != nullptr) {
3252 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3253 } else if (s.barrierGbp_legacy != nullptr) {
3254 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003255 if (authenticateSurfaceTextureLocked(gbp)) {
3256 const auto& otherLayer =
3257 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003258 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003259 } else {
3260 ALOGE("Attempt to defer transaction to to an"
3261 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003262 }
3263 }
chaviw8b3871a2017-11-01 17:41:01 -07003264 // We don't trigger a traversal here because if no other state is
3265 // changed, we don't want this to cause any more work
3266 }
chaviw8b3871a2017-11-01 17:41:01 -07003267 if (what & layer_state_t::eReparentChildren) {
3268 if (layer->reparentChildren(s.reparentHandle)) {
3269 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003270 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003271 }
chaviw8b3871a2017-11-01 17:41:01 -07003272 if (what & layer_state_t::eDetachChildren) {
3273 layer->detachChildren();
3274 }
3275 if (what & layer_state_t::eOverrideScalingModeChanged) {
3276 layer->setOverrideScalingMode(s.overrideScalingMode);
3277 // We don't trigger a traversal here because if no other state is
3278 // changed, we don't want this to cause any more work
3279 }
Marissa Wall61c58622018-07-18 10:12:20 -07003280 if (what & layer_state_t::eTransformChanged) {
3281 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3282 }
3283 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3284 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3285 flags |= eTraversalNeeded;
3286 }
3287 if (what & layer_state_t::eCropChanged) {
3288 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3289 }
Marissa Wall861616d2018-10-22 12:52:23 -07003290 if (what & layer_state_t::eFrameChanged) {
3291 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3292 }
Marissa Wall61c58622018-07-18 10:12:20 -07003293 if (what & layer_state_t::eAcquireFenceChanged) {
3294 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3295 }
3296 if (what & layer_state_t::eDataspaceChanged) {
3297 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3298 }
3299 if (what & layer_state_t::eHdrMetadataChanged) {
3300 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3301 }
3302 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3303 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3304 }
3305 if (what & layer_state_t::eApiChanged) {
3306 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3307 }
3308 if (what & layer_state_t::eSidebandStreamChanged) {
3309 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3310 }
Robert Carr720e5062018-07-30 17:45:14 -07003311 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003312 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003313 layer->setInputInfo(s.inputInfo);
3314 flags |= eTraversalNeeded;
3315 } else {
3316 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3317 }
Robert Carr720e5062018-07-30 17:45:14 -07003318 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003319 if (what & layer_state_t::eMetadataChanged) {
3320 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3321 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003322 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3323 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3324 flags |= eTraversalNeeded;
3325 }
3326 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003327 // This has to happen after we reparent children because when we reparent to null we remove
3328 // child layers from current state and remove its relative z. If the children are reparented in
3329 // the same transaction, then we have to make sure we reparent the children first so we do not
3330 // lose its relative z order.
3331 if (what & layer_state_t::eReparent) {
3332 bool hadParent = layer->hasParent();
3333 if (layer->reparent(s.parentHandleForChild)) {
3334 if (!hadParent) {
3335 mCurrentState.layersSortedByZ.remove(layer);
3336 }
3337 flags |= eTransactionNeeded | eTraversalNeeded;
3338 }
3339 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003340 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003341 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3342 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003343 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3344 }
3345 }
Marissa Wall78b72202019-03-15 14:58:34 -07003346 bool bufferChanged = what & layer_state_t::eBufferChanged;
3347 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3348 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003349 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003350 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003351 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3352 if (success) {
3353 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3354 success = ClientCache::getInstance()
3355 .registerErasedRecipient(s.cachedBuffer,
3356 wp<ClientCache::ErasedRecipient>(this));
3357 if (!success) {
3358 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3359 }
3360 }
Marissa Wall78b72202019-03-15 14:58:34 -07003361 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003362 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003363 } else if (bufferChanged) {
3364 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003365 }
Marissa Wall78b72202019-03-15 14:58:34 -07003366 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003367 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003368 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003369 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003370 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003371 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3372 // Do not put anything that updates layer state or modifies flags after
3373 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003374 return flags;
3375}
3376
chaviw273171b2018-12-26 11:46:30 -08003377uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3378 uint32_t flags = 0;
3379 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3380 flags |= eTraversalNeeded;
3381 }
3382
chaviwa911b102019-02-14 10:18:33 -08003383 if (inputWindowCommands.syncInputWindows) {
3384 flags |= eTraversalNeeded;
3385 }
3386
Vishnu Nairec0ab382019-02-13 15:32:56 -08003387 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003388 return flags;
3389}
3390
Marissa Wall2d814fb2019-04-09 18:52:57 +00003391status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3392 uint32_t h, PixelFormat format, uint32_t flags,
3393 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003394 sp<IGraphicBufferProducer>* gbp,
3395 const sp<IBinder>& parentHandle,
3396 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003397 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003398 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003399 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003400 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003401 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003402
Robert Carrc0df3122019-04-11 13:18:21 -07003403 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3404 "Expected only one of parentLayer or parentHandle to be non-null. "
3405 "Programmer error?");
3406
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003407 status_t result = NO_ERROR;
3408
3409 sp<Layer> layer;
3410
Cody Northropbc755282017-03-31 12:00:08 -06003411 String8 uniqueName = getUniqueLayerName(name);
3412
Evan Roskya1f1e152019-01-24 16:17:46 -08003413 bool primaryDisplayOnly = false;
3414
3415 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3416 // TODO b/64227542
3417 if (metadata.has(METADATA_WINDOW_TYPE)) {
3418 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3419 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003420 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003421 primaryDisplayOnly = true;
3422 }
3423 }
3424
Mathias Agopian3165cc22012-08-08 19:42:09 -07003425 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003426 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08003427 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
3428 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003429
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003430 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003431 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08003432 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
3433 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003434 break;
chaviw13fdc492017-06-27 12:40:18 -07003435 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003436 // check if buffer size is set for color layer.
3437 if (w > 0 || h > 0) {
3438 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3439 int(w), int(h));
3440 return BAD_VALUE;
3441 }
3442
Evan Roskya1f1e152019-01-24 16:17:46 -08003443 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
3444 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003445 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003446 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003447 // check if buffer size is set for container layer.
3448 if (w > 0 || h > 0) {
3449 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3450 int(w), int(h));
3451 return BAD_VALUE;
3452 }
Evan Roskya1f1e152019-01-24 16:17:46 -08003453 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
3454 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003455 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003456 default:
3457 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003458 break;
3459 }
3460
Dan Stoza7d89d062015-04-30 13:29:25 -07003461 if (result != NO_ERROR) {
3462 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003463 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003464
Evan Roskya1f1e152019-01-24 16:17:46 -08003465 if (primaryDisplayOnly) {
3466 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003467 }
3468
Robert Carrb89ea9d2018-12-10 13:01:14 -08003469 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003470 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3471 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003472 if (result != NO_ERROR) {
3473 return result;
3474 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003475 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003476
3477 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003478 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003479}
3480
Cody Northropbc755282017-03-31 12:00:08 -06003481String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3482{
3483 bool matchFound = true;
3484 uint32_t dupeCounter = 0;
3485
3486 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3487 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3488
Dan Stoza436ccf32018-06-21 12:10:12 -07003489 // Grab the state lock since we're accessing mCurrentState
3490 Mutex::Autolock lock(mStateLock);
3491
Cody Northropbc755282017-03-31 12:00:08 -06003492 // Loop over layers until we're sure there is no matching name
3493 while (matchFound) {
3494 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003495 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003496 if (layer->getName() == uniqueName) {
3497 matchFound = true;
3498 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3499 }
3500 });
3501 }
3502
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003503 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3504 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003505
3506 return uniqueName;
3507}
3508
Marissa Wallfd668622018-05-10 10:21:13 -07003509status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3510 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003511 LayerMetadata metadata, PixelFormat& format,
3512 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003513 sp<IGraphicBufferProducer>* gbp,
3514 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003515 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003516 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003517 case PIXEL_FORMAT_TRANSPARENT:
3518 case PIXEL_FORMAT_TRANSLUCENT:
3519 format = PIXEL_FORMAT_RGBA_8888;
3520 break;
3521 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003522 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003523 break;
3524 }
3525
chaviwb4c6e582019-08-16 14:35:07 -07003526 sp<BufferQueueLayer> layer;
3527 LayerCreationArgs args =
3528 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata));
3529 args.textureName = getNewTexture();
3530 {
3531 // Grab the SF state lock during this since it's the only safe way to access
3532 // RenderEngine when creating a BufferLayerConsumer
3533 // TODO: Check if this lock is still needed here
3534 Mutex::Autolock lock(mStateLock);
3535 layer = getFactory().createBufferQueueLayer(args);
3536 }
3537
Marissa Wallfd668622018-05-10 10:21:13 -07003538 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003539 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003540 *handle = layer->getHandle();
3541 *gbp = layer->getProducer();
3542 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003543 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003544
Marissa Wallfd668622018-05-10 10:21:13 -07003545 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003546 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003547}
3548
Marissa Wall61c58622018-07-18 10:12:20 -07003549status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3550 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003551 LayerMetadata metadata, sp<IBinder>* handle,
3552 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07003553 LayerCreationArgs args =
3554 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata));
3555 args.displayDevice = getDefaultDisplayDevice();
3556 args.textureName = getNewTexture();
3557 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07003558 *handle = layer->getHandle();
3559 *outLayer = layer;
3560
3561 return NO_ERROR;
3562}
3563
Evan Roskya1f1e152019-01-24 16:17:46 -08003564status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
3565 uint32_t h, uint32_t flags, LayerMetadata metadata,
3566 sp<IBinder>* handle, sp<Layer>* outLayer) {
3567 *outLayer = getFactory().createColorLayer(
3568 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003569 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003570 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003571}
3572
Evan Roskya1f1e152019-01-24 16:17:46 -08003573status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
3574 uint32_t w, uint32_t h, uint32_t flags,
3575 LayerMetadata metadata, sp<IBinder>* handle,
3576 sp<Layer>* outLayer) {
3577 *outLayer = getFactory().createContainerLayer(
3578 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003579 *handle = (*outLayer)->getHandle();
3580 return NO_ERROR;
3581}
3582
3583
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003584void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003585 mLayersPendingRemoval.add(layer);
3586 mLayersRemoved = true;
3587 setTransactionFlags(eTransactionNeeded);
3588}
3589
Robert Carr695d5282018-12-18 15:27:58 -08003590void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003591{
Robert Carr2e102c92018-10-23 12:11:15 -07003592 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003593 // If a layer has a parent, we allow it to out-live it's handle
3594 // with the idea that the parent holds a reference and will eventually
3595 // be cleaned up. However no one cleans up the top-level so we do so
3596 // here.
3597 if (layer->getParent() == nullptr) {
3598 mCurrentState.layersSortedByZ.remove(layer);
3599 }
3600 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003601
3602 auto it = mLayersByLocalBinderToken.begin();
3603 while (it != mLayersByLocalBinderToken.end()) {
3604 if (it->second == layer) {
3605 it = mLayersByLocalBinderToken.erase(it);
3606 } else {
3607 it++;
3608 }
3609 }
3610
Robert Carr695d5282018-12-18 15:27:58 -08003611 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003612}
3613
Mathias Agopianb60314a2012-04-10 22:09:54 -07003614// ---------------------------------------------------------------------------
3615
Andy McFadden13a082e2012-08-24 10:16:42 -07003616void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003617 const auto display = getDefaultDisplayDeviceLocked();
3618 if (!display) return;
3619
3620 const sp<IBinder> token = display->getDisplayToken().promote();
3621 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003622
Jesse Hall01e29052013-02-19 16:13:35 -08003623 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003624 Vector<ComposerState> state;
3625 Vector<DisplayState> displays;
3626 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003627 d.what = DisplayState::eDisplayProjectionChanged |
3628 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003629 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003630 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003631 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003632 d.frame.makeInvalid();
3633 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003634 d.width = 0;
3635 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003636 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003637 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3638 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003639
Dominik Laskowskie9774092018-12-11 10:04:24 -08003640 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003641
Dominik Laskowski83b88212018-12-11 13:34:06 -08003642 const nsecs_t vsyncPeriod = getVsyncPeriod();
3643 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003644
Brian Andersond0010582017-03-07 13:20:31 -08003645 // Use phase of 0 since phase is not known.
3646 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003647 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003648 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003649}
3650
3651void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003652 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003653 postMessageAsync(
3654 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003655}
3656
Ady Abraham27c70212019-06-11 10:52:26 -07003657void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3658 if (mHWCVsyncState != enabled) {
3659 getHwComposer().setVsyncEnabled(displayId, enabled);
3660 mHWCVsyncState = enabled;
3661 }
3662}
3663
Dominik Laskowskie9774092018-12-11 10:04:24 -08003664void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003665 if (display->isVirtual()) {
3666 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003667 return;
3668 }
3669
Dominik Laskowski075d3172018-05-24 15:50:06 -07003670 const auto displayId = display->getId();
3671 LOG_ALWAYS_FATAL_IF(!displayId);
3672
Dominik Laskowski34157762018-10-31 13:07:19 -07003673 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003674
3675 int currentMode = display->getPowerMode();
3676 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003677 return;
3678 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003679
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003680 display->setPowerMode(mode);
3681
Lloyd Pique4dccc412018-01-22 17:21:36 -08003682 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003683 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003684 }
3685
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003686 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003687 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003688 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003689 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003690 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003691 mScheduler->onScreenAcquired(mAppConnectionHandle);
3692 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003693 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003694
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003695 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003696 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003697 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003698
3699 struct sched_param param = {0};
3700 param.sched_priority = 1;
3701 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3702 ALOGW("Couldn't set SCHED_FIFO on display on");
3703 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003704 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003705 // Turn off the display
3706 struct sched_param param = {0};
3707 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3708 ALOGW("Couldn't set SCHED_OTHER on display off");
3709 }
3710
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003711 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003712 mScheduler->disableHardwareVsync(true);
3713 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003714 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003715
Ady Abraham27c70212019-06-11 10:52:26 -07003716 // Make sure HWVsync is disabled before turning off the display
3717 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3718
Dominik Laskowski075d3172018-05-24 15:50:06 -07003719 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003720 mVisibleRegionsDirty = true;
3721 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003722 } else if (mode == HWC_POWER_MODE_DOZE ||
3723 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003724 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003725 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003726 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003727 mScheduler->onScreenAcquired(mAppConnectionHandle);
3728 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003729 }
3730 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3731 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003732 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003733 mScheduler->disableHardwareVsync(true);
3734 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003735 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003736 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003737 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003738 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003739 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003740 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003741
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003742 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003743 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003744 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003745 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003746 }
3747
Dominik Laskowski34157762018-10-31 13:07:19 -07003748 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003749}
3750
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003751void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003752 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003753 const auto display = getDisplayDevice(displayToken);
3754 if (!display) {
3755 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3756 displayToken.get());
3757 } else if (display->isVirtual()) {
3758 ALOGW("Attempt to set power mode %d for virtual display", mode);
3759 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003760 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003761 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003762 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003763}
3764
3765// ---------------------------------------------------------------------------
3766
Dominik Laskowskic2867142019-01-21 11:33:38 -08003767status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3768 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003769 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003770
Mathias Agopianbd115332013-04-18 16:41:04 -07003771 IPCThreadState* ipc = IPCThreadState::self();
3772 const int pid = ipc->getCallingPid();
3773 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003774
Mathias Agopianbd115332013-04-18 16:41:04 -07003775 if ((uid != AID_SHELL) &&
3776 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003777 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3778 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003779 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003780 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003781 // (this would indicate SF is stuck, but we want to be able to
3782 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003783 status_t err = mStateLock.timedLock(s2ns(1));
3784 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003785 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003786 StringAppendF(&result,
3787 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3788 "(no locks held)\n",
3789 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003790 }
3791
Dominik Laskowskic2867142019-01-21 11:33:38 -08003792 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07003793
Dominik Laskowskic2867142019-01-21 11:33:38 -08003794 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003795 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003796 {"--dispsync"s,
3797 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003798 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003799 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3800 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3801 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3802 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3803 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3804 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003805 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003806 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3807 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003808
Dominik Laskowskic2867142019-01-21 11:33:38 -08003809 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003810
Dominik Laskowski46470112019-08-02 13:13:11 -07003811 const auto it = dumpers.find(flag);
3812 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003813 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07003814 } else if (!asProto) {
3815 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003816 }
3817
Mathias Agopian9795c422009-08-26 16:36:26 -07003818 if (locked) {
3819 mStateLock.unlock();
3820 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003821
Dominik Laskowski46470112019-08-02 13:13:11 -07003822 if (it == dumpers.end()) {
3823 const LayersProto layersProto = dumpProtoFromMainThread();
3824 if (asProto) {
3825 result.append(layersProto.SerializeAsString());
3826 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07003827 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07003828 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3829 result.append(LayerProtoParser::layerTreeToString(layerTree));
3830 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07003831 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07003832 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003833 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003834 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08003835 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003836 return NO_ERROR;
3837}
3838
Nataniel Borges8e7dc722019-02-28 15:10:28 -08003839status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
3840 if (asProto && mTracing.isEnabled()) {
3841 mTracing.writeToFileAsync();
3842 }
3843
3844 return doDump(fd, DumpArgs(), asProto);
3845}
3846
Dominik Laskowskic2867142019-01-21 11:33:38 -08003847void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003848 mCurrentState.traverseInZOrder(
3849 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003850}
3851
Dominik Laskowskic2867142019-01-21 11:33:38 -08003852void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003853 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003854
Dominik Laskowskic2867142019-01-21 11:33:38 -08003855 if (args.size() > 1) {
3856 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08003857 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003858 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003859 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003860 }
Robert Carr2047fae2016-11-28 14:09:09 -08003861 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08003862 } else {
3863 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003864 }
3865}
3866
Dominik Laskowskic2867142019-01-21 11:33:38 -08003867void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08003868 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003869 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003870 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003871 }
Robert Carr2047fae2016-11-28 14:09:09 -08003872 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003873
Svetoslavd85084b2014-03-20 10:28:31 -07003874 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003875}
3876
Dominik Laskowskic2867142019-01-21 11:33:38 -08003877void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
3878 mTimeStats->parseArgs(asProto, args, result);
3879}
3880
Jamie Gennis6547ff42013-07-16 20:12:42 -07003881// This should only be called from the main thread. Otherwise it would need
3882// the lock and should use mCurrentState rather than mDrawingState.
3883void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003884 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003885 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003886 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003887
3888 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3889}
3890
Yiwei Zhang5434a782018-12-05 18:06:32 -08003891void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003892 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003893
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003894 if (isLayerTripleBufferingDisabled())
3895 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003896
Yiwei Zhang5434a782018-12-05 18:06:32 -08003897 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
3898 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
3899 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
3900 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
3901 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3902 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003903 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003904}
3905
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003906void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07003907 mScheduler->dump(result);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003908 StringAppendF(&result, "+ Refresh rate switching: %s\n",
3909 mRefreshRateConfigs->refreshRateSwitchingSupported() ? "on" : "off");
Dominik Laskowski98041832019-08-01 18:35:59 -07003910 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
3911
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003912 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07003913 result.append("\n");
3914
Ana Krulec757f63a2019-01-25 10:46:18 -08003915 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003916 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07003917 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08003918 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003919
Ady Abraham42b3beb2019-07-09 18:09:52 -07003920 StringAppendF(&result, "Allowed Display Configs: ");
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003921 for (int32_t configId : mAllowedDisplayConfigs) {
3922 StringAppendF(&result, "%" PRIu32 " Hz, ",
3923 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07003924 }
3925 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
3926 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07003927
Ana Krulecc2870422019-01-29 19:00:58 -08003928 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003929}
3930
Yiwei Zhang5434a782018-12-05 18:06:32 -08003931void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
3932 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003933 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3934 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003935 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003936 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003937 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003938 }
David Sodman4a36e932017-11-07 14:29:47 -08003939 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003940 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003941 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003942 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
3943 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003944}
3945
Dan Stozae77c7662016-05-13 11:37:28 -07003946void SurfaceFlinger::recordBufferingStats(const char* layerName,
3947 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003948 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3949 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003950 for (const auto& segment : history) {
3951 if (!segment.usedThirdBuffer) {
3952 stats.twoBufferTime += segment.totalTime;
3953 }
3954 if (segment.occupancyAverage < 1.0f) {
3955 stats.doubleBufferedTime += segment.totalTime;
3956 } else if (segment.occupancyAverage < 2.0f) {
3957 stats.tripleBufferedTime += segment.totalTime;
3958 }
3959 ++stats.numSegments;
3960 stats.totalTime += segment.totalTime;
3961 }
3962}
3963
Yiwei Zhang5434a782018-12-05 18:06:32 -08003964void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
3965 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07003966
3967 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3968 const size_t count = currentLayers.size();
3969 for (size_t i=0 ; i<count ; i++) {
3970 currentLayers[i]->dumpFrameEvents(result);
3971 }
3972}
3973
Yiwei Zhang5434a782018-12-05 18:06:32 -08003974void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07003975 result.append("Buffering stats:\n");
3976 result.append(" [Layer name] <Active time> <Two buffer> "
3977 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003978 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003979 typedef std::tuple<std::string, float, float, float> BufferTuple;
3980 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003981 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003982 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003983 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003984 if (stats.numSegments == 0) {
3985 continue;
3986 }
3987 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3988 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3989 stats.totalTime;
3990 float doubleBufferRatio = static_cast<float>(
3991 stats.doubleBufferedTime) / stats.totalTime;
3992 float tripleBufferRatio = static_cast<float>(
3993 stats.tripleBufferedTime) / stats.totalTime;
3994 sorted.insert({activeTime, {name, twoBufferRatio,
3995 doubleBufferRatio, tripleBufferRatio}});
3996 }
3997 for (const auto& sortedPair : sorted) {
3998 float activeTime = sortedPair.first;
3999 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004000 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4001 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004002 }
4003 result.append("\n");
4004}
4005
Yiwei Zhang5434a782018-12-05 18:06:32 -08004006void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004007 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004008 const auto displayId = display->getId();
4009 if (!displayId) {
4010 continue;
4011 }
4012 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004013 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004014 continue;
4015 }
4016
Yiwei Zhang5434a782018-12-05 18:06:32 -08004017 StringAppendF(&result,
4018 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4019 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004020 uint8_t port;
4021 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004022 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004023 result.append("no identification data\n");
4024 continue;
4025 }
4026
4027 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004028 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004029 continue;
4030 }
4031
4032 const auto edid = parseEdid(data);
4033 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004034 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004035 continue;
4036 }
4037
Yiwei Zhang5434a782018-12-05 18:06:32 -08004038 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004039 result.append(edid->displayName.data(), edid->displayName.length());
4040 result.append("\"\n");
4041 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004042}
4043
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004044void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4045 std::string& result) const {
4046 hwc2_display_t hwcDisplayId;
4047 uint8_t port;
4048 DisplayIdentificationData data;
4049
4050 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4051 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4052 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4053 }
4054}
4055
Yiwei Zhang5434a782018-12-05 18:06:32 -08004056void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004057 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004058 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4059 StringAppendF(&result, "DisplayColorSetting: %s\n",
4060 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004061
4062 // TODO: print out if wide-color mode is active or not
4063
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004064 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004065 const auto displayId = display->getId();
4066 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004067 continue;
4068 }
4069
Yiwei Zhang5434a782018-12-05 18:06:32 -08004070 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004071 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004072 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004073 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004074 }
4075
Lloyd Pique32cbe282018-10-19 13:09:22 -07004076 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004077 StringAppendF(&result, " Current color mode: %s (%d)\n",
4078 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004079 }
4080 result.append("\n");
4081}
4082
Vishnu Nair8406fd72019-07-30 11:29:31 -07004083LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004084 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004085 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004086 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004087 layer->writeToProtoDrawingState(layerProto, traceFlags);
4088 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004089 });
4090
4091 return layersProto;
4092}
4093
Vishnu Nair0f085c62019-08-30 08:49:12 -07004094void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4095 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4096 // it.
4097 LayerProto* rootProto = layersProto.add_layers();
4098 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4099 rootProto->set_id(offscreenRootLayerId);
4100 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004101 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004102
4103 for (Layer* offscreenLayer : mOffscreenLayers) {
4104 // Add layer as child of the fake root
4105 rootProto->add_children(offscreenLayer->sequence);
4106
4107 // Add layer
4108 LayerProto* layerProto = layersProto.add_layers();
4109 offscreenLayer->writeToProtoDrawingState(layerProto, traceFlags);
4110 offscreenLayer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing,
4111 traceFlags);
4112 layerProto->set_parent(offscreenRootLayerId);
4113
4114 // Add children
4115 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4116 if (layer == offscreenLayer) {
4117 return;
4118 }
4119 LayerProto* childProto = layersProto.add_layers();
4120 layer->writeToProtoDrawingState(childProto, traceFlags);
4121 layer->writeToProtoCommonState(childProto, LayerVector::StateSet::Drawing, traceFlags);
4122 });
4123 }
4124}
4125
Vishnu Nair8406fd72019-07-30 11:29:31 -07004126LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4127 LayersProto layersProto;
4128 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4129 return layersProto;
4130}
4131
Vishnu Nair0f085c62019-08-30 08:49:12 -07004132void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4133 result.append("Offscreen Layers:\n");
4134 postMessageSync(new LambdaMessage([&]() {
4135 for (Layer* offscreenLayer : mOffscreenLayers) {
4136 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4137 layer->dumpCallingUidPid(result);
4138 });
4139 }
4140 }));
4141}
4142
Dominik Laskowskic2867142019-01-21 11:33:38 -08004143void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4144 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004145 Colorizer colorizer(colorize);
4146
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004147 // figure out if we're stuck somewhere
4148 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004149 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004150 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4151
4152 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004153 * Dump library configuration.
4154 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004155
4156 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004157 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004158 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004159 appendSfConfigString(result);
4160 appendUiConfigString(result);
4161 appendGuiConfigString(result);
4162 result.append("\n");
4163
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004164 result.append("\nDisplay identification data:\n");
4165 dumpDisplayIdentificationData(result);
4166
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004167 result.append("\nWide-Color information:\n");
4168 dumpWideColorInfo(result);
4169
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004170 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004171 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004172 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004173 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004174 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004175
Andy McFadden41d67d72014-04-25 16:58:34 -07004176 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004177 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004178 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004179 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004180 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004181
Dan Stozab90cf072015-03-05 11:05:59 -08004182 dumpStaticScreenStats(result);
4183 result.append("\n");
4184
Alec Mouri40189b02019-03-05 15:07:54 -08004185 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4186 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4187 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004188
Dan Stozae77c7662016-05-13 11:37:28 -07004189 dumpBufferingStats(result);
4190
Andy McFadden4803b742012-09-24 19:07:20 -07004191 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004192 * Dump the visible layer list
4193 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004194 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004195 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004196 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4197 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004198 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004199
Chia-I Wu2f884132018-09-13 15:17:58 -07004200 {
Lloyd Pique207def92019-02-28 16:09:52 -08004201 StringAppendF(&result, "Composition layers\n");
4202 mDrawingState.traverseInZOrder([&](Layer* layer) {
4203 auto compositionLayer = layer->getCompositionLayer();
4204 if (compositionLayer) compositionLayer->dump(result);
4205 });
4206 }
4207
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004208 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004209 * Dump Display state
4210 */
4211
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004212 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004213 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004214 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004215 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004216 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004217 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004218 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004219
4220 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004221 * Dump CompositionEngine state
4222 */
4223
4224 mCompositionEngine->dump(result);
4225
4226 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004227 * Dump SurfaceFlinger global state
4228 */
4229
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004230 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004231 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004232 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004233
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004234 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004235
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004236 DebugEGLImageTracker::getInstance()->dump(result);
4237
Dominik Laskowski075d3172018-05-24 15:50:06 -07004238 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004239 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4240 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004241 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4242 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004243 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004244 StringAppendF(&result,
4245 " transaction-flags : %08x\n"
4246 " gpu_to_cpu_unsupported : %d\n",
4247 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004248
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004249 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004250 displayId && getHwComposer().isConnected(*displayId)) {
4251 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004252 StringAppendF(&result,
4253 " refresh-rate : %f fps\n"
4254 " x-dpi : %f\n"
4255 " y-dpi : %f\n",
4256 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4257 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004258 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004259
Yiwei Zhang5434a782018-12-05 18:06:32 -08004260 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004261
Dan Stozae22aec72016-08-01 13:20:59 -07004262 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004263 * Tracing state
4264 */
4265 mTracing.dump(result);
4266 result.append("\n");
4267
4268 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004269 * HWC layer minidump
4270 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004271 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004272 const auto displayId = display->getId();
4273 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004274 continue;
4275 }
4276
Yiwei Zhang5434a782018-12-05 18:06:32 -08004277 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004278 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004279 const sp<DisplayDevice> displayDevice = display;
4280 mCurrentState.traverseInZOrder(
4281 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004282 result.append("\n");
4283 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004284
4285 /*
4286 * Dump HWComposer state
4287 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004288 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004289 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004290 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004291 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004292 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004293 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004294
4295 /*
4296 * Dump gralloc state
4297 */
4298 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4299 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004300
4301 /*
4302 * Dump VrFlinger state if in use.
4303 */
4304 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4305 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004306 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004307 result.append("\n");
4308 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004309
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004310 result.append(mTimeStats->miniDump());
4311 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004312}
4313
Chia-I Wu28f320b2018-05-03 11:02:56 -07004314void SurfaceFlinger::updateColorMatrixLocked() {
4315 mat4 colorMatrix;
4316 if (mGlobalSaturationFactor != 1.0f) {
4317 // Rec.709 luma coefficients
4318 float3 luminance{0.213f, 0.715f, 0.072f};
4319 luminance *= 1.0f - mGlobalSaturationFactor;
4320 mat4 saturationMatrix = mat4(
4321 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4322 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4323 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4324 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4325 );
4326 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4327 } else {
4328 colorMatrix = mClientColorMatrix * mDaltonizer();
4329 }
4330
4331 if (mCurrentState.colorMatrix != colorMatrix) {
4332 mCurrentState.colorMatrix = colorMatrix;
4333 mCurrentState.colorMatrixChanged = true;
4334 setTransactionFlags(eTransactionNeeded);
4335 }
4336}
4337
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004338status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004339#pragma clang diagnostic push
4340#pragma clang diagnostic error "-Wswitch-enum"
4341 switch (static_cast<ISurfaceComposerTag>(code)) {
4342 // These methods should at minimum make sure that the client requested
4343 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004344 case BOOT_FINISHED:
4345 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004346 case CREATE_DISPLAY:
4347 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004348 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004349 case GET_ANIMATION_FRAME_STATS:
4350 case GET_HDR_CAPABILITIES:
4351 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004352 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004353 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004354 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004355 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004356 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004357 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004358 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004359 case GET_DISPLAYED_CONTENT_SAMPLE:
4360 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004361 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4362 IPCThreadState* ipc = IPCThreadState::self();
4363 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4364 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004365 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004366 }
Robert Carr1db73f62016-12-21 12:58:51 -08004367 return OK;
4368 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004369 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004370 IPCThreadState* ipc = IPCThreadState::self();
4371 const int pid = ipc->getCallingPid();
4372 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004373 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4374 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004375 return PERMISSION_DENIED;
4376 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004377 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004378 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004379 // Used by apps to hook Choreographer to SurfaceFlinger.
4380 case CREATE_DISPLAY_EVENT_CONNECTION:
4381 // The following calls are currently used by clients that do not
4382 // request necessary permissions. However, they do not expose any secret
4383 // information, so it is OK to pass them.
4384 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004385 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004386 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004387 case GET_PHYSICAL_DISPLAY_IDS:
4388 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004389 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004390 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004391 case GET_DISPLAY_CONFIGS:
4392 case GET_DISPLAY_STATS:
4393 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4394 // Calling setTransactionState is safe, because you need to have been
4395 // granted a reference to Client* and Handle* to do anything with it.
4396 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004397 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004398 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004399 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004400 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004401 case IS_WIDE_COLOR_DISPLAY:
4402 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4403 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004404 return OK;
4405 }
Chong Zhangda6c1592019-07-16 13:45:06 -07004406 case CAPTURE_LAYERS: {
4407 IPCThreadState* ipc = IPCThreadState::self();
4408 const int pid = ipc->getCallingPid();
4409 const int uid = ipc->getCallingUid();
4410 // allow media to capture layer for video thumbnails
4411 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
4412 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4413 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
4414 return PERMISSION_DENIED;
4415 }
4416 return OK;
4417 }
Dan Stoza84ab9372018-12-17 15:27:57 -08004418 case CAPTURE_SCREEN:
4419 case ADD_REGION_SAMPLING_LISTENER:
4420 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004421 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004422 IPCThreadState* ipc = IPCThreadState::self();
4423 const int pid = ipc->getCallingPid();
4424 const int uid = ipc->getCallingUid();
4425 if ((uid != AID_GRAPHICS) &&
4426 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4427 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4428 return PERMISSION_DENIED;
4429 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004430 return OK;
4431 }
4432 // The following codes are deprecated and should never be allowed to access SF.
4433 case CONNECT_DISPLAY_UNUSED:
4434 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4435 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4436 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004437 }
chaviw93df2ea2019-04-30 16:45:12 -07004438 case CAPTURE_SCREEN_BY_ID: {
4439 IPCThreadState* ipc = IPCThreadState::self();
4440 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004441 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004442 return OK;
4443 }
4444 return PERMISSION_DENIED;
4445 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004446 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004447
4448 // These codes are used for the IBinder protocol to either interrogate the recipient
4449 // side of the transaction for its canonical interface descriptor or to dump its state.
4450 // We let them pass by default.
4451 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4452 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4453 code == IBinder::SYSPROPS_TRANSACTION) {
4454 return OK;
4455 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004456 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004457 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004458 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004459 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4460 return OK;
4461 }
4462 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4463 return PERMISSION_DENIED;
4464#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004465}
4466
Ana Krulec13be8ad2018-08-21 02:43:56 +00004467status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4468 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004469 status_t credentialCheck = CheckTransactCodeCredentials(code);
4470 if (credentialCheck != OK) {
4471 return credentialCheck;
4472 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004473
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004474 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4475 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004476 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004477 IPCThreadState* ipc = IPCThreadState::self();
4478 const int uid = ipc->getCallingUid();
4479 if (CC_UNLIKELY(uid != AID_SYSTEM
4480 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004481 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004482 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004483 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004484 return PERMISSION_DENIED;
4485 }
4486 int n;
4487 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004488 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004489 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004490 return NO_ERROR;
4491 case 1002: // SHOW_UPDATES
4492 n = data.readInt32();
4493 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004494 invalidateHwcGeometry();
4495 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004496 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004497 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004498 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004499 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004500 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004501 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004502 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004503 setTransactionFlags(
4504 eTransactionNeeded|
4505 eDisplayTransactionNeeded|
4506 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004507 return NO_ERROR;
4508 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004509 case 1006:{ // send empty update
4510 signalRefresh();
4511 return NO_ERROR;
4512 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004513 case 1008: // toggle use of hw composer
4514 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004515 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004516 invalidateHwcGeometry();
4517 repaintEverything();
4518 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004519 case 1009: // toggle use of transform hint
4520 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004521 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004522 invalidateHwcGeometry();
4523 repaintEverything();
4524 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004525 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004526 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004527 reply->writeInt32(0);
4528 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004529 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004530 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004531 return NO_ERROR;
4532 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004533 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004534 if (!display) {
4535 return NAME_NOT_FOUND;
4536 }
4537
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004538 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004539 return NO_ERROR;
4540 }
4541 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004542 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004543 // daltonize
4544 n = data.readInt32();
4545 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004546 case 1:
4547 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4548 break;
4549 case 2:
4550 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4551 break;
4552 case 3:
4553 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4554 break;
4555 default:
4556 mDaltonizer.setType(ColorBlindnessType::None);
4557 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004558 }
4559 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004560 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004561 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004562 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004563 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004564
4565 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004566 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004567 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004568 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004569 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004570 // apply a color matrix
4571 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004572 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004573 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004574 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004575 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004576 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004577 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004578 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004579 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004580 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004581 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004582
4583 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4584 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004585 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004586 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4587 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4588 }
4589
Chia-I Wu28f320b2018-05-03 11:02:56 -07004590 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004591 return NO_ERROR;
4592 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004593 case 1016: { // Unused.
4594 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004595 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004596 case 1017: {
4597 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004598 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004599 return NO_ERROR;
4600 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004601 case 1018: { // Modify Choreographer's phase offset
4602 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004603 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004604 return NO_ERROR;
4605 }
4606 case 1019: { // Modify SurfaceFlinger's phase offset
4607 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004608 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004609 return NO_ERROR;
4610 }
Irvel468051e2016-06-13 16:44:44 -07004611 case 1020: { // Layer updates interceptor
4612 n = data.readInt32();
4613 if (n) {
4614 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004615 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004616 }
4617 else{
4618 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004619 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004620 }
4621 return NO_ERROR;
4622 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004623 case 1021: { // Disable HWC virtual displays
4624 n = data.readInt32();
4625 mUseHwcVirtualDisplays = !n;
4626 return NO_ERROR;
4627 }
Romain Guy0147a172017-06-01 13:53:56 -07004628 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004629 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004630 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004631
Chia-I Wu28f320b2018-05-03 11:02:56 -07004632 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004633 return NO_ERROR;
4634 }
Romain Guy54f154a2017-10-24 21:40:32 +01004635 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004636 int32_t colorMode;
4637
Chia-I Wu0d711262018-05-21 15:19:35 -07004638 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004639 if (data.readInt32(&colorMode) == NO_ERROR) {
4640 mForceColorMode = static_cast<ColorMode>(colorMode);
4641 }
Romain Guy54f154a2017-10-24 21:40:32 +01004642 invalidateHwcGeometry();
4643 repaintEverything();
4644 return NO_ERROR;
4645 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004646 // Deprecate, use 1030 to check whether the device is color managed.
4647 case 1024: {
4648 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004649 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004650 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004651 n = data.readInt32();
4652 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004653 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004654 Mutex::Autolock lock(mStateLock);
4655 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004656 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004657 reply->writeInt32(NO_ERROR);
4658 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004659 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004660 bool writeFile = false;
4661 {
4662 Mutex::Autolock lock(mStateLock);
4663 mTracingEnabledChanged = true;
4664 writeFile = mTracing.disable();
4665 }
4666
4667 if (writeFile) {
4668 reply->writeInt32(mTracing.writeToFile());
4669 } else {
4670 reply->writeInt32(NO_ERROR);
4671 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004672 }
4673 return NO_ERROR;
4674 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004675 case 1026: { // Get layer tracing status
4676 reply->writeBool(mTracing.isEnabled());
4677 return NO_ERROR;
4678 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004679 // Is a DisplayColorSetting supported?
4680 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004681 const auto display = getDefaultDisplayDevice();
4682 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004683 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004684 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004685
4686 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4687 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004688 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004689 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004690 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004691 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004692 reply->writeBool(true);
4693 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004694 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004695 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004696 break;
4697 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004698 reply->writeBool(
4699 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004700 break;
4701 }
4702 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004703 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004704 // Is VrFlinger active?
4705 case 1028: {
4706 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004707 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004708 return NO_ERROR;
4709 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004710 // Set buffer size for SF tracing (value in KB)
4711 case 1029: {
4712 n = data.readInt32();
4713 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4714 ALOGW("Invalid buffer size: %d KB", n);
4715 reply->writeInt32(BAD_VALUE);
4716 return BAD_VALUE;
4717 }
4718
4719 ALOGD("Updating trace buffer to %d KB", n);
4720 mTracing.setBufferSize(n * 1024);
4721 reply->writeInt32(NO_ERROR);
4722 return NO_ERROR;
4723 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004724 // Is device color managed?
4725 case 1030: {
4726 reply->writeBool(useColorManagement);
4727 return NO_ERROR;
4728 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004729 // Override default composition data space
4730 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4731 // && adb shell stop zygote && adb shell start zygote
4732 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4733 // adb shell stop zygote && adb shell start zygote
4734 case 1031: {
4735 Mutex::Autolock _l(mStateLock);
4736 n = data.readInt32();
4737 if (n) {
4738 n = data.readInt32();
4739 if (n) {
4740 Dataspace dataspace = static_cast<Dataspace>(n);
4741 if (!validateCompositionDataspace(dataspace)) {
4742 return BAD_VALUE;
4743 }
4744 mDefaultCompositionDataspace = dataspace;
4745 }
4746 n = data.readInt32();
4747 if (n) {
4748 Dataspace dataspace = static_cast<Dataspace>(n);
4749 if (!validateCompositionDataspace(dataspace)) {
4750 return BAD_VALUE;
4751 }
4752 mWideColorGamutCompositionDataspace = dataspace;
4753 }
4754 } else {
4755 // restore composition data space.
4756 mDefaultCompositionDataspace = defaultCompositionDataspace;
4757 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4758 }
4759 return NO_ERROR;
4760 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004761 // Set trace flags
4762 case 1033: {
4763 n = data.readUint32();
4764 ALOGD("Updating trace flags to 0x%x", n);
4765 mTracing.setTraceFlags(n);
4766 reply->writeInt32(NO_ERROR);
4767 return NO_ERROR;
4768 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004769 case 1034: {
4770 // TODO(b/129297325): expose this via developer menu option
4771 n = data.readInt32();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004772 if (n && !mRefreshRateOverlay &&
4773 mRefreshRateConfigs->refreshRateSwitchingSupported()) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07004774 RefreshRateType type;
4775 {
4776 std::lock_guard<std::mutex> lock(mActiveConfigLock);
4777 type = mDesiredActiveConfig.type;
4778 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004779 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07004780 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004781 } else if (!n) {
4782 mRefreshRateOverlay.reset();
4783 }
4784 return NO_ERROR;
4785 }
Ady Abraham34392f72019-04-10 11:29:27 -07004786 case 1035: {
4787 n = data.readInt32();
4788 mDebugDisplayConfigSetByBackdoor = false;
4789 if (n >= 0) {
4790 const auto displayToken = getInternalDisplayToken();
4791 status_t result = setAllowedDisplayConfigs(displayToken, {n});
4792 if (result != NO_ERROR) {
4793 return result;
4794 }
4795 mDebugDisplayConfigSetByBackdoor = true;
4796 }
4797 return NO_ERROR;
4798 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004799 }
4800 }
4801 return err;
4802}
4803
Steven Thomas6d8110b2017-08-31 18:24:21 -07004804void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004805 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004806 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004807}
4808
Ana Krulec7d1d6832018-12-27 11:10:09 -08004809void SurfaceFlinger::repaintEverythingForHWC() {
4810 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004811 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004812}
4813
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004814// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4815class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004816public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004817 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4818 ~WindowDisconnector() {
4819 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004820 }
4821
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004822private:
4823 ANativeWindow* mWindow;
4824 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004825};
4826
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004827status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07004828 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
4829 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004830 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07004831 uint32_t reqWidth, uint32_t reqHeight,
4832 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08004833 ISurfaceComposer::Rotation rotation,
4834 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004835 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004836
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004837 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004838
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07004839 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
4840
Chia-I Wu20261cb2018-08-23 12:55:44 -07004841 sp<DisplayDevice> display;
4842 {
4843 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004844
Chia-I Wu20261cb2018-08-23 12:55:44 -07004845 display = getDisplayDeviceLocked(displayToken);
4846 if (!display) return BAD_VALUE;
4847
Chia-I Wucb023152018-08-28 12:57:23 -07004848 // set the requested width/height to the logical display viewport size
4849 // by default
4850 if (reqWidth == 0 || reqHeight == 0) {
4851 reqWidth = uint32_t(display->getViewport().width());
4852 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07004853 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004854 }
4855
Peiyong Lin0e003c92018-09-17 11:09:51 -07004856 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08004857 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004858
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08004859 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4860 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07004861 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07004862 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004863}
4864
chaviw93df2ea2019-04-30 16:45:12 -07004865static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
4866 switch (colorMode) {
4867 case ColorMode::DISPLAY_P3:
4868 case ColorMode::BT2100_PQ:
4869 case ColorMode::BT2100_HLG:
4870 case ColorMode::DISPLAY_BT2020:
4871 return Dataspace::DISPLAY_P3;
4872 default:
4873 return Dataspace::V0_SRGB;
4874 }
4875}
4876
4877const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
4878 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
4879 if (displayToken) {
4880 return getDisplayDeviceLocked(displayToken);
4881 }
4882 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
4883 // may not have a displayId.
4884 for (const auto& [token, display] : mDisplays) {
4885 if (display->getLayerStack() == displayOrLayerStack) {
4886 return display;
4887 }
4888 }
4889 return nullptr;
4890}
4891
4892status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
4893 sp<GraphicBuffer>* outBuffer) {
4894 sp<DisplayDevice> display;
4895 uint32_t width;
4896 uint32_t height;
4897 ui::Transform::orientation_flags captureOrientation;
4898 {
4899 Mutex::Autolock _l(mStateLock);
4900 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
4901 if (!display) {
4902 return BAD_VALUE;
4903 }
4904
4905 width = uint32_t(display->getViewport().width());
4906 height = uint32_t(display->getViewport().height());
4907
4908 captureOrientation = fromSurfaceComposerRotation(
4909 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07004910 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
4911 captureOrientation = ui::Transform::orientation_flags::ROT_270;
4912 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
4913 captureOrientation = ui::Transform::orientation_flags::ROT_90;
4914 }
chaviw93df2ea2019-04-30 16:45:12 -07004915 *outDataspace =
4916 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
4917 }
4918
4919 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
4920 false /* captureSecureLayers */);
4921
4922 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4923 std::placeholders::_1);
4924 bool ignored = false;
4925 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
4926 false /* useIdentityTransform */,
4927 ignored /* outCapturedSecureLayers */);
4928}
4929
Robert Carr866455f2019-04-02 16:28:26 -07004930status_t SurfaceFlinger::captureLayers(
4931 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
4932 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
4933 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
4934 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004935 ATRACE_CALL();
4936
4937 class LayerRenderArea : public RenderArea {
4938 public:
Robert Carr578038f2018-03-09 12:25:24 -08004939 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004940 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
4941 bool childrenOnly)
4942 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08004943 mLayer(layer),
4944 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004945 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08004946 mFlinger(flinger),
4947 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004948 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004949 Rect getBounds() const override {
4950 const Layer::State& layerState(mLayer->getDrawingState());
4951 return mLayer->getBufferSize(layerState);
4952 }
Marissa Wall61c58622018-07-18 10:12:20 -07004953 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004954 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07004955 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08004956 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004957 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08004958 }
chaviwa76b2712017-09-20 12:02:26 -07004959 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004960 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004961 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004962 Rect getSourceCrop() const override {
4963 if (mCrop.isEmpty()) {
4964 return getBounds();
4965 } else {
4966 return mCrop;
4967 }
4968 }
Robert Carr578038f2018-03-09 12:25:24 -08004969 class ReparentForDrawing {
4970 public:
4971 const sp<Layer>& oldParent;
4972 const sp<Layer>& newParent;
4973
Vishnu Nair4351ad52019-02-11 14:13:02 -08004974 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
4975 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08004976 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08004977 // Compute and cache the bounds for the new parent layer.
4978 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07004979 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004980 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08004981 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004982 };
4983
4984 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004985 const Rect sourceCrop = getSourceCrop();
4986 // no need to check rotation because there is none
4987 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
4988 sourceCrop.height() != getReqHeight();
4989
Robert Carr578038f2018-03-09 12:25:24 -08004990 if (!mChildrenOnly) {
4991 mTransform = mLayer->getTransform().inverse();
4992 drawLayers();
4993 } else {
4994 Rect bounds = getBounds();
chaviw32811fd2019-08-12 13:16:09 -07004995 // In the "childrenOnly" case we reparent the children to a screenshot
4996 // layer which has no properties set and which does not draw.
4997 sp<ContainerLayer> screenshotParentLayer =
4998 mFlinger->getFactory().createContainerLayer(
4999 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5000 bounds.getWidth(), bounds.getHeight(), 0,
5001 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005002
Vishnu Nair4351ad52019-02-11 14:13:02 -08005003 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005004 drawLayers();
5005 }
5006 }
chaviwa76b2712017-09-20 12:02:26 -07005007
chaviwa76b2712017-09-20 12:02:26 -07005008 private:
chaviw7206d492017-11-10 16:16:12 -08005009 const sp<Layer> mLayer;
5010 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005011
Peiyong Linefefaac2018-08-17 12:27:51 -07005012 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005013 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005014
5015 SurfaceFlinger* mFlinger;
5016 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005017 };
5018
Robert Carrc0df3122019-04-11 13:18:21 -07005019 int reqWidth = 0;
5020 int reqHeight = 0;
5021 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005022 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005023 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005024
Robert Carrc0df3122019-04-11 13:18:21 -07005025 {
5026 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005027
Robert Carrc0df3122019-04-11 13:18:21 -07005028 parent = fromHandle(layerHandleBinder);
5029 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5030 ALOGE("captureLayers called with an invalid or removed parent");
5031 return NAME_NOT_FOUND;
5032 }
5033
5034 const int uid = IPCThreadState::self()->getCallingUid();
5035 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5036 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5037 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5038 return PERMISSION_DENIED;
5039 }
5040
5041 if (sourceCrop.width() <= 0) {
5042 crop.left = 0;
5043 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5044 }
5045
5046 if (sourceCrop.height() <= 0) {
5047 crop.top = 0;
5048 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5049 }
5050 reqWidth = crop.width() * frameScale;
5051 reqHeight = crop.height() * frameScale;
5052
5053 for (const auto& handle : excludeHandles) {
5054 sp<Layer> excludeLayer = fromHandle(handle);
5055 if (excludeLayer != nullptr) {
5056 excludeLayers.emplace(excludeLayer);
5057 } else {
5058 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5059 return NAME_NOT_FOUND;
5060 }
5061 }
5062 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005063
Chia-I Wu20261cb2018-08-23 12:55:44 -07005064 // really small crop or frameScale
5065 if (reqWidth <= 0) {
5066 reqWidth = 1;
5067 }
5068 if (reqHeight <= 0) {
5069 reqHeight = 1;
5070 }
5071
Robert Carr866455f2019-04-02 16:28:26 -07005072 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5073 auto traverseLayers = [parent, childrenOnly,
5074 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005075 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5076 if (!layer->isVisible()) {
5077 return;
Robert Carr578038f2018-03-09 12:25:24 -08005078 } else if (childrenOnly && layer == parent.get()) {
5079 return;
chaviwa76b2712017-09-20 12:02:26 -07005080 }
Robert Carr866455f2019-04-02 16:28:26 -07005081
5082 sp<Layer> p = layer;
5083 while (p != nullptr) {
5084 if (excludeLayers.count(p) != 0) {
5085 return;
5086 }
5087 p = p->getParent();
5088 }
5089
chaviwa76b2712017-09-20 12:02:26 -07005090 visitor(layer);
5091 });
5092 };
Robert Carr108b2c72019-04-02 16:32:58 -07005093
5094 bool outCapturedSecureLayers = false;
5095 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5096 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005097}
5098
5099status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5100 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005101 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005102 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005103 bool useIdentityTransform,
5104 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005105 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005106
Peiyong Lin0e003c92018-09-17 11:09:51 -07005107 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005108 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5109 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005110 *outBuffer =
5111 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5112 static_cast<android_pixel_format>(reqPixelFormat), 1,
5113 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005114
Robert Carr108b2c72019-04-02 16:32:58 -07005115 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5116 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005117}
5118
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005119status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5120 TraverseLayersFunction traverseLayers,
5121 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005122 bool useIdentityTransform,
5123 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005124 // This mutex protects syncFd and captureResult for communication of the return values from the
5125 // main thread back to this Binder thread
5126 std::mutex captureMutex;
5127 std::condition_variable captureCondition;
5128 std::unique_lock<std::mutex> captureLock(captureMutex);
5129 int syncFd = -1;
5130 std::optional<status_t> captureResult;
5131
Robert Carr03480e22018-01-04 16:02:06 -08005132 const int uid = IPCThreadState::self()->getCallingUid();
5133 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5134
Dominik Laskowski8c001672018-05-30 16:52:06 -07005135 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005136 // If there is a refresh pending, bug out early and tell the binder thread to try again
5137 // after the refresh.
5138 if (mRefreshPending) {
5139 ATRACE_NAME("Skipping screenshot for now");
5140 std::unique_lock<std::mutex> captureLock(captureMutex);
5141 captureResult = std::make_optional<status_t>(EAGAIN);
5142 captureCondition.notify_one();
5143 return;
5144 }
5145
5146 status_t result = NO_ERROR;
5147 int fd = -1;
5148 {
5149 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005150 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005151 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005152 useIdentityTransform, forSystem, &fd,
5153 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005154 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005155 }
5156
5157 {
5158 std::unique_lock<std::mutex> captureLock(captureMutex);
5159 syncFd = fd;
5160 captureResult = std::make_optional<status_t>(result);
5161 captureCondition.notify_one();
5162 }
5163 });
5164
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005165 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005166 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005167 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005168 while (*captureResult == EAGAIN) {
5169 captureResult.reset();
5170 result = postMessageAsync(message);
5171 if (result != NO_ERROR) {
5172 return result;
5173 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005174 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005175 }
5176 result = *captureResult;
5177 }
5178
5179 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005180 sync_wait(syncFd, -1);
5181 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005182 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005183
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005184 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005185}
5186
chaviwa76b2712017-09-20 12:02:26 -07005187void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005188 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005189 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5190 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005191 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005192
chaviwa76b2712017-09-20 12:02:26 -07005193 const auto reqWidth = renderArea.getReqWidth();
5194 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005195 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005196 const auto transform = renderArea.getTransform();
5197 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005198
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005199 renderengine::DisplaySettings clientCompositionDisplay;
5200 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005201
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005202 // assume that bounds are never offset, and that they are the same as the
5203 // buffer bounds.
5204 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005205 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005206 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005207
5208 // Now take into account the rotation flag. We append a transform that
5209 // rotates the layer stack about the origin, then translate by buffer
5210 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005211 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005212 int displacementX = 0;
5213 int displacementY = 0;
5214 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5215 switch (rotation) {
5216 case ui::Transform::ROT_90:
5217 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005218 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005219 break;
5220 case ui::Transform::ROT_180:
5221 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005222 displacementY = renderArea.getBounds().getWidth();
5223 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005224 break;
5225 case ui::Transform::ROT_270:
5226 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005227 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005228 break;
5229 default:
5230 break;
5231 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005232
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005233 // We need to transform the clipping window into the right spot.
5234 // First, rotate the clipping rectangle by the rotation hint to get the
5235 // right orientation
5236 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5237 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5238 const vec4 rotClipTL = rotMatrix * clipTL;
5239 const vec4 rotClipBR = rotMatrix * clipBR;
5240 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5241 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5242 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5243 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5244
5245 // Now reposition the clipping rectangle with the displacement vector
5246 // computed above.
5247 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005248 clientCompositionDisplay.clip =
5249 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5250 newClipRight + displacementX, newClipBottom + displacementY);
5251
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005252 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005253 clientCompositionDisplay.globalTransform =
5254 clipTransform * clientCompositionDisplay.globalTransform;
5255
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005256 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5257 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005258
chaviw50da5042018-04-09 13:49:37 -07005259 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005260
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005261 renderengine::LayerSettings fillLayer;
5262 fillLayer.source.buffer.buffer = nullptr;
5263 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5264 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5265 fillLayer.alpha = half(alpha);
5266 clientCompositionLayers.push_back(fillLayer);
5267
5268 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005269 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005270 const bool supportProtectedContent = false;
5271 Region clip(renderArea.getBounds());
5272 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5273 clip,
5274 useIdentityTransform,
5275 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5276 renderArea.isSecure(),
5277 supportProtectedContent,
5278 clearRegion,
5279 };
5280 auto result = layer->prepareClientComposition(targetSettings);
5281 if (result) {
5282 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005283 }
chaviwa76b2712017-09-20 12:02:26 -07005284 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005285
5286 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005287 // Use an empty fence for the buffer fence, since we just created the buffer so
5288 // there is no need for synchronization with the GPU.
5289 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005290 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005291 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005292 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005293 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005294
5295 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005296}
5297
chaviwa76b2712017-09-20 12:02:26 -07005298status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5299 TraverseLayersFunction traverseLayers,
5300 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005301 bool useIdentityTransform, bool forSystem,
5302 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005303 ATRACE_CALL();
5304
chaviwa76b2712017-09-20 12:02:26 -07005305 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005306 outCapturedSecureLayers =
5307 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005308 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005309
Robert Carr03480e22018-01-04 16:02:06 -08005310 // We allow the system server to take screenshots of secure layers for
5311 // use in situations like the Screen-rotation animation and place
5312 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005313 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005314 ALOGW("FB is protected: PERMISSION_DENIED");
5315 return PERMISSION_DENIED;
5316 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005317 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005318 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005319}
5320
chaviw95ef3c42019-02-14 10:55:09 -08005321void SurfaceFlinger::setInputWindowsFinished() {
5322 Mutex::Autolock _l(mStateLock);
5323
5324 mPendingSyncInputWindows = false;
5325 mTransactionCV.broadcast();
5326}
chaviw5f21a5e2019-02-14 10:00:34 -08005327
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005328// ---------------------------------------------------------------------------
5329
Dan Stoza412903f2017-04-27 13:42:17 -07005330void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5331 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005332}
5333
Dan Stoza412903f2017-04-27 13:42:17 -07005334void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5335 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005336}
5337
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005338void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005339 const LayerVector::Visitor& visitor) {
5340 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005341 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005342 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005343 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005344 continue;
5345 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005346 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005347 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005348 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005349 return;
5350 }
chaviwa76b2712017-09-20 12:02:26 -07005351 if (!layer->isVisible()) {
5352 return;
5353 }
5354 visitor(layer);
5355 });
5356 }
5357}
5358
Dominik Laskowski22488f62019-03-28 09:53:04 -07005359void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5360 const std::vector<int32_t>& allowedConfigs) {
5361 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08005362 return;
5363 }
5364
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005365 const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
5366 allowedConfigs.end());
5367 if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
5368 return;
5369 }
5370
Ady Abraham838de062019-02-04 10:24:03 -08005371 ALOGV("Updating allowed configs");
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005372 mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
5373
5374 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5375 // that listeners that care about a change in allowed configs can get the notification.
5376 // Giving current ActiveConfig so that most other listeners would just drop the event
5377 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5378 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08005379
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005380 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5381 const auto& type = mScheduler->getPreferredRefreshRateType();
5382 const auto& config = mRefreshRateConfigs->getRefreshRateFromType(type);
5383 if (isDisplayConfigAllowed(config.configId)) {
5384 ALOGV("switching to Scheduler preferred config %d", config.configId);
5385 setDesiredActiveConfig({type, config.configId, Scheduler::ConfigEvent::Changed});
5386 } else {
5387 // Set the highest allowed config by iterating backwards on available refresh rates
5388 const auto& refreshRates = mRefreshRateConfigs->getRefreshRateMap();
5389 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
5390 if (isDisplayConfigAllowed(iter->second.configId)) {
5391 ALOGV("switching to allowed config %d", iter->second.configId);
5392 setDesiredActiveConfig(
5393 {iter->first, iter->second.configId, Scheduler::ConfigEvent::Changed});
5394 break;
5395 }
5396 }
5397 }
5398 } else if (!allowedConfigs.empty()) {
5399 ALOGV("switching to config %d", allowedConfigs[0]);
5400 setDesiredActiveConfig(
5401 {RefreshRateType::DEFAULT, allowedConfigs[0], Scheduler::ConfigEvent::Changed});
5402 }
Ady Abraham838de062019-02-04 10:24:03 -08005403}
5404
Dominik Laskowski22488f62019-03-28 09:53:04 -07005405status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005406 const std::vector<int32_t>& allowedConfigs) {
5407 ATRACE_CALL();
5408
Dominik Laskowski22488f62019-03-28 09:53:04 -07005409 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005410 return BAD_VALUE;
5411 }
5412
Ady Abraham34392f72019-04-10 11:29:27 -07005413 if (mDebugDisplayConfigSetByBackdoor) {
5414 // ignore this request as config is overridden by backdoor
5415 return NO_ERROR;
5416 }
5417
Ady Abraham838de062019-02-04 10:24:03 -08005418 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005419 const auto display = getDisplayDeviceLocked(displayToken);
5420 if (!display) {
5421 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5422 displayToken.get());
5423 } else if (display->isVirtual()) {
5424 ALOGW("Attempt to set allowed display configs for virtual display");
5425 } else {
5426 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5427 }
Ady Abraham838de062019-02-04 10:24:03 -08005428 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005429
Ady Abraham838de062019-02-04 10:24:03 -08005430 return NO_ERROR;
5431}
5432
Dominik Laskowski22488f62019-03-28 09:53:04 -07005433status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005434 std::vector<int32_t>* outAllowedConfigs) {
5435 ATRACE_CALL();
5436
Dominik Laskowski22488f62019-03-28 09:53:04 -07005437 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005438 return BAD_VALUE;
5439 }
5440
Dominik Laskowski22488f62019-03-28 09:53:04 -07005441 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005442
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005443 const auto display = getDisplayDeviceLocked(displayToken);
5444 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005445 return NAME_NOT_FOUND;
5446 }
5447
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005448 if (display->isPrimary()) {
5449 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
5450 }
5451
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005452 return NO_ERROR;
5453}
5454
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005455void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005456 mFlinger->setInputWindowsFinished();
5457}
5458
Robert Carrc0df3122019-04-11 13:18:21 -07005459sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5460 BBinder *b = handle->localBinder();
5461 if (b == nullptr) {
5462 return nullptr;
5463 }
5464 auto it = mLayersByLocalBinderToken.find(b);
5465 if (it != mLayersByLocalBinderToken.end()) {
5466 return it->second.promote();
5467 }
5468 return nullptr;
5469}
5470
Alec Mouri4545a8a2019-08-08 20:05:32 -07005471void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5472 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5473}
5474
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005475} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005476
Mathias Agopian3f844832013-08-07 21:24:32 -07005477#if defined(__gl_h_)
5478#error "don't include gl/gl.h in this file"
5479#endif
5480
5481#if defined(__gl2_h_)
5482#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005483#endif