blob: 54e20659a72550ab21e3620ac7f6bb0582e9d910 [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()),
Valerie Haud251afb2019-03-29 14:19:02 -0700261 mPhaseOffsets(mFactory.createPhaseOffsets()),
262 mPendingSyncInputWindows(false) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800263
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700264SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800265 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800266
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900267 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800268
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900269 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700270
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900271 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700272
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900273 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800274
Steven Thomas050b2c82017-03-06 11:45:16 -0800275 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900276 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800277
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800279
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 mDefaultCompositionDataspace =
285 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700286 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
287 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900288 defaultCompositionDataspace = mDefaultCompositionDataspace;
289 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
290 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
291 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
292 wideColorGamutCompositionPixelFormat =
293 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700294
Yichi Chenda901bf2019-06-28 14:58:27 +0800295 mColorSpaceAgnosticDataspace =
296 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
297
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900298 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
301 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
302 switch (tmpPrimaryDisplayOrientation) {
303 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700304 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800305 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900306 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700307 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800308 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900309 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700310 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800311 break;
312 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700313 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800314 break;
315 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700316 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800317
Sundong Ahn85131bd2019-02-18 15:51:53 +0900318 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800319
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800320 // debugging stuff...
321 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700322
Mathias Agopianb4b17302013-03-20 18:36:41 -0700323 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700324 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700325
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800326 property_get("debug.sf.showupdates", value, "0");
327 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700328
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700329 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000330
331 // DDMS debugging deprecated (b/120782499)
332 property_get("debug.sf.ddms", value, "0");
333 int debugDdms = atoi(value);
334 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700335
336 property_get("debug.sf.disable_backpressure", value, "0");
337 mPropagateBackpressure = !atoi(value);
338 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700339
Ady Abrahamadb9a992019-09-19 21:21:55 +0000340 property_get("debug.sf.enable_gl_backpressure", value, "0");
341 mPropagateBackpressureClientComposition = atoi(value);
342 ALOGI_IF(mPropagateBackpressureClientComposition,
343 "Enabling backpressure propagation for Client Composition");
344
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800345 property_get("debug.sf.enable_hwc_vds", value, "0");
346 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800347 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800348
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800349 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800350 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800351 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700352
Yiwei Zhang243b3782018-05-15 17:40:04 -0700353 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700354 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
355 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
356
Ana Krulece5a06e02019-03-06 17:09:03 -0800357 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800358 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800359
360 int int_value = atoi(value);
361 if (int_value) {
362 mUseSmart90ForVideo = true;
363 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800364
Dan Stozaec460082018-12-17 15:35:09 -0800365 property_get("debug.sf.luma_sampling", value, "1");
366 mLumaSampling = atoi(value);
367
Romain Guy11d63f42017-07-20 12:47:14 -0700368 // We should be reading 'persist.sys.sf.color_saturation' here
369 // but since /data may be encrypted, we need to wait until after vold
370 // comes online to attempt to read the property. The property is
371 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800372
373 if (useTrebleTestingOverride()) {
374 // Without the override SurfaceFlinger cannot connect to HIDL
375 // services that are not listed in the manifests. Considered
376 // deriving the setting from the set service name, but it
377 // would be brittle if the name that's not 'default' is used
378 // for production purposes later on.
379 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
380 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381}
382
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800383void SurfaceFlinger::onFirstRef()
384{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800385 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800386}
387
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700388SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800389
Dan Stozac7014012014-02-14 15:03:43 -0800390void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800391{
392 // the window manager died on us. prepare its eulogy.
393
Andy McFadden13a082e2012-08-24 10:16:42 -0700394 // restore initial conditions (default device unblank, etc)
395 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800396
397 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700398 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800399}
400
Robert Carr1db73f62016-12-21 12:58:51 -0800401static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700402 status_t err = client->initCheck();
403 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800404 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800405 }
Robert Carr1db73f62016-12-21 12:58:51 -0800406 return nullptr;
407}
408
409sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
410 return initClient(new Client(this));
411}
412
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700413sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
414 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700415{
416 class DisplayToken : public BBinder {
417 sp<SurfaceFlinger> flinger;
418 virtual ~DisplayToken() {
419 // no more references, this display must be terminated
420 Mutex::Autolock _l(flinger->mStateLock);
421 flinger->mCurrentState.displays.removeItem(this);
422 flinger->setTransactionFlags(eDisplayTransactionNeeded);
423 }
424 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700425 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700426 : flinger(flinger) {
427 }
428 };
429
430 sp<BBinder> token = new DisplayToken(this);
431
432 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700433 // Display ID is assigned when virtual display is allocated by HWC.
434 DisplayDeviceState state;
435 state.isSecure = secure;
436 state.displayName = displayName;
437 mCurrentState.displays.add(token, state);
438 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700439 return token;
440}
441
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700442void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700443 Mutex::Autolock _l(mStateLock);
444
Dominik Laskowski075d3172018-05-24 15:50:06 -0700445 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
446 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700447 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700448 return;
449 }
450
Dominik Laskowski075d3172018-05-24 15:50:06 -0700451 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
452 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700453 ALOGE("destroyDisplay called for non-virtual display");
454 return;
455 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700456 mInterceptor->saveDisplayDeletion(state.sequenceId);
457 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700458 setTransactionFlags(eDisplayTransactionNeeded);
459}
460
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800461std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
462 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700463
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800464 const auto internalDisplayId = getInternalDisplayIdLocked();
465 if (!internalDisplayId) {
466 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700467 }
468
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800469 std::vector<PhysicalDisplayId> displayIds;
470 displayIds.reserve(mPhysicalDisplayTokens.size());
471 displayIds.push_back(internalDisplayId->value);
472
473 for (const auto& [id, token] : mPhysicalDisplayTokens) {
474 if (id != *internalDisplayId) {
475 displayIds.push_back(id.value);
476 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700477 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700478
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800479 return displayIds;
480}
481
482sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
483 Mutex::Autolock lock(mStateLock);
484 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700485}
486
Ady Abraham37965d42018-11-01 13:43:32 -0700487status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
488 if (!outGetColorManagement) {
489 return BAD_VALUE;
490 }
491 *outGetColorManagement = useColorManagement;
492 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700493}
494
Lloyd Pique441d5042018-10-18 16:49:51 -0700495HWComposer& SurfaceFlinger::getHwComposer() const {
496 return mCompositionEngine->getHwComposer();
497}
498
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700499renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
500 return mCompositionEngine->getRenderEngine();
501}
502
Lloyd Pique70d91362018-10-18 16:02:55 -0700503compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
504 return *mCompositionEngine.get();
505}
506
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800507void SurfaceFlinger::bootFinished()
508{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700509 if (mStartPropertySetThread->join() != NO_ERROR) {
510 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800511 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800512 const nsecs_t now = systemTime();
513 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000514 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700515
Mikael Pessa90092f42019-08-26 17:22:04 -0700516 mFrameTracer->initialize();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700517
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700518 // wait patiently for the window manager death
519 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700520 mWindowManager = defaultServiceManager()->getService(name);
521 if (mWindowManager != 0) {
522 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700523 }
Robert Carr720e5062018-07-30 17:45:14 -0700524 sp<IBinder> input(defaultServiceManager()->getService(
525 String16("inputflinger")));
526 if (input == nullptr) {
527 ALOGE("Failed to link to input service");
528 } else {
529 mInputFlinger = interface_cast<IInputFlinger>(input);
530 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700531
Steven Thomas050b2c82017-03-06 11:45:16 -0800532 if (mVrFlinger) {
533 mVrFlinger->OnBootFinished();
534 }
535
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700536 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700537 // formerly we would just kill the process, but we now ask it to exit so it
538 // can choose where to stop the animation.
539 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700540
541 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
542 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
543 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700544
Ana Krulecbd6654b2019-02-15 15:18:15 -0800545 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800546 readPersistentProperties();
547 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800548
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700549 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
550 // set the refresh rate according to the policy
551 const auto& performanceRefreshRate =
552 mRefreshRateConfigs->getRefreshRateFromType(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800553
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700554 if (isDisplayConfigAllowed(performanceRefreshRate.configId)) {
555 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
556 } else {
557 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
558 }
Ana Krulecbd6654b2019-02-15 15:18:15 -0800559 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800560 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800561}
562
Dan Stoza436ccf32018-06-21 12:10:12 -0700563uint32_t SurfaceFlinger::getNewTexture() {
564 {
565 std::lock_guard lock(mTexturePoolMutex);
566 if (!mTexturePool.empty()) {
567 uint32_t name = mTexturePool.back();
568 mTexturePool.pop_back();
569 ATRACE_INT("TexturePoolSize", mTexturePool.size());
570 return name;
571 }
572
573 // The pool was too small, so increase it for the future
574 ++mTexturePoolSize;
575 }
576
577 // The pool was empty, so we need to get a new texture name directly using a
578 // blocking call to the main thread
579 uint32_t name = 0;
580 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
581 return name;
582}
583
Mathias Agopian3f844832013-08-07 21:24:32 -0700584void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700585 std::lock_guard lock(mTexturePoolMutex);
586 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
587 // to actually delete this or not based on mTexturePoolSize
588 mTexturePool.push_back(texture);
589 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700590}
591
Wei Wangf9b05ee2017-07-19 20:59:39 -0700592// Do not call property_set on main thread which will be blocked by init
593// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700594void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700595 ALOGI( "SurfaceFlinger's main thread ready to run. "
596 "Initializing graphics H/W...");
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700597 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900598
Steven Thomasb02664d2017-07-26 18:48:28 -0700599 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800600
Steven Thomasb02664d2017-07-26 18:48:28 -0700601 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700602 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700603 renderEngineFeature |= (useColorManagement ?
604 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700605 renderEngineFeature |= (useContextPriority ?
606 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700607 renderEngineFeature |=
608 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
609 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700610
611 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800612 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700613 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700614 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800615 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700616
617 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
618 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700619 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
620 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800621 // Process any initial hotplug and resulting display changes.
622 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700623 const auto display = getDefaultDisplayDeviceLocked();
624 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700625 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700626 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800627
Steven Thomas050b2c82017-03-06 11:45:16 -0800628 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700629 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700630 // This callback is called from the vr flinger dispatch thread. We
631 // need to call signalTransaction(), which requires holding
632 // mStateLock when we're not on the main thread. Acquiring
633 // mStateLock from the vr flinger dispatch thread might trigger a
634 // deadlock in surface flinger (see b/66916578), so post a message
635 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700636 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700637 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
638 mVrFlingerRequestsDisplay = requestDisplay;
639 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700640 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800641 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700642 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
643 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700644 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700645 .value_or(0),
646 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800647 if (!mVrFlinger) {
648 ALOGE("Failed to start vrflinger");
649 }
650 }
651
Mathias Agopian92a979a2012-08-02 18:32:23 -0700652 // initialize our drawing state
653 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700654
Andy McFadden13a082e2012-08-24 10:16:42 -0700655 // set initial conditions (e.g. unblank default device)
656 initializeDisplays();
657
Steven Thomas137d4bc2019-07-25 16:55:14 -0700658 char primeShaderCache[PROPERTY_VALUE_MAX];
659 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
660 if (atoi(primeShaderCache)) {
661 getRenderEngine().primeCache();
662 }
Dan Stoza4e637772016-07-28 13:31:51 -0700663
Wei Wangf9b05ee2017-07-19 20:59:39 -0700664 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700665
666 const bool presentFenceReliable =
667 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
668 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700669
670 if (mStartPropertySetThread->Start() != NO_ERROR) {
671 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800672 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800673
Dan Stoza9e56aa02015-11-02 13:00:03 -0800674 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700675}
676
Romain Guy11d63f42017-07-20 12:47:14 -0700677void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700678 Mutex::Autolock _l(mStateLock);
679
Romain Guy11d63f42017-07-20 12:47:14 -0700680 char value[PROPERTY_VALUE_MAX];
681
682 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800683 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700684 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800685 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100686
687 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700688 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800689
690 property_get("persist.sys.sf.color_mode", value, "0");
691 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700692}
693
Mathias Agopiana67e4182012-06-19 17:26:12 -0700694void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800695 // Start boot animation service by setting a property mailbox
696 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700697 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800698 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700699 if (mStartPropertySetThread->join() != NO_ERROR) {
700 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800701 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700702}
703
Mathias Agopian875d8e12013-06-07 15:35:48 -0700704size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700705 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700706}
707
Mathias Agopian875d8e12013-06-07 15:35:48 -0700708size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700709 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700710}
711
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800712// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800713
Jamie Gennis582270d2011-08-17 18:19:00 -0700714bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800715 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800716 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800717 return authenticateSurfaceTextureLocked(bufferProducer);
718}
719
720bool SurfaceFlinger::authenticateSurfaceTextureLocked(
721 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800722 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800723 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800724}
725
Brian Anderson6b376712017-04-04 10:51:39 -0700726status_t SurfaceFlinger::getSupportedFrameTimestamps(
727 std::vector<FrameEvent>* outSupported) const {
728 *outSupported = {
729 FrameEvent::REQUESTED_PRESENT,
730 FrameEvent::ACQUIRE,
731 FrameEvent::LATCH,
732 FrameEvent::FIRST_REFRESH_START,
733 FrameEvent::LAST_REFRESH_START,
734 FrameEvent::GPU_COMPOSITION_DONE,
735 FrameEvent::DEQUEUE_READY,
736 FrameEvent::RELEASE,
737 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700738 ConditionalLock _l(mStateLock,
739 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700740 if (!getHwComposer().hasCapability(
741 HWC2::Capability::PresentFenceIsNotReliable)) {
742 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
743 }
744 return NO_ERROR;
745}
746
Dominik Laskowski22488f62019-03-28 09:53:04 -0700747status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
748 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700749 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700750 return BAD_VALUE;
751 }
752
Dominik Laskowski22488f62019-03-28 09:53:04 -0700753 Mutex::Autolock lock(mStateLock);
754
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800755 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700756 if (!displayId) {
757 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700758 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700759
Mathias Agopian8b736f12012-08-13 17:54:26 -0700760 // TODO: Not sure if display density should handled by SF any longer
761 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700762 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700763 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700764 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800765 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700766 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700767 }
768 return density;
769 }
770 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700771 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700772 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700773 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700774 return getDensityFromProperty("ro.sf.lcd_density"); }
775 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700776
Dan Stoza7f7da322014-05-02 15:26:25 -0700777 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700778
Dominik Laskowski075d3172018-05-24 15:50:06 -0700779 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700780 DisplayInfo info = DisplayInfo();
781
Dan Stoza9e56aa02015-11-02 13:00:03 -0800782 float xdpi = hwConfig->getDpiX();
783 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700784
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700785 info.w = hwConfig->getWidth();
786 info.h = hwConfig->getHeight();
787 // Default display viewport to display width and height
788 info.viewportW = info.w;
789 info.viewportH = info.h;
790
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800791 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700792 // The density of the device is provided by a build property
793 float density = Density::getBuildDensity() / 160.0f;
794 if (density == 0) {
795 // the build doesn't provide a density -- this is wrong!
796 // use xdpi instead
797 ALOGE("ro.sf.lcd_density must be defined as a build property");
798 density = xdpi / 160.0f;
799 }
800 if (Density::getEmuDensity()) {
801 // if "qemu.sf.lcd_density" is specified, it overrides everything
802 xdpi = ydpi = density = Density::getEmuDensity();
803 density /= 160.0f;
804 }
805 info.density = density;
806
807 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700808 const auto display = getDefaultDisplayDeviceLocked();
809 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700810
811 // This is for screenrecord
812 const Rect viewport = display->getViewport();
813 if (viewport.isValid()) {
814 info.viewportW = uint32_t(viewport.getWidth());
815 info.viewportH = uint32_t(viewport.getHeight());
816 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700817 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700818 } else {
819 // TODO: where should this value come from?
820 static const int TV_DENSITY = 213;
821 info.density = TV_DENSITY / 160.0f;
822 info.orientation = 0;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700823
824 const auto display = getDisplayDeviceLocked(displayToken);
825 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700826 }
827
Dan Stoza7f7da322014-05-02 15:26:25 -0700828 info.xdpi = xdpi;
829 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800830 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700831 const auto refreshRateType =
832 mRefreshRateConfigs->getRefreshRateTypeFromHwcConfigId(hwConfig->getId());
Ady Abraham796beb02019-04-11 15:23:07 -0700833 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
834 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800835
Andy McFadden91b2ca82014-06-13 14:04:23 -0700836 // This is how far in advance a buffer must be queued for
837 // presentation at a given time. If you want a buffer to appear
838 // on the screen at time N, you must submit the buffer before
839 // (N - presentationDeadline).
840 //
841 // Normally it's one full refresh period (to give SF a chance to
842 // latch the buffer), but this can be reduced by configuring a
843 // DispSync offset. Any additional delays introduced by the hardware
844 // composer or panel must be accounted for here.
845 //
846 // We add an additional 1ms to allow for processing time and
847 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700848 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700849
850 // All non-virtual displays are currently considered secure.
851 info.secure = true;
852
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800853 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700854 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800855 std::swap(info.w, info.h);
856 }
857
Michael Wright28f24d02016-07-12 13:30:53 -0700858 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700859 }
860
Dan Stoza7f7da322014-05-02 15:26:25 -0700861 return NO_ERROR;
862}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700863
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700864status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
865 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700866 return BAD_VALUE;
867 }
868
Ana Krulecc2870422019-01-29 19:00:58 -0800869 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700870 return NO_ERROR;
871}
872
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700873int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
874 const auto display = getDisplayDevice(displayToken);
875 if (!display) {
876 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800877 return BAD_VALUE;
878 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700879
Steven Thomasc9098452019-09-30 17:15:05 -0700880 if (display->isPrimary()) {
881 std::lock_guard<std::mutex> lock(mActiveConfigLock);
882 if (mDesiredActiveConfigChanged) {
883 return mDesiredActiveConfig.configId;
884 } else {
885 return display->getActiveConfig();
886 }
887 } else {
888 return display->getActiveConfig();
889 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700890}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700891
Ady Abraham03b02dd2019-03-21 15:40:11 -0700892void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800893 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800894
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800895 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800896 // config twice. However event generation config might have changed so we need to update it
897 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800898 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700899 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
900 mDesiredActiveConfig = info;
901 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800902
903 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800904 // This will trigger HWC refresh without resetting the idle timer.
905 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700906 // Start receiving vsync samples now, so that we can detect a period
907 // switch.
908 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700909 // As we called to set period, we will call to onRefreshRateChangeCompleted once
910 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700911 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700912 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700913 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800914 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800915 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700916
917 if (mRefreshRateOverlay) {
918 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
919 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800920}
921
922status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
923 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800924
925 std::vector<int32_t> allowedConfig;
926 allowedConfig.push_back(mode);
927
928 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800929}
930
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800931void SurfaceFlinger::setActiveConfigInternal() {
932 ATRACE_CALL();
933
Dominik Laskowski22488f62019-03-28 09:53:04 -0700934 const auto display = getDefaultDisplayDeviceLocked();
935 if (!display) {
936 return;
937 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800938
Dominik Laskowski22488f62019-03-28 09:53:04 -0700939 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700940 mRefreshRateConfigs->setCurrentConfig(mUpcomingActiveConfig.configId);
941 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700942
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800943 display->setActiveConfig(mUpcomingActiveConfig.configId);
944
Alec Mouri754c98a2019-03-18 18:53:42 -0700945 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700946 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800947 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700948
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800949 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800950 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
951 mUpcomingActiveConfig.configId);
952 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800953}
954
Ady Abraham53852a52019-05-28 18:07:44 -0700955void SurfaceFlinger::desiredActiveConfigChangeDone() {
956 std::lock_guard<std::mutex> lock(mActiveConfigLock);
957 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
958 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700959
960 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
961 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700962 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700963}
964
Dominik Laskowski22488f62019-03-28 09:53:04 -0700965bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800966 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800967 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700968 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800969 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700970 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800971 return true;
972 }
973
974 // We received the present fence from the HWC, so we assume it successfully updated
975 // the config, hence we update SF.
976 mCheckPendingFence = false;
977 setActiveConfigInternal();
978 }
979
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800980 // Store the local variable to release the lock.
981 ActiveConfigInfo desiredActiveConfig;
982 {
983 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800984 if (!mDesiredActiveConfigChanged) {
985 return false;
986 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800987 desiredActiveConfig = mDesiredActiveConfig;
988 }
989
Dominik Laskowski22488f62019-03-28 09:53:04 -0700990 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800991 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
992 // display is not valid or we are already in the requested mode
993 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -0700994 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800995 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800996 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800997
Ady Abraham838de062019-02-04 10:24:03 -0800998 // Desired active config was set, it is different than the config currently in use, however
999 // allowed configs might have change by the time we process the refresh.
1000 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001001 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001002 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001003 return false;
1004 }
Alec Mouri7f015182019-07-11 13:56:22 -07001005
Ady Abrahamb838aed2019-02-12 15:30:16 -08001006 mUpcomingActiveConfig = desiredActiveConfig;
1007 const auto displayId = display->getId();
1008 LOG_ALWAYS_FATAL_IF(!displayId);
1009
1010 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1011 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1012
1013 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001014 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001015 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001016 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001017}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001018
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001019status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1020 Vector<ColorMode>* outColorModes) {
1021 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001022 return BAD_VALUE;
1023 }
1024
Peiyong Lina52f0292018-03-14 17:26:31 -07001025 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001026 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001027 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001028 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1029
1030 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1031 if (!displayId) {
1032 return NAME_NOT_FOUND;
1033 }
1034
Dominik Laskowski075d3172018-05-24 15:50:06 -07001035 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001036 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001037 }
Michael Wright28f24d02016-07-12 13:30:53 -07001038 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001039
1040 // If it's built-in display and the configuration claims it's not wide color capable,
1041 // filter out all wide color modes. The typical reason why this happens is that the
1042 // hardware is not good enough to support GPU composition of wide color, and thus the
1043 // OEMs choose to disable this capability.
1044 if (isInternalDisplay && !hasWideColorDisplay) {
1045 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1046 isWideColorMode);
1047 } else {
1048 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1049 }
Michael Wright28f24d02016-07-12 13:30:53 -07001050
1051 return NO_ERROR;
1052}
1053
Daniel Solomon42d04562019-01-20 21:03:19 -08001054status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1055 ui::DisplayPrimaries &primaries) {
1056 if (!displayToken) {
1057 return BAD_VALUE;
1058 }
1059
1060 // Currently we only support this API for a single internal display.
1061 if (getInternalDisplayToken() != displayToken) {
1062 return BAD_VALUE;
1063 }
1064
1065 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1066 return NO_ERROR;
1067}
1068
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001069ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1070 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001071 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001072 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001073 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001074}
1075
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001076status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001077 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001078 Vector<ColorMode> modes;
1079 getDisplayColorModes(displayToken, &modes);
1080 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1081 if (mode < ColorMode::NATIVE || !exists) {
1082 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1083 decodeColorMode(mode).c_str(), mode, displayToken.get());
1084 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001085 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001086 const auto display = getDisplayDevice(displayToken);
1087 if (!display) {
1088 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1089 decodeColorMode(mode).c_str(), mode, displayToken.get());
1090 } else if (display->isVirtual()) {
1091 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1092 decodeColorMode(mode).c_str(), mode);
1093 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001094 display->getCompositionDisplay()->setColorProfile(
1095 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1096 RenderIntent::COLORIMETRIC,
1097 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098 }
1099 }));
1100
Michael Wright28f24d02016-07-12 13:30:53 -07001101 return NO_ERROR;
1102}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001103
Svetoslavd85084b2014-03-20 10:28:31 -07001104status_t SurfaceFlinger::clearAnimationFrameStats() {
1105 Mutex::Autolock _l(mStateLock);
1106 mAnimFrameTracker.clearStats();
1107 return NO_ERROR;
1108}
1109
1110status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1111 Mutex::Autolock _l(mStateLock);
1112 mAnimFrameTracker.getStats(outStats);
1113 return NO_ERROR;
1114}
1115
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001116status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1117 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001118 Mutex::Autolock _l(mStateLock);
1119
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001120 const auto display = getDisplayDeviceLocked(displayToken);
1121 if (!display) {
1122 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001123 return BAD_VALUE;
1124 }
1125
Peiyong Linfb069302018-04-25 14:34:31 -07001126 // At this point the DisplayDeivce should already be set up,
1127 // meaning the luminance information is already queried from
1128 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001129 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001130 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1131 capabilities.getDesiredMaxLuminance(),
1132 capabilities.getDesiredMaxAverageLuminance(),
1133 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001134
1135 return NO_ERROR;
1136}
1137
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001138status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1139 ui::PixelFormat* outFormat,
1140 ui::Dataspace* outDataspace,
1141 uint8_t* outComponentMask) const {
1142 if (!outFormat || !outDataspace || !outComponentMask) {
1143 return BAD_VALUE;
1144 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001145 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001146 if (!display || !display->getId()) {
1147 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1148 return BAD_VALUE;
1149 }
1150 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1151 outDataspace, outComponentMask);
1152}
1153
Kevin DuBois74e53772018-11-19 10:52:38 -08001154status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1155 bool enable, uint8_t componentMask,
1156 uint64_t maxFrames) const {
1157 const auto display = getDisplayDevice(displayToken);
1158 if (!display || !display->getId()) {
1159 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1160 return BAD_VALUE;
1161 }
1162
1163 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1164 componentMask, maxFrames);
1165}
1166
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001167status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1168 uint64_t maxFrames, uint64_t timestamp,
1169 DisplayedFrameStats* outStats) const {
1170 const auto display = getDisplayDevice(displayToken);
1171 if (!display || !display->getId()) {
1172 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1173 return BAD_VALUE;
1174 }
1175
1176 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1177 outStats);
1178}
1179
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001180status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1181 if (!outSupported) {
1182 return BAD_VALUE;
1183 }
1184 *outSupported = getRenderEngine().supportsProtectedContent();
1185 return NO_ERROR;
1186}
1187
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001188status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1189 bool* outIsWideColorDisplay) const {
1190 if (!displayToken || !outIsWideColorDisplay) {
1191 return BAD_VALUE;
1192 }
1193 Mutex::Autolock _l(mStateLock);
1194 const auto display = getDisplayDeviceLocked(displayToken);
1195 if (!display) {
1196 return BAD_VALUE;
1197 }
Peiyong Linff84a152019-05-17 18:36:19 -07001198
1199 // Use hasWideColorDisplay to override built-in display.
1200 const auto displayId = display->getId();
1201 if (displayId && displayId == getInternalDisplayIdLocked()) {
1202 *outIsWideColorDisplay = hasWideColorDisplay;
1203 return NO_ERROR;
1204 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001205 *outIsWideColorDisplay = display->hasWideColorGamut();
1206 return NO_ERROR;
1207}
1208
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001209status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001210 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001211 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001212
Dominik Laskowski6505f792019-09-18 11:10:05 -07001213 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1214 mEventQueue->setEventConnection(
1215 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001216 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001217 }));
1218
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001219 return NO_ERROR;
1220}
1221
1222status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001223 Mutex::Autolock lock(mStateLock);
1224 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001225}
1226
Lloyd Pique755e3192018-01-31 16:46:15 -08001227status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1228 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001229 // Try to acquire a lock for 1s, fail gracefully
1230 const status_t err = mStateLock.timedLock(s2ns(1));
1231 const bool locked = (err == NO_ERROR);
1232 if (!locked) {
1233 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1234 return TIMED_OUT;
1235 }
1236
1237 outLayers->clear();
1238 mCurrentState.traverseInZOrder([&](Layer* layer) {
1239 outLayers->push_back(layer->getLayerDebugInfo());
1240 });
1241
1242 mStateLock.unlock();
1243 return NO_ERROR;
1244}
1245
Peiyong Linc6780972018-10-28 15:24:08 -07001246status_t SurfaceFlinger::getCompositionPreference(
1247 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1248 Dataspace* outWideColorGamutDataspace,
1249 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001250 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001251 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001252 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001253 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001254 return NO_ERROR;
1255}
1256
Dan Stozaec460082018-12-17 15:35:09 -08001257status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1258 const sp<IBinder>& stopLayerHandle,
1259 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001260 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001261 return BAD_VALUE;
1262 }
1263 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001264 return NO_ERROR;
1265}
1266
Dan Stozaec460082018-12-17 15:35:09 -08001267status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001268 if (!listener) {
1269 return BAD_VALUE;
1270 }
Dan Stozaec460082018-12-17 15:35:09 -08001271 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001272 return NO_ERROR;
1273}
Dan Gittik57e63c52019-01-18 16:37:54 +00001274
1275status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1276 bool* outSupport) const {
1277 if (!displayToken || !outSupport) {
1278 return BAD_VALUE;
1279 }
1280 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1281 if (!displayId) {
1282 return NAME_NOT_FOUND;
1283 }
1284 *outSupport =
1285 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1286 return NO_ERROR;
1287}
1288
1289status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1290 float brightness) const {
1291 if (!displayToken) {
1292 return BAD_VALUE;
1293 }
1294 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1295 if (!displayId) {
1296 return NAME_NOT_FOUND;
1297 }
1298 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1299}
1300
Ady Abraham8532d012019-05-08 14:50:56 -07001301status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1302 PowerHint powerHint = static_cast<PowerHint>(hintId);
1303
1304 if (powerHint == PowerHint::INTERACTION) {
1305 mScheduler->notifyTouchEvent();
1306 }
1307
1308 return NO_ERROR;
1309}
1310
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001311// ----------------------------------------------------------------------------
1312
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001313sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001314 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001315 const auto& handle =
1316 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001317
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001318 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001319}
1320
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001321// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001322
1323void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001324 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001325}
1326
1327void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001328 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001329 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001330}
1331
1332void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001333 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001334 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001335}
1336
1337void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001338 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001339 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001340}
1341
1342status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001343 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001344 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001345}
1346
1347status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001348 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001349 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001350 if (res == NO_ERROR) {
1351 msg->wait();
1352 }
1353 return res;
1354}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001355
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001356void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001357 do {
1358 waitForEvent();
1359 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001360}
1361
Dominik Laskowski83b88212018-12-11 13:34:06 -08001362nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001363 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001364 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1365 return 0;
1366 }
1367
1368 const auto config = getHwComposer().getActiveConfig(*displayId);
1369 return config ? config->getVsyncPeriod() : 0;
1370}
1371
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001372void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1373 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001374 ATRACE_NAME("SF onVsync");
1375
Steven Thomas3cfac282017-02-06 12:29:30 -08001376 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001377 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001378 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 return;
1380 }
1381
Dominik Laskowski075d3172018-05-24 15:50:06 -07001382 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001383 return;
1384 }
1385
Dominik Laskowski075d3172018-05-24 15:50:06 -07001386 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001387 // For now, we don't do anything with external display vsyncs.
1388 return;
1389 }
1390
Alec Mourif8e689c2019-05-20 18:32:22 -07001391 bool periodFlushed = false;
1392 mScheduler->addResyncSample(timestamp, &periodFlushed);
1393 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001394 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001395 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001396}
1397
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001398void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001399 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1400 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001401}
1402
Ady Abraham261614e2019-07-10 17:53:12 -07001403bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001404 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001405}
1406
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001407void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001408 const auto display = getDefaultDisplayDeviceLocked();
1409 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001410 return;
1411 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001412 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001413
Ana Krulec7d1d6832018-12-27 11:10:09 -08001414 // Don't do any updating if the current fps is the same as the new one.
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001415 const auto& refreshRateConfig = mRefreshRateConfigs->getRefreshRateFromType(refreshRate);
1416 const int desiredConfigId = refreshRateConfig.configId;
Alec Mouri0a1cc962019-03-14 12:33:02 -07001417
Dominik Laskowski22488f62019-03-28 09:53:04 -07001418 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001419 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1420 return;
1421 }
1422
Dominik Laskowski22488f62019-03-28 09:53:04 -07001423 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001424}
1425
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001426void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001427 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001428 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001429 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001430
Lloyd Piqueba04e622017-12-14 17:11:26 -08001431 // Ignore events that do not have the right sequenceId.
1432 if (sequenceId != getBE().mComposerSequenceId) {
1433 return;
1434 }
1435
Steven Thomasb02664d2017-07-26 18:48:28 -07001436 // Only lock if we're not on the main thread. This function is normally
1437 // called on a hwbinder thread, but for the primary display it's called on
1438 // the main thread with the state lock already held, so don't attempt to
1439 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001440 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001441
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001442 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001443
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001444 if (std::this_thread::get_id() == mMainThreadId) {
1445 // Process all pending hot plug events immediately if we are on the main thread.
1446 processDisplayHotplugEventsLocked();
1447 }
1448
Lloyd Piqueba04e622017-12-14 17:11:26 -08001449 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001450}
1451
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001452void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001453 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001454 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001455 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001456 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001457 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001458}
1459
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001460void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001461 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001462
1463 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1464 // display power state.
1465 postMessageAsync(new LambdaMessage(
1466 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1467}
1468
1469void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1470 ATRACE_CALL();
1471
Ady Abraham27c70212019-06-11 10:52:26 -07001472 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1473
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001474 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001475 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1476 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001477 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001478 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001479 }
Mathias Agopian86303202012-07-24 22:46:10 -07001480}
1481
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001482// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001483void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001484 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001485 // Clear the drawing state so that the logic inside of
1486 // handleTransactionLocked will fire. It will determine the delta between
1487 // mCurrentState and mDrawingState and re-apply all changes when we make the
1488 // transition.
1489 mDrawingState.displays.clear();
1490 mDisplays.clear();
1491}
1492
Steven Thomas050b2c82017-03-06 11:45:16 -08001493void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001494 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001495 if (!mVrFlinger)
1496 return;
1497 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001498 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001499 return;
1500 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001501
Lloyd Pique441d5042018-10-18 16:49:51 -07001502 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001503 ALOGE("Vr flinger is only supported for remote hardware composer"
1504 " service connections. Ignoring request to transition to vr"
1505 " flinger.");
1506 mVrFlingerRequestsDisplay = false;
1507 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001508 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001509
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001510 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001511
Steven Thomas0123ac62018-07-12 11:32:34 -07001512 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001513 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001514
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001515 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001516
1517 // Clear out all the output layers from the composition engine for all
1518 // displays before destroying the hardware composer interface. This ensures
1519 // any HWC layers are destroyed through that interface before it becomes
1520 // invalid.
1521 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001522 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001523 }
1524
Steven Thomas0123ac62018-07-12 11:32:34 -07001525 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1526 // called below. Clear the reference now so we don't accidentally use it
1527 // later.
1528 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001529
Steven Thomasb02664d2017-07-26 18:48:28 -07001530 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001531 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001532 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001533
Steven Thomasb02664d2017-07-26 18:48:28 -07001534 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001535 // Delete the current instance before creating the new one
1536 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1537 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1538 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1539 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001540
Lloyd Pique441d5042018-10-18 16:49:51 -07001541 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001542 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001543
1544 if (vrFlingerRequestsDisplay) {
1545 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001546 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001547
1548 mVisibleRegionsDirty = true;
1549 invalidateHwcGeometry();
1550
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001551 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001552 display = getDefaultDisplayDeviceLocked();
1553 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001554 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001555
Steven Thomasb02664d2017-07-26 18:48:28 -07001556 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001557 const nsecs_t vsyncPeriod = getVsyncPeriod();
1558 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001559
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001560 // The present fences returned from vr_hwc are not an accurate
1561 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001562 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001563
Steven Thomasb02664d2017-07-26 18:48:28 -07001564 // Use phase of 0 since phase is not known.
1565 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001566 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001567 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001568
Ana Krulecc2870422019-01-29 19:00:58 -08001569 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001570
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001571 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001572 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001573}
1574
Ady Abraham11579302019-09-19 12:35:58 -07001575bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1576 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001577 // We are storing the last 2 present fences. If sf's phase offset is to be
1578 // woken up before the actual vsync but targeting the next vsync, we need to check
1579 // fence N-2
1580 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001581 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001582 ? mPreviousPresentFences[0]
1583 : mPreviousPresentFences[1];
1584
Ady Abraham11579302019-09-19 12:35:58 -07001585 if (fence == Fence::NO_FENCE) {
1586 return false;
1587 }
1588
1589 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1590 fence->wait(graceTimeMs);
1591 }
1592
1593 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001594}
1595
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001596void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001597 DisplayStatInfo stats;
1598 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001599 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001600 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001601 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001602 mPhaseOffsets->getOffsetThresholdForNextVsync()
1603 ? presentTime
1604 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001605}
1606
Dominik Laskowski22488f62019-03-28 09:53:04 -07001607void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001608 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001609 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001610 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001611 // calculate the expected present time once and use the cached
1612 // value throughout this frame to make sure all layers are
1613 // seeing this same value.
1614 populateExpectedPresentTime();
1615
Ady Abraham11579302019-09-19 12:35:58 -07001616 // When Backpressure propagation is enabled we want to give a small grace period
1617 // for the present fence to fire instead of just giving up on this frame to handle cases
1618 // where present fence is just about to get signaled.
1619 const int graceTimeForPresentFenceMs =
1620 (mPropagateBackpressure &&
1621 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1622 ? 1
1623 : 0;
1624 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1625 previousFrameMissed(
1626 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001627 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1628 mHadDeviceComposition && frameMissed};
1629 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1630 mHadClientComposition && frameMissed};
1631
Alec Mouricc0fc602019-02-26 21:45:19 -08001632 if (frameMissed) {
1633 mFrameMissedCount++;
1634 mTimeStats->incrementMissedFrames();
1635 }
1636
Alec Mouri40189b02019-03-05 15:07:54 -08001637 if (hwcFrameMissed) {
1638 mHwcFrameMissedCount++;
1639 }
1640
1641 if (gpuFrameMissed) {
1642 mGpuFrameMissedCount++;
1643 }
1644
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001645 if (mUseSmart90ForVideo) {
1646 // This call is made each time SF wakes up and creates a new frame. It is part
1647 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001648 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001649 }
1650
Ady Abrahamb838aed2019-02-12 15:30:16 -08001651 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001652 break;
1653 }
1654
Ady Abrahamadb9a992019-09-19 21:21:55 +00001655 if (frameMissed && mPropagateBackpressure) {
1656 if ((hwcFrameMissed && !gpuFrameMissed) ||
1657 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001658 signalLayerUpdate();
1659 break;
1660 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001661 }
Dan Stoza50182882016-07-08 12:02:20 -07001662
Steven Thomas050b2c82017-03-06 11:45:16 -08001663 // Now that we're going to make it to the handleMessageTransaction()
1664 // call below it's safe to call updateVrFlinger(), which will
1665 // potentially trigger a display handoff.
1666 updateVrFlinger();
1667
Dan Stoza6b9454d2014-11-07 16:00:59 -08001668 bool refreshNeeded = handleMessageTransaction();
1669 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001670
1671 updateCursorAsync();
1672 updateInputFlinger();
1673
Dan Stoza58784442014-12-02 16:58:17 -08001674 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001675 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001676 // Signal a refresh if a transaction modified the window state,
1677 // a new buffer was latched, or if HWC has requested a full
1678 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001679 signalRefresh();
1680 }
1681 break;
1682 }
1683 case MessageQueue::REFRESH: {
1684 handleMessageRefresh();
1685 break;
1686 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001687 }
1688}
1689
Dan Stoza6b9454d2014-11-07 16:00:59 -08001690bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001691 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001692 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001693
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001694 bool flushedATransaction = flushTransactionQueues();
1695
1696 bool runHandleTransaction = transactionFlags &&
1697 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1698
1699 if (runHandleTransaction) {
1700 handleTransaction(eTransactionMask);
1701 } else {
1702 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001703 }
1704
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001705 if (transactionFlushNeeded()) {
1706 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001707 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001708
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001709 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001710}
1711
Mathias Agopian4fec8732012-06-29 14:12:52 -07001712void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001713 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001714
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001715 mRefreshPending = false;
1716
Lloyd Piqueab039b52019-02-13 14:22:42 -08001717 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001718 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001719 for (const auto& [_, display] : mDisplays) {
1720 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1721 }
1722 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1723 auto compositionLayer = layer->getCompositionLayer();
1724 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1725 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001726 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1727 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1728 auto compositionLayer = layer->getCompositionLayer();
1729 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
1730 }
1731
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001732 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001733 refreshArgs.outputColorSetting = useColorManagement
1734 ? mDisplayColorSetting
1735 : compositionengine::OutputColorSetting::kUnmanaged;
1736 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1737 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001738
1739 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1740 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001741
1742 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1743 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1744 mDrawingState.colorMatrixChanged = false;
1745 }
1746
1747 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1748
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001749 if (mDebugRegion != 0) {
1750 refreshArgs.devOptFlashDirtyRegionsDelay =
1751 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1752 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001753
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001754 mGeometryInvalid = false;
1755
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001756 mCompositionEngine->present(refreshArgs);
1757
David Sodmanfa9b2af2017-12-24 13:28:59 -08001758 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001759 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001760
Lloyd Pique66d68602019-02-13 14:23:31 -08001761 mHadClientComposition =
1762 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1763 auto& displayDevice = tokenDisplayPair.second;
1764 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1765 });
1766 mHadDeviceComposition =
1767 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1768 auto& displayDevice = tokenDisplayPair.second;
1769 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1770 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001771
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001772 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001773
David Sodman7e4ae112018-02-09 15:02:28 -08001774 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001775 if (mVisibleRegionsDirty) {
1776 mVisibleRegionsDirty = false;
1777 if (mTracingEnabled) {
1778 mTracing.notify("visibleRegionsDirty");
1779 }
1780 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001781
1782 if (mCompositionEngine->needsAnotherUpdate()) {
1783 signalLayerUpdate();
1784 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001785}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001786
David Sodmanfa9b2af2017-12-24 13:28:59 -08001787
1788bool SurfaceFlinger::handleMessageInvalidate() {
1789 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001790 bool refreshNeeded = handlePageFlip();
1791
Vishnu Nair4351ad52019-02-11 14:13:02 -08001792 if (mVisibleRegionsDirty) {
1793 computeLayerBounds();
1794 }
1795
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001796 for (auto& layer : mLayersPendingRefresh) {
1797 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001798 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001799 invalidateLayerStack(layer, visibleReg);
1800 }
1801 mLayersPendingRefresh.clear();
1802 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001803}
1804
Ana Krulece588e312018-09-18 12:32:24 -07001805void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1806 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001807 // Update queue of past composite+present times and determine the
1808 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001809 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001810 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001811 while (!getBE().mCompositePresentTimes.empty()) {
1812 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001813 // Cached values should have been updated before calling this method,
1814 // which helps avoid duplicate syscalls.
1815 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1816 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1817 break;
1818 }
1819 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001820 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001821 }
1822
1823 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001824 while (getBE().mCompositePresentTimes.size() > 16) {
1825 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001826 }
1827
Ana Krulece588e312018-09-18 12:32:24 -07001828 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001829}
1830
Ana Krulece588e312018-09-18 12:32:24 -07001831void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1832 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001833 // Integer division and modulo round toward 0 not -inf, so we need to
1834 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001835 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1836 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1837 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001838
Ana Krulec757f63a2019-01-25 10:46:18 -08001839 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001840 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001841 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001842 }
1843
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001844 // Snap the latency to a value that removes scheduling jitter from the
1845 // composition and present times, which often have >1ms of jitter.
1846 // Reducing jitter is important if an app attempts to extrapolate
1847 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001848 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001849 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001850 nsecs_t bias = stats.vsyncPeriod / 2;
1851 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1852 nsecs_t snappedCompositeToPresentLatency =
1853 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001854
David Sodman99974d22017-11-28 12:04:33 -08001855 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001856 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1857 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001858 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001859}
1860
David Sodman2b406362017-12-15 13:33:47 -08001861void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001862{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001863 ATRACE_CALL();
1864 ALOGV("postComposition");
1865
Brian Anderson3546a3f2016-07-14 11:51:14 -07001866 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001867 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001868 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001869 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001870 }
1871
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001872 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001873 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001874
David Sodman73beded2017-11-15 11:56:06 -08001875 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001876 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08001877 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001878 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001879 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1880 ->getRenderSurface()
1881 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001882 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001883 } else {
1884 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1885 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001886
David Sodman73beded2017-11-15 11:56:06 -08001887 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001888 mPreviousPresentFences[1] = mPreviousPresentFences[0];
1889 mPreviousPresentFences[0] = displayDevice
1890 ? getHwComposer().getPresentFence(*displayDevice->getId())
1891 : Fence::NO_FENCE;
1892 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08001893 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001894
Ana Krulece588e312018-09-18 12:32:24 -07001895 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08001896 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001897
Lloyd Piqueab039b52019-02-13 14:22:42 -08001898 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
1899 // be sampled a little later than when we started doing work for this frame,
1900 // but that should be okay since updateCompositorTiming has snapping logic.
1901 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
1902 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001903 CompositorTiming compositorTiming;
1904 {
David Sodman99974d22017-11-28 12:04:33 -08001905 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1906 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001907 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001908
Robert Carr2047fae2016-11-28 14:09:09 -08001909 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001910 bool frameLatched =
1911 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
1912 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001913 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001914 recordBufferingStats(layer->getName().string(),
1915 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001916 }
Robert Carr2047fae2016-11-28 14:09:09 -08001917 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001918
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001919 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001920 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001921 }
1922
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001923 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001924 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1925 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001926 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001927 }
1928 }
1929
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001930 if (mAnimCompositionPending) {
1931 mAnimCompositionPending = false;
1932
Brian Anderson4e606e32017-03-16 15:34:57 -07001933 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001934 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001935 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07001936 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001937 // The HWC doesn't support present fences, so use the refresh
1938 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07001939 const nsecs_t presentTime =
1940 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001941 mAnimFrameTracker.setActualPresentTime(presentTime);
1942 }
1943 mAnimFrameTracker.advanceFrame();
1944 }
Dan Stozab90cf072015-03-05 11:05:59 -08001945
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001946 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001947 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001948 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001949 }
1950
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001951 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001952
Lloyd Pique32cbe282018-10-19 13:09:22 -07001953 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1954 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001955 return;
1956 }
1957
1958 nsecs_t currentTime = systemTime();
1959 if (mHasPoweredOff) {
1960 mHasPoweredOff = false;
1961 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001962 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001963 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001964 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1965 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001966 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001967 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001968 }
David Sodman4a36e932017-11-07 14:29:47 -08001969 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001970 }
David Sodman4a36e932017-11-07 14:29:47 -08001971 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001972
1973 {
1974 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07001975 if (mTexturePool.size() < mTexturePoolSize) {
1976 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07001977 const size_t offset = mTexturePool.size();
1978 mTexturePool.resize(mTexturePoolSize);
1979 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1980 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07001981 } else if (mTexturePool.size() > mTexturePoolSize) {
1982 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
1983 const size_t offset = mTexturePoolSize;
1984 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
1985 mTexturePool.resize(mTexturePoolSize);
1986 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07001987 }
1988 }
Marissa Walle2ffb422018-10-12 11:33:52 -07001989
Ady Abrahambe0f9482019-04-24 15:41:53 -07001990 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07001991 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08001992
Kevin DuBois413287f2019-02-25 08:46:47 -08001993 if (mLumaSampling && mRegionSamplingThread) {
1994 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08001995 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07001996
1997 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
1998 // side-effect of getTotalSize(), so we check that again here
1999 if (ATRACE_ENABLED()) {
2000 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2001 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002002}
2003
Vishnu Nair4351ad52019-02-11 14:13:02 -08002004void SurfaceFlinger::computeLayerBounds() {
2005 for (const auto& pair : mDisplays) {
2006 const auto& displayDevice = pair.second;
2007 const auto display = displayDevice->getCompositionDisplay();
2008 for (const auto& layer : mDrawingState.layersSortedByZ) {
2009 // only consider the layers on the given layer stack
2010 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002011 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002012 }
2013
2014 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2015 }
2016 }
2017}
2018
David Sodmanfa9b2af2017-12-24 13:28:59 -08002019void SurfaceFlinger::postFrame()
2020{
2021 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002022 const auto display = getDefaultDisplayDeviceLocked();
2023 if (display && getHwComposer().isConnected(*display->getId())) {
2024 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002025 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2026 logFrameStats();
2027 }
2028 }
2029}
2030
Mathias Agopian87baae12012-07-31 12:38:26 -07002031void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002032{
Mathias Agopian841cde52012-03-01 15:44:37 -08002033 ATRACE_CALL();
2034
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002035 // here we keep a copy of the drawing state (that is the state that's
2036 // going to be overwritten by handleTransactionLocked()) outside of
2037 // mStateLock so that the side-effects of the State assignment
2038 // don't happen with mStateLock held (which can cause deadlocks).
2039 State drawingState(mDrawingState);
2040
Mathias Agopianca4d3602011-05-19 15:38:14 -07002041 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002042 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002043
Mathias Agopianca4d3602011-05-19 15:38:14 -07002044 // Here we're guaranteed that some transaction flags are set
2045 // so we can call handleTransactionLocked() unconditionally.
2046 // We call getTransactionFlags(), which will also clear the flags,
2047 // with mStateLock held to guarantee that mCurrentState won't change
2048 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002049
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002050 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002051 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002052 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002053
Mathias Agopianca4d3602011-05-19 15:38:14 -07002054 mDebugInTransaction = 0;
2055 invalidateHwcGeometry();
2056 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002057}
2058
Lloyd Piqueba04e622017-12-14 17:11:26 -08002059void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2060 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002061 const std::optional<DisplayIdentificationInfo> info =
2062 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002063
Dominik Laskowski075d3172018-05-24 15:50:06 -07002064 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002065 continue;
2066 }
2067
Lloyd Piqueba04e622017-12-14 17:11:26 -08002068 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002069 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002070 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002071 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2072 initScheduler(info->id);
2073 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002074 mPhysicalDisplayTokens[info->id] = new BBinder();
2075 DisplayDeviceState state;
2076 state.displayId = info->id;
2077 state.isSecure = true; // All physical displays are currently considered secure.
2078 state.displayName = info->name;
2079 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2080 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002081 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002082 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002083 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002084
Dominik Laskowski075d3172018-05-24 15:50:06 -07002085 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2086 if (index >= 0) {
2087 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2088 mInterceptor->saveDisplayDeletion(state.sequenceId);
2089 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002090 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002091 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002092 }
2093
2094 processDisplayChangesLocked();
2095 }
2096
2097 mPendingHotplugEvents.clear();
2098}
2099
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002100void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002101 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2102 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002103}
2104
Lloyd Pique99d3da52018-01-22 17:48:03 -08002105sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002106 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002107 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002108 const sp<IGraphicBufferProducer>& producer) {
2109 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002110 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002111 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002112 creationArgs.isSecure = state.isSecure;
2113 creationArgs.displaySurface = dispSurface;
2114 creationArgs.hasWideColorGamut = false;
2115 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002116 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002117
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002118 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002119 creationArgs.isPrimary = isInternalDisplay;
2120
2121 if (useColorManagement && displayId) {
2122 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002123 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002124 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002125 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002126 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002127
Dominik Laskowski7e045462018-05-30 13:02:02 -07002128 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002129 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002130 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002131 }
tangrobin6753a022018-08-10 10:58:54 +08002132 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002133
Dominik Laskowski075d3172018-05-24 15:50:06 -07002134 if (displayId) {
2135 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002136 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002137 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002138 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002139
Lloyd Pique90c115d2018-09-18 21:39:42 -07002140 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002141 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002142 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002143
Lloyd Pique99d3da52018-01-22 17:48:03 -08002144 // Make sure that composition can never be stalled by a virtual display
2145 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002146 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002147 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002148 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2149 }
2150
Dominik Laskowski075d3172018-05-24 15:50:06 -07002151 creationArgs.displayInstallOrientation =
2152 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002153
Lloyd Pique99d3da52018-01-22 17:48:03 -08002154 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002155 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002156
Lloyd Pique90c115d2018-09-18 21:39:42 -07002157 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002158
2159 if (maxFrameBufferAcquiredBuffers >= 3) {
2160 nativeWindowSurface->preallocateBuffers();
2161 }
2162
2163 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002164 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002165 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002166 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002167 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002168 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002169 display->getCompositionDisplay()->setColorProfile(
2170 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2171 RenderIntent::COLORIMETRIC,
2172 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002173 if (!state.isVirtual()) {
2174 LOG_ALWAYS_FATAL_IF(!displayId);
2175 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002176 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002177
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002178 display->setLayerStack(state.layerStack);
2179 display->setProjection(state.orientation, state.viewport, state.frame);
2180 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002181
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002182 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002183}
2184
Lloyd Pique347200f2017-12-14 17:00:15 -08002185void SurfaceFlinger::processDisplayChangesLocked() {
2186 // here we take advantage of Vector's copy-on-write semantics to
2187 // improve performance by skipping the transaction entirely when
2188 // know that the lists are identical
2189 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2190 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2191 if (!curr.isIdenticalTo(draw)) {
2192 mVisibleRegionsDirty = true;
2193 const size_t cc = curr.size();
2194 size_t dc = draw.size();
2195
2196 // find the displays that were removed
2197 // (ie: in drawing state but not in current state)
2198 // also handle displays that changed
2199 // (ie: displays that are in both lists)
2200 for (size_t i = 0; i < dc;) {
2201 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2202 if (j < 0) {
2203 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002204 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002205 // Save display ID before disconnecting.
2206 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002207 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002208
2209 if (!display->isVirtual()) {
2210 LOG_ALWAYS_FATAL_IF(!displayId);
2211 dispatchDisplayHotplugEvent(displayId->value, false);
2212 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002213 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002214
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002215 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002216 } else {
2217 // this display is in both lists. see if something changed.
2218 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002219 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002220 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2221 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2222 if (state_binder != draw_binder) {
2223 // changing the surface is like destroying and
2224 // recreating the DisplayDevice, so we just remove it
2225 // from the drawing state, so that it get re-added
2226 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002227 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002228 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002229 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002230 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002231 mDrawingState.displays.removeItemsAt(i);
2232 dc--;
2233 // at this point we must loop to the next item
2234 continue;
2235 }
2236
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002237 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002238 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002239 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002240 }
2241 if ((state.orientation != draw[i].orientation) ||
2242 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002243 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002244 }
2245 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002246 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002247 }
2248 }
2249 }
2250 ++i;
2251 }
2252
2253 // find displays that were added
2254 // (ie: in current state but not in drawing state)
2255 for (size_t i = 0; i < cc; i++) {
2256 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2257 const DisplayDeviceState& state(curr[i]);
2258
Lloyd Pique542307f2018-10-19 13:24:08 -07002259 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002260 sp<IGraphicBufferProducer> producer;
2261 sp<IGraphicBufferProducer> bqProducer;
2262 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002263 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002264
Dominik Laskowski075d3172018-05-24 15:50:06 -07002265 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002266 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002267 // Virtual displays without a surface are dormant:
2268 // they have external state (layer stack, projection,
2269 // etc.) but no internal state (i.e. a DisplayDevice).
2270 if (state.surface != nullptr) {
2271 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002272 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002273 int width = 0;
2274 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2275 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2276 int height = 0;
2277 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2278 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2279 int intFormat = 0;
2280 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2281 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002282 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002283
Dominik Laskowski075d3172018-05-24 15:50:06 -07002284 displayId =
2285 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002286 }
2287
2288 // TODO: Plumb requested format back up to consumer
2289
2290 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002291 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002292 bqProducer, bqConsumer,
2293 state.displayName);
2294
2295 dispSurface = vds;
2296 producer = vds;
2297 }
2298 } else {
2299 ALOGE_IF(state.surface != nullptr,
2300 "adding a supported display, but rendering "
2301 "surface is provided (%p), ignoring it",
2302 state.surface.get());
2303
Dominik Laskowski075d3172018-05-24 15:50:06 -07002304 displayId = state.displayId;
2305 LOG_ALWAYS_FATAL_IF(!displayId);
2306 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002307 producer = bqProducer;
2308 }
2309
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002310 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002311 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002312 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002313 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002314 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002315 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002316 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002317 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002318 }
2319 }
2320 }
2321 }
2322 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002323
2324 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002325}
2326
Mathias Agopian87baae12012-07-31 12:38:26 -07002327void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002328{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002329 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2330
Dan Stoza7dde5992015-05-22 09:51:44 -07002331 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002332 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2333 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002334 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002335
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002336 /*
2337 * Traversal of the children
2338 * (perform the transaction for each of them if needed)
2339 */
2340
Marissa Wall06255332019-03-27 13:48:27 -07002341 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002342 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002343 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002344 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002345
2346 const uint32_t flags = layer->doTransaction(0);
2347 if (flags & Layer::eVisibleRegion)
2348 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002349
2350 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002351 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002352 }
Robert Carr2047fae2016-11-28 14:09:09 -08002353 });
Marissa Wall06255332019-03-27 13:48:27 -07002354 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002355 }
2356
2357 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002358 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002359 */
2360
Mathias Agopiane57f2922012-08-09 16:29:12 -07002361 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002362 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002363 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002364 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002365
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002366 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002367 // The transform hint might have changed for some layers
2368 // (either because a display has changed, or because a layer
2369 // as changed).
2370 //
2371 // Walk through all the layers in currentLayers,
2372 // and update their transform hint.
2373 //
2374 // If a layer is visible only on a single display, then that
2375 // display is used to calculate the hint, otherwise we use the
2376 // default display.
2377 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002378 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002379 // the hint is set before we acquire a buffer from the surface texture.
2380 //
2381 // NOTE: layer transactions have taken place already, so we use their
2382 // drawing state. However, SurfaceFlinger's own transaction has not
2383 // happened yet, so we must use the current state layer list
2384 // (soon to become the drawing state list).
2385 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002386 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002387 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002388 bool first = true;
2389 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002390 // NOTE: we rely on the fact that layers are sorted by
2391 // layerStack first (so we don't have to traverse the list
2392 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002393 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002394 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002395 currentlayerStack = layerStack;
2396 // figure out if this layerstack is mirrored
2397 // (more than one display) if so, pick the default display,
2398 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002399 hintDisplay = nullptr;
2400 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002401 if (display->getCompositionDisplay()
2402 ->belongsInOutput(layer->getLayerStack(),
2403 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002404 if (hintDisplay) {
2405 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002406 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002407 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002408 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002409 }
2410 }
2411 }
2412 }
Chet Haase91d25932013-04-11 15:24:55 -07002413
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002414 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002415 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2416 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002417
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002418 // could be null when this layer is using a layerStack
2419 // that is not visible on any display. Also can occur at
2420 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002421 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002422 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002423
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002424 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002425 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002426 if (hintDisplay) {
2427 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002428 }
Robert Carr2047fae2016-11-28 14:09:09 -08002429
2430 first = false;
2431 });
Mathias Agopian84300952012-11-21 16:02:13 -08002432 }
2433
2434
Mathias Agopian3559b072012-08-15 13:46:03 -07002435 /*
2436 * Perform our own transaction if needed
2437 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002438
2439 if (mLayersAdded) {
2440 mLayersAdded = false;
2441 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002442 mVisibleRegionsDirty = true;
2443 }
2444
2445 // some layers might have been removed, so
2446 // we need to update the regions they're exposing.
2447 if (mLayersRemoved) {
2448 mLayersRemoved = false;
2449 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002450 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002451 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002452 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002453 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002454 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002455 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002456 }
Robert Carr2047fae2016-11-28 14:09:09 -08002457 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002458 }
2459
Vishnu Nairec0ab382019-02-13 15:32:56 -08002460 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002461 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002462}
2463
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002464void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002465 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002466 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002467 return;
2468 }
2469
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002470 if (mVisibleRegionsDirty || mInputInfoChanged) {
2471 mInputInfoChanged = false;
2472 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002473 } else if (mInputWindowCommands.syncInputWindows) {
2474 // If the caller requested to sync input windows, but there are no
2475 // changes to input windows, notify immediately.
2476 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002477 }
2478
Arthur Hung6cbb9752019-09-05 16:38:18 +08002479 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002480}
2481
2482void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002483 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002484
2485 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2486 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002487 // When calculating the screen bounds we ignore the transparent region since it may
2488 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002489 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002490 }
2491 });
chaviw291d88a2019-02-14 10:33:58 -08002492
2493 mInputFlinger->setInputWindows(inputHandles,
2494 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2495 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002496}
2497
Vishnu Nairec0ab382019-02-13 15:32:56 -08002498void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002499 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002500 mPendingInputWindowCommands.clear();
2501}
2502
Riley Andrews03414a12014-07-01 14:22:59 -07002503void SurfaceFlinger::updateCursorAsync()
2504{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002505 compositionengine::CompositionRefreshArgs refreshArgs;
2506 for (const auto& [_, display] : mDisplays) {
2507 if (display->getId()) {
2508 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002509 }
2510 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002511
2512 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002513}
2514
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002515void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2516 if (mScheduler) {
2517 // In practice it's not allowed to hotplug in/out the primary display once it's been
2518 // connected during startup, but some tests do it, so just warn and return.
2519 ALOGW("Can't re-init scheduler");
2520 return;
2521 }
2522
2523 int currentConfig = getHwComposer().getActiveConfigIndex(primaryDisplayId);
2524 mRefreshRateConfigs =
2525 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2526 getHwComposer().getConfigs(
2527 primaryDisplayId),
2528 currentConfig);
2529 mRefreshRateStats =
2530 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2531 currentConfig, HWC_POWER_MODE_OFF);
2532 mRefreshRateStats->setConfigMode(currentConfig);
2533
2534 // start the EventThread
2535 mScheduler =
2536 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
2537 *mRefreshRateConfigs);
2538 mAppConnectionHandle =
2539 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
2540 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2541 impl::EventThread::InterceptVSyncsCallback());
2542 mSfConnectionHandle =
2543 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
2544 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2545 [this](nsecs_t timestamp) {
2546 mInterceptor->saveVSyncEvent(timestamp);
2547 });
2548
2549 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2550 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
2551 mPhaseOffsets->getCurrentOffsets());
2552
2553 mRegionSamplingThread =
2554 new RegionSamplingThread(*this, *mScheduler,
2555 RegionSamplingThread::EnvironmentTimingTunables());
2556
2557 mScheduler->setChangeRefreshRateCallback(
2558 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
2559 Mutex::Autolock lock(mStateLock);
2560 setRefreshRateTo(type, event);
2561 });
2562}
2563
Mathias Agopian4fec8732012-06-29 14:12:52 -07002564void SurfaceFlinger::commitTransaction()
2565{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002566 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002567
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002568 mTransactionPending = false;
2569 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002570 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002571}
2572
Lloyd Pique58e24a32019-08-01 15:50:14 -07002573void SurfaceFlinger::commitTransactionLocked() {
2574 if (!mLayersPendingRemoval.isEmpty()) {
2575 // Notify removed layers now that they can't be drawn from
2576 for (const auto& l : mLayersPendingRemoval) {
2577 recordBufferingStats(l->getName().string(), l->getOccupancyHistory(true));
2578
2579 // Ensure any buffers set to display on any children are released.
2580 if (l->isRemovedFromCurrentState()) {
2581 l->latchAndReleaseBuffer();
2582 }
2583
2584 // If the layer has been removed and has no parent, then it will not be reachable
2585 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2586 // ensure we can copy its current to drawing state.
2587 if (!l->getParent()) {
2588 mOffscreenLayers.emplace(l.get());
2589 }
2590 }
2591 mLayersPendingRemoval.clear();
2592 }
2593
2594 // If this transaction is part of a window animation then the next frame
2595 // we composite should be considered an animation as well.
2596 mAnimCompositionPending = mAnimTransactionPending;
2597
2598 mDrawingState = mCurrentState;
2599 // clear the "changed" flags in current state
2600 mCurrentState.colorMatrixChanged = false;
2601
2602 mDrawingState.traverseInZOrder([&](Layer* layer) {
2603 layer->commitChildList();
2604
2605 // If the layer can be reached when traversing mDrawingState, then the layer is no
2606 // longer offscreen. Remove the layer from the offscreenLayer set.
2607 if (mOffscreenLayers.count(layer)) {
2608 mOffscreenLayers.erase(layer);
2609 }
2610 });
2611
2612 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002613 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002614}
2615
Nataniel Borges2b796da2019-02-15 13:32:18 -08002616void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2617 if (mTracingEnabledChanged) {
2618 mTracingEnabled = mTracing.isEnabled();
2619 mTracingEnabledChanged = false;
2620 }
2621
2622 // Synchronize with Tracing thread
2623 std::unique_lock<std::mutex> lock;
2624 if (mTracingEnabled) {
2625 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2626 }
2627
2628 lockedOperation();
2629
2630 // Synchronize with Tracing thread
2631 if (mTracingEnabled) {
2632 lock.unlock();
2633 }
2634}
2635
chaviw74d90ad2019-04-26 14:45:26 -07002636void SurfaceFlinger::commitOffscreenLayers() {
2637 for (Layer* offscreenLayer : mOffscreenLayers) {
2638 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2639 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2640 if (!trFlags) return;
2641
2642 layer->doTransaction(0);
2643 layer->commitChildList();
2644 });
2645 }
2646}
2647
Chia-I Wuab0c3192017-08-01 11:29:00 -07002648void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002649 for (const auto& [token, displayDevice] : mDisplays) {
2650 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002651 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002652 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002653 }
2654 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002655}
2656
Dan Stoza6b9454d2014-11-07 16:00:59 -08002657bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002658{
Ady Abraham09bd3922019-04-08 10:44:56 -07002659 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002660 ALOGV("handlePageFlip");
2661
Brian Andersond6927fb2016-07-23 23:37:30 -07002662 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663
Mathias Agopian4fec8732012-06-29 14:12:52 -07002664 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002665 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002666 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002667
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002668 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2669
Eric Penner51c59cd2014-07-28 19:51:58 -07002670 // Store the set of layers that need updates. This set must not change as
2671 // buffers are being latched, as this could result in a deadlock.
2672 // Example: Two producers share the same command stream and:
2673 // 1.) Layer 0 is latched
2674 // 2.) Layer 0 gets a new frame
2675 // 2.) Layer 1 gets a new frame
2676 // 3.) Layer 1 is latched.
2677 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2678 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002679 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002680 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002681 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002682 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002683 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002684 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002685 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002686 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002687 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002688 } else {
2689 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002690 }
Robert Carr2047fae2016-11-28 14:09:09 -08002691 });
2692
chaviw49a108c2019-08-12 11:23:06 -07002693 // The client can continue submitting buffers for offscreen layers, but they will not
2694 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2695 // layers to ensure dequeueBuffer doesn't block indefinitely.
2696 for (Layer* offscreenLayer : mOffscreenLayers) {
2697 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2698 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2699 }
2700
Lloyd Piquef2c79392018-12-20 16:23:33 -08002701 if (!mLayersWithQueuedFrames.empty()) {
2702 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2703 // writes to Layer current state. See also b/119481871
2704 Mutex::Autolock lock(mStateLock);
2705
2706 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002707 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002708 mLayersPendingRefresh.push_back(layer);
2709 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002710 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002711 if (layer->isBufferLatched()) {
2712 newDataLatched = true;
2713 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002714 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002715 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002716
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002717 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002718
2719 // If we will need to wake up at some time in the future to deal with a
2720 // queued frame that shouldn't be displayed during this vsync period, wake
2721 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002722 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002723 signalLayerUpdate();
2724 }
2725
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002726 // enter boot animation on first buffer latch
2727 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2728 ALOGI("Enter boot animation");
2729 mBootStage = BootStage::BOOTANIMATION;
2730 }
2731
chaviw74b03172019-08-19 11:09:03 -07002732 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2733
Dan Stoza6b9454d2014-11-07 16:00:59 -08002734 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002735 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002736}
2737
Mathias Agopianad456f92011-01-13 17:53:01 -08002738void SurfaceFlinger::invalidateHwcGeometry()
2739{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002740 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002741}
2742
Robert Carrc0df3122019-04-11 13:18:21 -07002743status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2744 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2745 const sp<IBinder>& parentHandle,
2746 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002747 // add this layer to the current state list
2748 {
2749 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002750 sp<Layer> parent;
2751 if (parentHandle != nullptr) {
2752 parent = fromHandle(parentHandle);
2753 if (parent == nullptr) {
2754 return NAME_NOT_FOUND;
2755 }
2756 } else {
2757 parent = parentLayer;
2758 }
2759
Robert Carr1f0a16a2016-10-24 16:27:39 -07002760 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002761 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002762 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002763 return NO_MEMORY;
2764 }
Robert Carrc0df3122019-04-11 13:18:21 -07002765
2766 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2767
Robert Carrb89ea9d2018-12-10 13:01:14 -08002768 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002769 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002770 } else if (parent == nullptr) {
2771 lbc->onRemovedFromCurrentState();
2772 } else if (parent->isRemovedFromCurrentState()) {
2773 parent->addChild(lbc);
2774 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002775 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002776 parent->addChild(lbc);
2777 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002778
Yiwei Zhang243b3782018-05-15 17:40:04 -07002779 if (gbc != nullptr) {
2780 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2781 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2782 mMaxGraphicBufferProducerListSize,
2783 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2784 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002785 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002786 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002787 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002788 }
2789
Mathias Agopian96f08192010-06-02 23:28:45 -07002790 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002791 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002792
Dan Stoza7d89d062015-04-30 13:29:25 -07002793 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002794}
2795
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002796uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002797 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002798}
2799
Mathias Agopian3f844832013-08-07 21:24:32 -07002800uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002801 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002802}
2803
Mathias Agopian3f844832013-08-07 21:24:32 -07002804uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002805 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002806}
2807
2808uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002809 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002810 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002811 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002812 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002813 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002814 }
2815 return old;
2816}
2817
Marissa Wall713b63f2018-10-17 15:42:43 -07002818bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002819 // to prevent onHandleDestroyed from being called while the lock is held,
2820 // we must keep a copy of the transactions (specifically the composer
2821 // states) around outside the scope of the lock
2822 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002823 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002824 {
2825 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002826
Valerie Haufce31b82019-04-30 16:41:14 -07002827 auto it = mTransactionQueues.begin();
2828 while (it != mTransactionQueues.end()) {
2829 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002830
Valerie Haufce31b82019-04-30 16:41:14 -07002831 while (!transactionQueue.empty()) {
2832 const auto& transaction = transactionQueue.front();
2833 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002834 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002835 transaction.states)) {
2836 setTransactionFlags(eTransactionFlushNeeded);
2837 break;
2838 }
2839 transactions.push_back(transaction);
2840 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2841 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002842 transaction.buffer, transaction.postTime,
2843 transaction.privileged, transaction.hasListenerCallbacks,
2844 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002845 transactionQueue.pop();
2846 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002847 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002848
Valerie Haufce31b82019-04-30 16:41:14 -07002849 if (transactionQueue.empty()) {
2850 it = mTransactionQueues.erase(it);
2851 mTransactionCV.broadcast();
2852 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002853 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002854 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002855 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002856 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002857 return flushedATransaction;
2858}
2859
2860bool SurfaceFlinger::transactionFlushNeeded() {
2861 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07002862}
2863
chaviwca27f252018-02-06 16:46:39 -08002864
Marissa Wall17b4e452018-12-26 16:32:34 -08002865bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002866 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08002867 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002868 if (!useCachedExpectedPresentTime)
2869 populateExpectedPresentTime();
2870
2871 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08002872 // Do not present if the desiredPresentTime has not passed unless it is more than one second
2873 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
2874 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
2875 desiredPresentTime < expectedPresentTime + s2ns(1)) {
2876 return false;
2877 }
2878
Marissa Wall713b63f2018-10-17 15:42:43 -07002879 for (const ComposerState& state : states) {
2880 const layer_state_t& s = state.state;
2881 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
2882 continue;
2883 }
2884 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08002885 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07002886 }
2887 }
Marissa Wall17b4e452018-12-26 16:32:34 -08002888 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002889}
2890
Valerie Hau9dab9732019-08-20 09:29:25 -07002891void SurfaceFlinger::setTransactionState(
2892 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2893 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
2894 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
2895 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002896 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08002897
Valerie Haubc6ddb12019-03-08 11:10:15 -08002898 const int64_t postTime = systemTime();
2899
Robert Carr14167e02019-02-13 13:50:55 -08002900 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
2901
Mathias Agopian698c0872011-06-28 19:09:31 -07002902 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07002903
Marissa Wall713b63f2018-10-17 15:42:43 -07002904 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07002905 auto itr = mTransactionQueues.find(applyToken);
2906 // if this is an animation frame, wait until prior animation frame has
2907 // been applied by SF
2908 if (flags & eAnimation) {
2909 while (itr != mTransactionQueues.end()) {
2910 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2911 if (CC_UNLIKELY(err != NO_ERROR)) {
2912 ALOGW_IF(err == TIMED_OUT,
2913 "setTransactionState timed out "
2914 "waiting for animation frame to apply");
2915 break;
2916 }
2917 itr = mTransactionQueues.find(applyToken);
2918 }
2919 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002920
2921 // Expected present time is computed and cached on invalidate, so it may be stale.
2922 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
2923 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08002924 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002925 uncacheBuffer, postTime, privileged,
2926 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002927 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002928 return;
2929 }
2930
Valerie Haubc6ddb12019-03-08 11:10:15 -08002931 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002932 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
2933 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07002934}
2935
Valerie Hau9dab9732019-08-20 09:29:25 -07002936void SurfaceFlinger::applyTransactionState(
2937 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2938 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
2939 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
2940 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
2941 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07002942 uint32_t transactionFlags = 0;
2943
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002944 if (flags & eAnimation) {
2945 // For window updates that are part of an animation we must wait for
2946 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07002947 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002948 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002949 if (CC_UNLIKELY(err != NO_ERROR)) {
2950 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002951 // caller after a few seconds.
2952 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2953 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002954 mAnimTransactionPending = false;
2955 break;
2956 }
2957 }
2958 }
2959
chaviwca27f252018-02-06 16:46:39 -08002960 for (const DisplayState& display : displays) {
2961 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002962 }
2963
Valerie Hau9dab9732019-08-20 09:29:25 -07002964 // start and end registration for listeners w/ no surface so they can get their callback. Note
2965 // that listeners with SurfaceControls will start registration during setClientStateLocked
2966 // below.
2967 for (const auto& listener : listenerCallbacks) {
2968 mTransactionCompletedThread.startRegistration(listener);
2969 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07002970 }
2971
Valerie Hau9dab9732019-08-20 09:29:25 -07002972 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07002973 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08002974 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07002975 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
2976 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07002977 }
2978
Valerie Hau9dab9732019-08-20 09:29:25 -07002979 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07002980 mTransactionCompletedThread.endRegistration(listenerCallback);
2981 }
2982
Marissa Walle2ffb422018-10-12 11:33:52 -07002983 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07002984 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07002985 mTransactionCompletedThread.sendCallbacks();
2986 }
2987 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08002988
chaviw273171b2018-12-26 11:46:30 -08002989 transactionFlags |= addInputWindowCommands(inputWindowCommands);
2990
Marissa Wall947d34e2019-03-29 14:03:53 -07002991 if (uncacheBuffer.isValid()) {
2992 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07002993 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07002994 }
2995
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002996 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2997 // anyway. This can be used as a flush mechanism for previous async transactions.
2998 // Empty animation transaction can be used to simulate back-pressure, so also force a
2999 // transaction for empty animation transactions.
3000 if (transactionFlags == 0 &&
3001 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003002 transactionFlags = eTransactionNeeded;
3003 }
3004
Marissa Wall06255332019-03-27 13:48:27 -07003005 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3006 // so we don't have to wake up again next frame to preform an uneeded traversal.
3007 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3008 transactionFlags = transactionFlags & (~eTraversalNeeded);
3009 mTraversalNeededMainThread = true;
3010 }
3011
Mathias Agopian386aa982011-11-07 21:58:03 -08003012 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003013 if (mInterceptor->isEnabled()) {
3014 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003015 }
Irvel468051e2016-06-13 16:44:44 -07003016
Mathias Agopian386aa982011-11-07 21:58:03 -08003017 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003018 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3019 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003020 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003021
3022 // if this is a synchronous transaction, wait for it to take effect
3023 // before returning.
3024 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003025 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003026 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003027 if (flags & eAnimation) {
3028 mAnimTransactionPending = true;
3029 }
chaviw4fe36852019-04-15 16:25:49 -07003030 if (mPendingInputWindowCommands.syncInputWindows) {
3031 mPendingSyncInputWindows = true;
3032 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003033
3034 // applyTransactionState can be called by either the main SF thread or by
3035 // another process through setTransactionState. While a given process may wish
3036 // to wait on synchronous transactions, the main SF thread should never
3037 // be blocked. Therefore, we only wait if isMainThread is false.
3038 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003039 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3040 if (CC_UNLIKELY(err != NO_ERROR)) {
3041 // just in case something goes wrong in SF, return to the
3042 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003043 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3044 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003045 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003046 break;
3047 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003048 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003049 }
3050}
3051
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003052uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3053 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3054 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003055
Mathias Agopiane57f2922012-08-09 16:29:12 -07003056 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003057 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3058
3059 const uint32_t what = s.what;
3060 if (what & DisplayState::eSurfaceChanged) {
3061 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3062 state.surface = s.surface;
3063 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003064 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003065 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003066 if (what & DisplayState::eLayerStackChanged) {
3067 if (state.layerStack != s.layerStack) {
3068 state.layerStack = s.layerStack;
3069 flags |= eDisplayTransactionNeeded;
3070 }
3071 }
3072 if (what & DisplayState::eDisplayProjectionChanged) {
3073 if (state.orientation != s.orientation) {
3074 state.orientation = s.orientation;
3075 flags |= eDisplayTransactionNeeded;
3076 }
3077 if (state.frame != s.frame) {
3078 state.frame = s.frame;
3079 flags |= eDisplayTransactionNeeded;
3080 }
3081 if (state.viewport != s.viewport) {
3082 state.viewport = s.viewport;
3083 flags |= eDisplayTransactionNeeded;
3084 }
3085 }
3086 if (what & DisplayState::eDisplaySizeChanged) {
3087 if (state.width != s.width) {
3088 state.width = s.width;
3089 flags |= eDisplayTransactionNeeded;
3090 }
3091 if (state.height != s.height) {
3092 state.height = s.height;
3093 flags |= eDisplayTransactionNeeded;
3094 }
3095 }
3096
Mathias Agopiane57f2922012-08-09 16:29:12 -07003097 return flags;
3098}
3099
Robert Carr14167e02019-02-13 13:50:55 -08003100bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003101 IPCThreadState* ipc = IPCThreadState::self();
3102 const int pid = ipc->getCallingPid();
3103 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003104 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003105 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003106 return false;
3107 }
3108 return true;
3109}
3110
Marissa Wall3dad52d2019-03-22 14:03:19 -07003111uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003112 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3113 bool privileged,
3114 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003115 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003116
Valerie Hau9dab9732019-08-20 09:29:25 -07003117 for (auto& listener : s.listeners) {
3118 // note that startRegistration will not re-register if the listener has
3119 // already be registered for a prior surface control
3120 mTransactionCompletedThread.startRegistration(listener);
3121 listenerCallbacks.insert(listener);
3122 }
3123
Vishnu Nairf03652d2019-07-16 17:56:56 -07003124 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003125 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003126 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003127 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003128 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003129 }
chaviw8b3871a2017-11-01 17:41:01 -07003130 return 0;
3131 }
3132
chaviw8b3871a2017-11-01 17:41:01 -07003133 uint32_t flags = 0;
3134
Garfield Tan8a3083e2018-12-03 13:21:07 -08003135 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003136
3137 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3138 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003139 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003140 layer->pushPendingState();
3141 }
3142
chaviw8b3871a2017-11-01 17:41:01 -07003143 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003144 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003145 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003146 }
chaviw8b3871a2017-11-01 17:41:01 -07003147 }
3148 if (what & layer_state_t::eLayerChanged) {
3149 // NOTE: index needs to be calculated before we update the state
3150 const auto& p = layer->getParent();
3151 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003152 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003153 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003154 mCurrentState.layersSortedByZ.removeAt(idx);
3155 mCurrentState.layersSortedByZ.add(layer);
3156 // we need traversal (state changed)
3157 // AND transaction (list changed)
3158 flags |= eTransactionNeeded|eTraversalNeeded;
3159 }
chaviw8b3871a2017-11-01 17:41:01 -07003160 } else {
3161 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003162 flags |= eTransactionNeeded|eTraversalNeeded;
3163 }
3164 }
chaviw8b3871a2017-11-01 17:41:01 -07003165 }
3166 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003167 // NOTE: index needs to be calculated before we update the state
3168 const auto& p = layer->getParent();
3169 if (p == nullptr) {
3170 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3171 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3172 mCurrentState.layersSortedByZ.removeAt(idx);
3173 mCurrentState.layersSortedByZ.add(layer);
3174 // we need traversal (state changed)
3175 // AND transaction (list changed)
3176 flags |= eTransactionNeeded|eTraversalNeeded;
3177 }
3178 } else {
3179 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3180 flags |= eTransactionNeeded|eTraversalNeeded;
3181 }
chaviw8b3871a2017-11-01 17:41:01 -07003182 }
3183 }
3184 if (what & layer_state_t::eSizeChanged) {
3185 if (layer->setSize(s.w, s.h)) {
3186 flags |= eTraversalNeeded;
3187 }
3188 }
3189 if (what & layer_state_t::eAlphaChanged) {
3190 if (layer->setAlpha(s.alpha))
3191 flags |= eTraversalNeeded;
3192 }
3193 if (what & layer_state_t::eColorChanged) {
3194 if (layer->setColor(s.color))
3195 flags |= eTraversalNeeded;
3196 }
Peiyong Lind3788632018-09-18 16:01:31 -07003197 if (what & layer_state_t::eColorTransformChanged) {
3198 if (layer->setColorTransform(s.colorTransform)) {
3199 flags |= eTraversalNeeded;
3200 }
3201 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003202 if (what & layer_state_t::eBackgroundColorChanged) {
3203 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3204 flags |= eTraversalNeeded;
3205 }
3206 }
chaviw8b3871a2017-11-01 17:41:01 -07003207 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003208 // TODO: b/109894387
3209 //
3210 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3211 // rotation. To see the problem observe that if we have a square parent, and a child
3212 // of the same size, then we rotate the child 45 degrees around it's center, the child
3213 // must now be cropped to a non rectangular 8 sided region.
3214 //
3215 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3216 // private API, and the WindowManager only uses rotation in one case, which is on a top
3217 // level layer in which cropping is not an issue.
3218 //
3219 // However given that abuse of rotation matrices could lead to surfaces extending outside
3220 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3221 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3222 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003223 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003224 flags |= eTraversalNeeded;
3225 }
3226 if (what & layer_state_t::eTransparentRegionChanged) {
3227 if (layer->setTransparentRegionHint(s.transparentRegion))
3228 flags |= eTraversalNeeded;
3229 }
3230 if (what & layer_state_t::eFlagsChanged) {
3231 if (layer->setFlags(s.flags, s.mask))
3232 flags |= eTraversalNeeded;
3233 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003234 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003235 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003236 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003237 if (what & layer_state_t::eCornerRadiusChanged) {
3238 if (layer->setCornerRadius(s.cornerRadius))
3239 flags |= eTraversalNeeded;
3240 }
chaviw8b3871a2017-11-01 17:41:01 -07003241 if (what & layer_state_t::eLayerStackChanged) {
3242 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3243 // We only allow setting layer stacks for top level layers,
3244 // everything else inherits layer stack from its parent.
3245 if (layer->hasParent()) {
3246 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3247 layer->getName().string());
3248 } else if (idx < 0) {
3249 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3250 "that also does not appear in the top level layer list. Something"
3251 " has gone wrong.", layer->getName().string());
3252 } else if (layer->setLayerStack(s.layerStack)) {
3253 mCurrentState.layersSortedByZ.removeAt(idx);
3254 mCurrentState.layersSortedByZ.add(layer);
3255 // we need traversal (state changed)
3256 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003257 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003258 }
3259 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003260 if (what & layer_state_t::eDeferTransaction_legacy) {
3261 if (s.barrierHandle_legacy != nullptr) {
3262 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3263 } else if (s.barrierGbp_legacy != nullptr) {
3264 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003265 if (authenticateSurfaceTextureLocked(gbp)) {
3266 const auto& otherLayer =
3267 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003268 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003269 } else {
3270 ALOGE("Attempt to defer transaction to to an"
3271 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003272 }
3273 }
chaviw8b3871a2017-11-01 17:41:01 -07003274 // We don't trigger a traversal here because if no other state is
3275 // changed, we don't want this to cause any more work
3276 }
chaviw8b3871a2017-11-01 17:41:01 -07003277 if (what & layer_state_t::eReparentChildren) {
3278 if (layer->reparentChildren(s.reparentHandle)) {
3279 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003280 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003281 }
chaviw8b3871a2017-11-01 17:41:01 -07003282 if (what & layer_state_t::eDetachChildren) {
3283 layer->detachChildren();
3284 }
3285 if (what & layer_state_t::eOverrideScalingModeChanged) {
3286 layer->setOverrideScalingMode(s.overrideScalingMode);
3287 // We don't trigger a traversal here because if no other state is
3288 // changed, we don't want this to cause any more work
3289 }
Marissa Wall61c58622018-07-18 10:12:20 -07003290 if (what & layer_state_t::eTransformChanged) {
3291 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3292 }
3293 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3294 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3295 flags |= eTraversalNeeded;
3296 }
3297 if (what & layer_state_t::eCropChanged) {
3298 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3299 }
Marissa Wall861616d2018-10-22 12:52:23 -07003300 if (what & layer_state_t::eFrameChanged) {
3301 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3302 }
Marissa Wall61c58622018-07-18 10:12:20 -07003303 if (what & layer_state_t::eAcquireFenceChanged) {
3304 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3305 }
3306 if (what & layer_state_t::eDataspaceChanged) {
3307 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3308 }
3309 if (what & layer_state_t::eHdrMetadataChanged) {
3310 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3311 }
3312 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3313 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3314 }
3315 if (what & layer_state_t::eApiChanged) {
3316 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3317 }
3318 if (what & layer_state_t::eSidebandStreamChanged) {
3319 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3320 }
Robert Carr720e5062018-07-30 17:45:14 -07003321 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003322 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003323 layer->setInputInfo(s.inputInfo);
3324 flags |= eTraversalNeeded;
3325 } else {
3326 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3327 }
Robert Carr720e5062018-07-30 17:45:14 -07003328 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003329 if (what & layer_state_t::eMetadataChanged) {
3330 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3331 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003332 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3333 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3334 flags |= eTraversalNeeded;
3335 }
3336 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003337 // This has to happen after we reparent children because when we reparent to null we remove
3338 // child layers from current state and remove its relative z. If the children are reparented in
3339 // the same transaction, then we have to make sure we reparent the children first so we do not
3340 // lose its relative z order.
3341 if (what & layer_state_t::eReparent) {
3342 bool hadParent = layer->hasParent();
3343 if (layer->reparent(s.parentHandleForChild)) {
3344 if (!hadParent) {
3345 mCurrentState.layersSortedByZ.remove(layer);
3346 }
3347 flags |= eTransactionNeeded | eTraversalNeeded;
3348 }
3349 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003350 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003351 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3352 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003353 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3354 }
3355 }
Marissa Wall78b72202019-03-15 14:58:34 -07003356 bool bufferChanged = what & layer_state_t::eBufferChanged;
3357 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3358 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003359 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003360 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003361 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3362 if (success) {
3363 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3364 success = ClientCache::getInstance()
3365 .registerErasedRecipient(s.cachedBuffer,
3366 wp<ClientCache::ErasedRecipient>(this));
3367 if (!success) {
3368 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3369 }
3370 }
Marissa Wall78b72202019-03-15 14:58:34 -07003371 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003372 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003373 } else if (bufferChanged) {
3374 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003375 }
Marissa Wall78b72202019-03-15 14:58:34 -07003376 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003377 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003378 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003379 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003380 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003381 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3382 // Do not put anything that updates layer state or modifies flags after
3383 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003384 return flags;
3385}
3386
chaviw273171b2018-12-26 11:46:30 -08003387uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3388 uint32_t flags = 0;
3389 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3390 flags |= eTraversalNeeded;
3391 }
3392
chaviwa911b102019-02-14 10:18:33 -08003393 if (inputWindowCommands.syncInputWindows) {
3394 flags |= eTraversalNeeded;
3395 }
3396
Vishnu Nairec0ab382019-02-13 15:32:56 -08003397 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003398 return flags;
3399}
3400
chaviwfe94a222019-08-21 13:52:59 -07003401status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3402 sp<IBinder>* outHandle) {
3403 if (!mirrorFromHandle) {
3404 return NAME_NOT_FOUND;
3405 }
3406
3407 sp<Layer> mirrorLayer;
3408 sp<Layer> mirrorFrom;
3409 String8 uniqueName = getUniqueLayerName(String8("MirrorRoot"));
3410
3411 {
3412 Mutex::Autolock _l(mStateLock);
3413 mirrorFrom = fromHandle(mirrorFromHandle);
3414 if (!mirrorFrom) {
3415 return NAME_NOT_FOUND;
3416 }
3417
3418 status_t result = createContainerLayer(client, uniqueName, -1, -1, 0, LayerMetadata(),
3419 outHandle, &mirrorLayer);
3420 if (result != NO_ERROR) {
3421 return result;
3422 }
3423
3424 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3425 }
3426
3427 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3428}
3429
Marissa Wall2d814fb2019-04-09 18:52:57 +00003430status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3431 uint32_t h, PixelFormat format, uint32_t flags,
3432 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003433 sp<IGraphicBufferProducer>* gbp,
3434 const sp<IBinder>& parentHandle,
3435 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003436 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003437 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003438 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003439 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003440 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003441
Robert Carrc0df3122019-04-11 13:18:21 -07003442 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3443 "Expected only one of parentLayer or parentHandle to be non-null. "
3444 "Programmer error?");
3445
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003446 status_t result = NO_ERROR;
3447
3448 sp<Layer> layer;
3449
Cody Northropbc755282017-03-31 12:00:08 -06003450 String8 uniqueName = getUniqueLayerName(name);
3451
Evan Roskya1f1e152019-01-24 16:17:46 -08003452 bool primaryDisplayOnly = false;
3453
3454 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3455 // TODO b/64227542
3456 if (metadata.has(METADATA_WINDOW_TYPE)) {
3457 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3458 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003459 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003460 primaryDisplayOnly = true;
3461 }
3462 }
3463
Mathias Agopian3165cc22012-08-08 19:42:09 -07003464 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003465 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08003466 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
3467 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003468
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003469 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003470 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08003471 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
3472 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003473 break;
chaviw13fdc492017-06-27 12:40:18 -07003474 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003475 // check if buffer size is set for color layer.
3476 if (w > 0 || h > 0) {
3477 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3478 int(w), int(h));
3479 return BAD_VALUE;
3480 }
3481
Evan Roskya1f1e152019-01-24 16:17:46 -08003482 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
3483 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003484 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003485 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003486 // check if buffer size is set for container layer.
3487 if (w > 0 || h > 0) {
3488 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3489 int(w), int(h));
3490 return BAD_VALUE;
3491 }
Evan Roskya1f1e152019-01-24 16:17:46 -08003492 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
3493 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003494 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003495 default:
3496 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003497 break;
3498 }
3499
Dan Stoza7d89d062015-04-30 13:29:25 -07003500 if (result != NO_ERROR) {
3501 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003502 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003503
Evan Roskya1f1e152019-01-24 16:17:46 -08003504 if (primaryDisplayOnly) {
3505 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003506 }
3507
Robert Carrb89ea9d2018-12-10 13:01:14 -08003508 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003509 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3510 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003511 if (result != NO_ERROR) {
3512 return result;
3513 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003514 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003515
3516 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003517 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003518}
3519
Cody Northropbc755282017-03-31 12:00:08 -06003520String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3521{
3522 bool matchFound = true;
3523 uint32_t dupeCounter = 0;
3524
3525 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3526 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3527
Dan Stoza436ccf32018-06-21 12:10:12 -07003528 // Grab the state lock since we're accessing mCurrentState
3529 Mutex::Autolock lock(mStateLock);
3530
Cody Northropbc755282017-03-31 12:00:08 -06003531 // Loop over layers until we're sure there is no matching name
3532 while (matchFound) {
3533 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003534 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003535 if (layer->getName() == uniqueName) {
3536 matchFound = true;
3537 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3538 }
3539 });
3540 }
3541
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003542 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3543 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003544
3545 return uniqueName;
3546}
3547
Marissa Wallfd668622018-05-10 10:21:13 -07003548status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3549 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003550 LayerMetadata metadata, PixelFormat& format,
3551 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003552 sp<IGraphicBufferProducer>* gbp,
3553 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003554 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003555 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003556 case PIXEL_FORMAT_TRANSPARENT:
3557 case PIXEL_FORMAT_TRANSLUCENT:
3558 format = PIXEL_FORMAT_RGBA_8888;
3559 break;
3560 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003561 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003562 break;
3563 }
3564
chaviwb4c6e582019-08-16 14:35:07 -07003565 sp<BufferQueueLayer> layer;
3566 LayerCreationArgs args =
3567 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata));
3568 args.textureName = getNewTexture();
3569 {
3570 // Grab the SF state lock during this since it's the only safe way to access
3571 // RenderEngine when creating a BufferLayerConsumer
3572 // TODO: Check if this lock is still needed here
3573 Mutex::Autolock lock(mStateLock);
3574 layer = getFactory().createBufferQueueLayer(args);
3575 }
3576
Marissa Wallfd668622018-05-10 10:21:13 -07003577 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003578 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003579 *handle = layer->getHandle();
3580 *gbp = layer->getProducer();
3581 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003582 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003583
Marissa Wallfd668622018-05-10 10:21:13 -07003584 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003585 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003586}
3587
Marissa Wall61c58622018-07-18 10:12:20 -07003588status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3589 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003590 LayerMetadata metadata, sp<IBinder>* handle,
3591 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07003592 LayerCreationArgs args =
3593 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata));
3594 args.displayDevice = getDefaultDisplayDevice();
3595 args.textureName = getNewTexture();
3596 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07003597 *handle = layer->getHandle();
3598 *outLayer = layer;
3599
3600 return NO_ERROR;
3601}
3602
Evan Roskya1f1e152019-01-24 16:17:46 -08003603status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
3604 uint32_t h, uint32_t flags, LayerMetadata metadata,
3605 sp<IBinder>* handle, sp<Layer>* outLayer) {
3606 *outLayer = getFactory().createColorLayer(
3607 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003608 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003609 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003610}
3611
Evan Roskya1f1e152019-01-24 16:17:46 -08003612status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
3613 uint32_t w, uint32_t h, uint32_t flags,
3614 LayerMetadata metadata, sp<IBinder>* handle,
3615 sp<Layer>* outLayer) {
3616 *outLayer = getFactory().createContainerLayer(
3617 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003618 *handle = (*outLayer)->getHandle();
3619 return NO_ERROR;
3620}
3621
3622
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003623void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003624 mLayersPendingRemoval.add(layer);
3625 mLayersRemoved = true;
3626 setTransactionFlags(eTransactionNeeded);
3627}
3628
Robert Carr695d5282018-12-18 15:27:58 -08003629void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003630{
Robert Carr2e102c92018-10-23 12:11:15 -07003631 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003632 // If a layer has a parent, we allow it to out-live it's handle
3633 // with the idea that the parent holds a reference and will eventually
3634 // be cleaned up. However no one cleans up the top-level so we do so
3635 // here.
3636 if (layer->getParent() == nullptr) {
3637 mCurrentState.layersSortedByZ.remove(layer);
3638 }
3639 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003640
3641 auto it = mLayersByLocalBinderToken.begin();
3642 while (it != mLayersByLocalBinderToken.end()) {
3643 if (it->second == layer) {
3644 it = mLayersByLocalBinderToken.erase(it);
3645 } else {
3646 it++;
3647 }
3648 }
3649
Robert Carr695d5282018-12-18 15:27:58 -08003650 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003651}
3652
Mathias Agopianb60314a2012-04-10 22:09:54 -07003653// ---------------------------------------------------------------------------
3654
Andy McFadden13a082e2012-08-24 10:16:42 -07003655void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003656 const auto display = getDefaultDisplayDeviceLocked();
3657 if (!display) return;
3658
3659 const sp<IBinder> token = display->getDisplayToken().promote();
3660 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003661
Jesse Hall01e29052013-02-19 16:13:35 -08003662 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003663 Vector<ComposerState> state;
3664 Vector<DisplayState> displays;
3665 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003666 d.what = DisplayState::eDisplayProjectionChanged |
3667 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003668 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003669 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003670 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003671 d.frame.makeInvalid();
3672 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003673 d.width = 0;
3674 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003675 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003676 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3677 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003678
Dominik Laskowskie9774092018-12-11 10:04:24 -08003679 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003680
Dominik Laskowski83b88212018-12-11 13:34:06 -08003681 const nsecs_t vsyncPeriod = getVsyncPeriod();
3682 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003683
Brian Andersond0010582017-03-07 13:20:31 -08003684 // Use phase of 0 since phase is not known.
3685 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003686 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003687 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003688}
3689
3690void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003691 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003692 postMessageAsync(
3693 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003694}
3695
Ady Abraham27c70212019-06-11 10:52:26 -07003696void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3697 if (mHWCVsyncState != enabled) {
3698 getHwComposer().setVsyncEnabled(displayId, enabled);
3699 mHWCVsyncState = enabled;
3700 }
3701}
3702
Dominik Laskowskie9774092018-12-11 10:04:24 -08003703void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003704 if (display->isVirtual()) {
3705 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003706 return;
3707 }
3708
Dominik Laskowski075d3172018-05-24 15:50:06 -07003709 const auto displayId = display->getId();
3710 LOG_ALWAYS_FATAL_IF(!displayId);
3711
Dominik Laskowski34157762018-10-31 13:07:19 -07003712 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003713
3714 int currentMode = display->getPowerMode();
3715 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003716 return;
3717 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003718
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003719 display->setPowerMode(mode);
3720
Lloyd Pique4dccc412018-01-22 17:21:36 -08003721 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003722 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003723 }
3724
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003725 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003726 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003727 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003728 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003729 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003730 mScheduler->onScreenAcquired(mAppConnectionHandle);
3731 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003732 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003733
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003734 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003735 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003736 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003737
3738 struct sched_param param = {0};
3739 param.sched_priority = 1;
3740 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3741 ALOGW("Couldn't set SCHED_FIFO on display on");
3742 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003743 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003744 // Turn off the display
3745 struct sched_param param = {0};
3746 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3747 ALOGW("Couldn't set SCHED_OTHER on display off");
3748 }
3749
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003750 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003751 mScheduler->disableHardwareVsync(true);
3752 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003753 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003754
Ady Abraham27c70212019-06-11 10:52:26 -07003755 // Make sure HWVsync is disabled before turning off the display
3756 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3757
Dominik Laskowski075d3172018-05-24 15:50:06 -07003758 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003759 mVisibleRegionsDirty = true;
3760 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003761 } else if (mode == HWC_POWER_MODE_DOZE ||
3762 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003763 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003764 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003765 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003766 mScheduler->onScreenAcquired(mAppConnectionHandle);
3767 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003768 }
3769 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3770 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003771 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003772 mScheduler->disableHardwareVsync(true);
3773 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003774 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003775 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003776 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003777 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003778 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003779 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003780
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003781 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003782 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003783 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003784 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003785 }
3786
Dominik Laskowski34157762018-10-31 13:07:19 -07003787 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003788}
3789
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003790void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003791 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003792 const auto display = getDisplayDevice(displayToken);
3793 if (!display) {
3794 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3795 displayToken.get());
3796 } else if (display->isVirtual()) {
3797 ALOGW("Attempt to set power mode %d for virtual display", mode);
3798 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003799 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003800 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003801 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003802}
3803
3804// ---------------------------------------------------------------------------
3805
Dominik Laskowskic2867142019-01-21 11:33:38 -08003806status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3807 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003808 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003809
Mathias Agopianbd115332013-04-18 16:41:04 -07003810 IPCThreadState* ipc = IPCThreadState::self();
3811 const int pid = ipc->getCallingPid();
3812 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003813
Mathias Agopianbd115332013-04-18 16:41:04 -07003814 if ((uid != AID_SHELL) &&
3815 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003816 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3817 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003818 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003819 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003820 // (this would indicate SF is stuck, but we want to be able to
3821 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003822 status_t err = mStateLock.timedLock(s2ns(1));
3823 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003824 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003825 StringAppendF(&result,
3826 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3827 "(no locks held)\n",
3828 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003829 }
3830
Dominik Laskowskic2867142019-01-21 11:33:38 -08003831 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07003832
Dominik Laskowskic2867142019-01-21 11:33:38 -08003833 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003834 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003835 {"--dispsync"s,
3836 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003837 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003838 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3839 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3840 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3841 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3842 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3843 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003844 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003845 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3846 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003847
Dominik Laskowskic2867142019-01-21 11:33:38 -08003848 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003849
Dominik Laskowski46470112019-08-02 13:13:11 -07003850 const auto it = dumpers.find(flag);
3851 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003852 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07003853 } else if (!asProto) {
3854 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003855 }
3856
Mathias Agopian9795c422009-08-26 16:36:26 -07003857 if (locked) {
3858 mStateLock.unlock();
3859 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003860
Dominik Laskowski46470112019-08-02 13:13:11 -07003861 if (it == dumpers.end()) {
3862 const LayersProto layersProto = dumpProtoFromMainThread();
3863 if (asProto) {
3864 result.append(layersProto.SerializeAsString());
3865 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07003866 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07003867 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3868 result.append(LayerProtoParser::layerTreeToString(layerTree));
3869 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07003870 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07003871 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003872 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003873 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08003874 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003875 return NO_ERROR;
3876}
3877
Nataniel Borges8e7dc722019-02-28 15:10:28 -08003878status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
3879 if (asProto && mTracing.isEnabled()) {
3880 mTracing.writeToFileAsync();
3881 }
3882
3883 return doDump(fd, DumpArgs(), asProto);
3884}
3885
Dominik Laskowskic2867142019-01-21 11:33:38 -08003886void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003887 mCurrentState.traverseInZOrder(
3888 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003889}
3890
Dominik Laskowskic2867142019-01-21 11:33:38 -08003891void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003892 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003893
Dominik Laskowskic2867142019-01-21 11:33:38 -08003894 if (args.size() > 1) {
3895 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08003896 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003897 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003898 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003899 }
Robert Carr2047fae2016-11-28 14:09:09 -08003900 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08003901 } else {
3902 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003903 }
3904}
3905
Dominik Laskowskic2867142019-01-21 11:33:38 -08003906void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08003907 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003908 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003909 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003910 }
Robert Carr2047fae2016-11-28 14:09:09 -08003911 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003912
Svetoslavd85084b2014-03-20 10:28:31 -07003913 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003914}
3915
Dominik Laskowskic2867142019-01-21 11:33:38 -08003916void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
3917 mTimeStats->parseArgs(asProto, args, result);
3918}
3919
Jamie Gennis6547ff42013-07-16 20:12:42 -07003920// This should only be called from the main thread. Otherwise it would need
3921// the lock and should use mCurrentState rather than mDrawingState.
3922void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003923 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003924 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003925 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003926
3927 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3928}
3929
Yiwei Zhang5434a782018-12-05 18:06:32 -08003930void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003931 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003932
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003933 if (isLayerTripleBufferingDisabled())
3934 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003935
Yiwei Zhang5434a782018-12-05 18:06:32 -08003936 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
3937 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
3938 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
3939 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
3940 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3941 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003942 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003943}
3944
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003945void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07003946 mScheduler->dump(result);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003947 StringAppendF(&result, "+ Refresh rate switching: %s\n",
3948 mRefreshRateConfigs->refreshRateSwitchingSupported() ? "on" : "off");
Dominik Laskowski98041832019-08-01 18:35:59 -07003949 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
3950
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003951 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07003952 result.append("\n");
3953
Ana Krulec757f63a2019-01-25 10:46:18 -08003954 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003955 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07003956 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08003957 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003958
Ady Abraham42b3beb2019-07-09 18:09:52 -07003959 StringAppendF(&result, "Allowed Display Configs: ");
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003960 for (int32_t configId : mAllowedDisplayConfigs) {
3961 StringAppendF(&result, "%" PRIu32 " Hz, ",
3962 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07003963 }
3964 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
3965 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07003966
Ana Krulecc2870422019-01-29 19:00:58 -08003967 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003968}
3969
Yiwei Zhang5434a782018-12-05 18:06:32 -08003970void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
3971 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003972 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3973 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003974 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003975 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003976 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003977 }
David Sodman4a36e932017-11-07 14:29:47 -08003978 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003979 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003980 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003981 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
3982 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003983}
3984
Dan Stozae77c7662016-05-13 11:37:28 -07003985void SurfaceFlinger::recordBufferingStats(const char* layerName,
3986 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003987 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3988 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003989 for (const auto& segment : history) {
3990 if (!segment.usedThirdBuffer) {
3991 stats.twoBufferTime += segment.totalTime;
3992 }
3993 if (segment.occupancyAverage < 1.0f) {
3994 stats.doubleBufferedTime += segment.totalTime;
3995 } else if (segment.occupancyAverage < 2.0f) {
3996 stats.tripleBufferedTime += segment.totalTime;
3997 }
3998 ++stats.numSegments;
3999 stats.totalTime += segment.totalTime;
4000 }
4001}
4002
Yiwei Zhang5434a782018-12-05 18:06:32 -08004003void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4004 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004005
4006 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4007 const size_t count = currentLayers.size();
4008 for (size_t i=0 ; i<count ; i++) {
4009 currentLayers[i]->dumpFrameEvents(result);
4010 }
4011}
4012
Yiwei Zhang5434a782018-12-05 18:06:32 -08004013void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004014 result.append("Buffering stats:\n");
4015 result.append(" [Layer name] <Active time> <Two buffer> "
4016 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004017 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004018 typedef std::tuple<std::string, float, float, float> BufferTuple;
4019 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004020 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004021 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004022 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004023 if (stats.numSegments == 0) {
4024 continue;
4025 }
4026 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4027 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4028 stats.totalTime;
4029 float doubleBufferRatio = static_cast<float>(
4030 stats.doubleBufferedTime) / stats.totalTime;
4031 float tripleBufferRatio = static_cast<float>(
4032 stats.tripleBufferedTime) / stats.totalTime;
4033 sorted.insert({activeTime, {name, twoBufferRatio,
4034 doubleBufferRatio, tripleBufferRatio}});
4035 }
4036 for (const auto& sortedPair : sorted) {
4037 float activeTime = sortedPair.first;
4038 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004039 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4040 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004041 }
4042 result.append("\n");
4043}
4044
Yiwei Zhang5434a782018-12-05 18:06:32 -08004045void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004046 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004047 const auto displayId = display->getId();
4048 if (!displayId) {
4049 continue;
4050 }
4051 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004052 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004053 continue;
4054 }
4055
Yiwei Zhang5434a782018-12-05 18:06:32 -08004056 StringAppendF(&result,
4057 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4058 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004059 uint8_t port;
4060 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004061 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004062 result.append("no identification data\n");
4063 continue;
4064 }
4065
4066 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004067 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004068 continue;
4069 }
4070
4071 const auto edid = parseEdid(data);
4072 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004073 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004074 continue;
4075 }
4076
Yiwei Zhang5434a782018-12-05 18:06:32 -08004077 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004078 result.append(edid->displayName.data(), edid->displayName.length());
4079 result.append("\"\n");
4080 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004081}
4082
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004083void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4084 std::string& result) const {
4085 hwc2_display_t hwcDisplayId;
4086 uint8_t port;
4087 DisplayIdentificationData data;
4088
4089 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4090 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4091 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4092 }
4093}
4094
Yiwei Zhang5434a782018-12-05 18:06:32 -08004095void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004096 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004097 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4098 StringAppendF(&result, "DisplayColorSetting: %s\n",
4099 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004100
4101 // TODO: print out if wide-color mode is active or not
4102
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004103 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004104 const auto displayId = display->getId();
4105 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004106 continue;
4107 }
4108
Yiwei Zhang5434a782018-12-05 18:06:32 -08004109 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004110 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004111 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004112 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004113 }
4114
Lloyd Pique32cbe282018-10-19 13:09:22 -07004115 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004116 StringAppendF(&result, " Current color mode: %s (%d)\n",
4117 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004118 }
4119 result.append("\n");
4120}
4121
Vishnu Nair8406fd72019-07-30 11:29:31 -07004122LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004123 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004124 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004125 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004126 layer->writeToProtoDrawingState(layerProto, traceFlags);
4127 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004128 });
4129
4130 return layersProto;
4131}
4132
Vishnu Nair0f085c62019-08-30 08:49:12 -07004133void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4134 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4135 // it.
4136 LayerProto* rootProto = layersProto.add_layers();
4137 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4138 rootProto->set_id(offscreenRootLayerId);
4139 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004140 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004141
4142 for (Layer* offscreenLayer : mOffscreenLayers) {
4143 // Add layer as child of the fake root
4144 rootProto->add_children(offscreenLayer->sequence);
4145
4146 // Add layer
4147 LayerProto* layerProto = layersProto.add_layers();
4148 offscreenLayer->writeToProtoDrawingState(layerProto, traceFlags);
4149 offscreenLayer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing,
4150 traceFlags);
4151 layerProto->set_parent(offscreenRootLayerId);
4152
4153 // Add children
4154 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4155 if (layer == offscreenLayer) {
4156 return;
4157 }
4158 LayerProto* childProto = layersProto.add_layers();
4159 layer->writeToProtoDrawingState(childProto, traceFlags);
4160 layer->writeToProtoCommonState(childProto, LayerVector::StateSet::Drawing, traceFlags);
4161 });
4162 }
4163}
4164
Vishnu Nair8406fd72019-07-30 11:29:31 -07004165LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4166 LayersProto layersProto;
4167 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4168 return layersProto;
4169}
4170
Vishnu Nair0f085c62019-08-30 08:49:12 -07004171void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4172 result.append("Offscreen Layers:\n");
4173 postMessageSync(new LambdaMessage([&]() {
4174 for (Layer* offscreenLayer : mOffscreenLayers) {
4175 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4176 layer->dumpCallingUidPid(result);
4177 });
4178 }
4179 }));
4180}
4181
Dominik Laskowskic2867142019-01-21 11:33:38 -08004182void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4183 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004184 Colorizer colorizer(colorize);
4185
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004186 // figure out if we're stuck somewhere
4187 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004188 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004189 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4190
4191 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004192 * Dump library configuration.
4193 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004194
4195 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004196 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004197 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004198 appendSfConfigString(result);
4199 appendUiConfigString(result);
4200 appendGuiConfigString(result);
4201 result.append("\n");
4202
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004203 result.append("\nDisplay identification data:\n");
4204 dumpDisplayIdentificationData(result);
4205
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004206 result.append("\nWide-Color information:\n");
4207 dumpWideColorInfo(result);
4208
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004209 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004210 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004211 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004212 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004213 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004214
Andy McFadden41d67d72014-04-25 16:58:34 -07004215 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004216 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004217 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004218 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004219 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004220
Dan Stozab90cf072015-03-05 11:05:59 -08004221 dumpStaticScreenStats(result);
4222 result.append("\n");
4223
Alec Mouri40189b02019-03-05 15:07:54 -08004224 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4225 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4226 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004227
Dan Stozae77c7662016-05-13 11:37:28 -07004228 dumpBufferingStats(result);
4229
Andy McFadden4803b742012-09-24 19:07:20 -07004230 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004231 * Dump the visible layer list
4232 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004233 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004234 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004235 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4236 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004237 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004238
Chia-I Wu2f884132018-09-13 15:17:58 -07004239 {
Lloyd Pique207def92019-02-28 16:09:52 -08004240 StringAppendF(&result, "Composition layers\n");
4241 mDrawingState.traverseInZOrder([&](Layer* layer) {
4242 auto compositionLayer = layer->getCompositionLayer();
4243 if (compositionLayer) compositionLayer->dump(result);
4244 });
4245 }
4246
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004247 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004248 * Dump Display state
4249 */
4250
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004251 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004252 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004253 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004254 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004255 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004256 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004257 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004258
4259 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004260 * Dump CompositionEngine state
4261 */
4262
4263 mCompositionEngine->dump(result);
4264
4265 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004266 * Dump SurfaceFlinger global state
4267 */
4268
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004269 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004270 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004271 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004272
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004273 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004274
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004275 DebugEGLImageTracker::getInstance()->dump(result);
4276
Dominik Laskowski075d3172018-05-24 15:50:06 -07004277 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004278 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4279 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004280 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4281 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004282 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004283 StringAppendF(&result,
4284 " transaction-flags : %08x\n"
4285 " gpu_to_cpu_unsupported : %d\n",
4286 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004287
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004288 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004289 displayId && getHwComposer().isConnected(*displayId)) {
4290 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004291 StringAppendF(&result,
4292 " refresh-rate : %f fps\n"
4293 " x-dpi : %f\n"
4294 " y-dpi : %f\n",
4295 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4296 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004297 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004298
Yiwei Zhang5434a782018-12-05 18:06:32 -08004299 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004300
Dan Stozae22aec72016-08-01 13:20:59 -07004301 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004302 * Tracing state
4303 */
4304 mTracing.dump(result);
4305 result.append("\n");
4306
4307 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004308 * HWC layer minidump
4309 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004310 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004311 const auto displayId = display->getId();
4312 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004313 continue;
4314 }
4315
Yiwei Zhang5434a782018-12-05 18:06:32 -08004316 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004317 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004318 const sp<DisplayDevice> displayDevice = display;
4319 mCurrentState.traverseInZOrder(
4320 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004321 result.append("\n");
4322 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004323
4324 /*
4325 * Dump HWComposer state
4326 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004327 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004328 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004329 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004330 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004331 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004332 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004333
4334 /*
4335 * Dump gralloc state
4336 */
4337 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4338 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004339
4340 /*
4341 * Dump VrFlinger state if in use.
4342 */
4343 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4344 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004345 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004346 result.append("\n");
4347 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004348
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004349 result.append(mTimeStats->miniDump());
4350 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004351}
4352
Chia-I Wu28f320b2018-05-03 11:02:56 -07004353void SurfaceFlinger::updateColorMatrixLocked() {
4354 mat4 colorMatrix;
4355 if (mGlobalSaturationFactor != 1.0f) {
4356 // Rec.709 luma coefficients
4357 float3 luminance{0.213f, 0.715f, 0.072f};
4358 luminance *= 1.0f - mGlobalSaturationFactor;
4359 mat4 saturationMatrix = mat4(
4360 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4361 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4362 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4363 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4364 );
4365 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4366 } else {
4367 colorMatrix = mClientColorMatrix * mDaltonizer();
4368 }
4369
4370 if (mCurrentState.colorMatrix != colorMatrix) {
4371 mCurrentState.colorMatrix = colorMatrix;
4372 mCurrentState.colorMatrixChanged = true;
4373 setTransactionFlags(eTransactionNeeded);
4374 }
4375}
4376
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004377status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004378#pragma clang diagnostic push
4379#pragma clang diagnostic error "-Wswitch-enum"
4380 switch (static_cast<ISurfaceComposerTag>(code)) {
4381 // These methods should at minimum make sure that the client requested
4382 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004383 case BOOT_FINISHED:
4384 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004385 case CREATE_DISPLAY:
4386 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004387 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004388 case GET_ANIMATION_FRAME_STATS:
4389 case GET_HDR_CAPABILITIES:
4390 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004391 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004392 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004393 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004394 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004395 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004396 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004397 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004398 case GET_DISPLAYED_CONTENT_SAMPLE:
4399 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004400 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4401 IPCThreadState* ipc = IPCThreadState::self();
4402 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4403 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004404 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004405 }
Robert Carr1db73f62016-12-21 12:58:51 -08004406 return OK;
4407 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004408 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004409 IPCThreadState* ipc = IPCThreadState::self();
4410 const int pid = ipc->getCallingPid();
4411 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004412 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4413 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004414 return PERMISSION_DENIED;
4415 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004416 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004417 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004418 // Used by apps to hook Choreographer to SurfaceFlinger.
4419 case CREATE_DISPLAY_EVENT_CONNECTION:
4420 // The following calls are currently used by clients that do not
4421 // request necessary permissions. However, they do not expose any secret
4422 // information, so it is OK to pass them.
4423 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004424 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004425 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004426 case GET_PHYSICAL_DISPLAY_IDS:
4427 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004428 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004429 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004430 case GET_DISPLAY_CONFIGS:
4431 case GET_DISPLAY_STATS:
4432 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4433 // Calling setTransactionState is safe, because you need to have been
4434 // granted a reference to Client* and Handle* to do anything with it.
4435 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004436 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004437 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004438 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004439 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004440 case IS_WIDE_COLOR_DISPLAY:
4441 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4442 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004443 return OK;
4444 }
Chong Zhangda6c1592019-07-16 13:45:06 -07004445 case CAPTURE_LAYERS: {
4446 IPCThreadState* ipc = IPCThreadState::self();
4447 const int pid = ipc->getCallingPid();
4448 const int uid = ipc->getCallingUid();
4449 // allow media to capture layer for video thumbnails
4450 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
4451 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4452 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
4453 return PERMISSION_DENIED;
4454 }
4455 return OK;
4456 }
Dan Stoza84ab9372018-12-17 15:27:57 -08004457 case CAPTURE_SCREEN:
4458 case ADD_REGION_SAMPLING_LISTENER:
4459 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004460 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004461 IPCThreadState* ipc = IPCThreadState::self();
4462 const int pid = ipc->getCallingPid();
4463 const int uid = ipc->getCallingUid();
4464 if ((uid != AID_GRAPHICS) &&
4465 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4466 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4467 return PERMISSION_DENIED;
4468 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004469 return OK;
4470 }
4471 // The following codes are deprecated and should never be allowed to access SF.
4472 case CONNECT_DISPLAY_UNUSED:
4473 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4474 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4475 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004476 }
chaviw93df2ea2019-04-30 16:45:12 -07004477 case CAPTURE_SCREEN_BY_ID: {
4478 IPCThreadState* ipc = IPCThreadState::self();
4479 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004480 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004481 return OK;
4482 }
4483 return PERMISSION_DENIED;
4484 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004485 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004486
4487 // These codes are used for the IBinder protocol to either interrogate the recipient
4488 // side of the transaction for its canonical interface descriptor or to dump its state.
4489 // We let them pass by default.
4490 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4491 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4492 code == IBinder::SYSPROPS_TRANSACTION) {
4493 return OK;
4494 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004495 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004496 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004497 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004498 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4499 return OK;
4500 }
4501 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4502 return PERMISSION_DENIED;
4503#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004504}
4505
Ana Krulec13be8ad2018-08-21 02:43:56 +00004506status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4507 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004508 status_t credentialCheck = CheckTransactCodeCredentials(code);
4509 if (credentialCheck != OK) {
4510 return credentialCheck;
4511 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004512
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004513 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4514 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004515 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004516 IPCThreadState* ipc = IPCThreadState::self();
4517 const int uid = ipc->getCallingUid();
4518 if (CC_UNLIKELY(uid != AID_SYSTEM
4519 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004520 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004521 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004522 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004523 return PERMISSION_DENIED;
4524 }
4525 int n;
4526 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004527 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004528 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004529 return NO_ERROR;
4530 case 1002: // SHOW_UPDATES
4531 n = data.readInt32();
4532 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004533 invalidateHwcGeometry();
4534 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004535 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004536 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004537 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004538 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004539 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004540 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004541 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004542 setTransactionFlags(
4543 eTransactionNeeded|
4544 eDisplayTransactionNeeded|
4545 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004546 return NO_ERROR;
4547 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004548 case 1006:{ // send empty update
4549 signalRefresh();
4550 return NO_ERROR;
4551 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004552 case 1008: // toggle use of hw composer
4553 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004554 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004555 invalidateHwcGeometry();
4556 repaintEverything();
4557 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004558 case 1009: // toggle use of transform hint
4559 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004560 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004561 invalidateHwcGeometry();
4562 repaintEverything();
4563 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004564 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004565 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004566 reply->writeInt32(0);
4567 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004568 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004569 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004570 return NO_ERROR;
4571 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004572 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004573 if (!display) {
4574 return NAME_NOT_FOUND;
4575 }
4576
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004577 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004578 return NO_ERROR;
4579 }
4580 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004581 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004582 // daltonize
4583 n = data.readInt32();
4584 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004585 case 1:
4586 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4587 break;
4588 case 2:
4589 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4590 break;
4591 case 3:
4592 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4593 break;
4594 default:
4595 mDaltonizer.setType(ColorBlindnessType::None);
4596 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004597 }
4598 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004599 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004600 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004601 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004602 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004603
4604 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004605 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004606 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004607 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004608 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004609 // apply a color matrix
4610 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004611 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004612 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004613 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004614 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004615 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004616 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004617 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004618 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004619 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004620 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004621
4622 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4623 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004624 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004625 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4626 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4627 }
4628
Chia-I Wu28f320b2018-05-03 11:02:56 -07004629 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004630 return NO_ERROR;
4631 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004632 case 1016: { // Unused.
4633 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004634 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004635 case 1017: {
4636 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004637 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004638 return NO_ERROR;
4639 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004640 case 1018: { // Modify Choreographer's phase offset
4641 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004642 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004643 return NO_ERROR;
4644 }
4645 case 1019: { // Modify SurfaceFlinger's phase offset
4646 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004647 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004648 return NO_ERROR;
4649 }
Irvel468051e2016-06-13 16:44:44 -07004650 case 1020: { // Layer updates interceptor
4651 n = data.readInt32();
4652 if (n) {
4653 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004654 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004655 }
4656 else{
4657 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004658 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004659 }
4660 return NO_ERROR;
4661 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004662 case 1021: { // Disable HWC virtual displays
4663 n = data.readInt32();
4664 mUseHwcVirtualDisplays = !n;
4665 return NO_ERROR;
4666 }
Romain Guy0147a172017-06-01 13:53:56 -07004667 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004668 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004669 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004670
Chia-I Wu28f320b2018-05-03 11:02:56 -07004671 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004672 return NO_ERROR;
4673 }
Romain Guy54f154a2017-10-24 21:40:32 +01004674 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004675 int32_t colorMode;
4676
Chia-I Wu0d711262018-05-21 15:19:35 -07004677 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004678 if (data.readInt32(&colorMode) == NO_ERROR) {
4679 mForceColorMode = static_cast<ColorMode>(colorMode);
4680 }
Romain Guy54f154a2017-10-24 21:40:32 +01004681 invalidateHwcGeometry();
4682 repaintEverything();
4683 return NO_ERROR;
4684 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004685 // Deprecate, use 1030 to check whether the device is color managed.
4686 case 1024: {
4687 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004688 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004689 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004690 n = data.readInt32();
4691 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004692 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004693 Mutex::Autolock lock(mStateLock);
4694 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004695 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004696 reply->writeInt32(NO_ERROR);
4697 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004698 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004699 bool writeFile = false;
4700 {
4701 Mutex::Autolock lock(mStateLock);
4702 mTracingEnabledChanged = true;
4703 writeFile = mTracing.disable();
4704 }
4705
4706 if (writeFile) {
4707 reply->writeInt32(mTracing.writeToFile());
4708 } else {
4709 reply->writeInt32(NO_ERROR);
4710 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004711 }
4712 return NO_ERROR;
4713 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004714 case 1026: { // Get layer tracing status
4715 reply->writeBool(mTracing.isEnabled());
4716 return NO_ERROR;
4717 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004718 // Is a DisplayColorSetting supported?
4719 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004720 const auto display = getDefaultDisplayDevice();
4721 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004722 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004723 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004724
4725 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4726 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004727 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004728 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004729 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004730 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004731 reply->writeBool(true);
4732 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004733 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004734 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004735 break;
4736 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004737 reply->writeBool(
4738 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004739 break;
4740 }
4741 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004742 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004743 // Is VrFlinger active?
4744 case 1028: {
4745 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004746 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004747 return NO_ERROR;
4748 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004749 // Set buffer size for SF tracing (value in KB)
4750 case 1029: {
4751 n = data.readInt32();
4752 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4753 ALOGW("Invalid buffer size: %d KB", n);
4754 reply->writeInt32(BAD_VALUE);
4755 return BAD_VALUE;
4756 }
4757
4758 ALOGD("Updating trace buffer to %d KB", n);
4759 mTracing.setBufferSize(n * 1024);
4760 reply->writeInt32(NO_ERROR);
4761 return NO_ERROR;
4762 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004763 // Is device color managed?
4764 case 1030: {
4765 reply->writeBool(useColorManagement);
4766 return NO_ERROR;
4767 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004768 // Override default composition data space
4769 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4770 // && adb shell stop zygote && adb shell start zygote
4771 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4772 // adb shell stop zygote && adb shell start zygote
4773 case 1031: {
4774 Mutex::Autolock _l(mStateLock);
4775 n = data.readInt32();
4776 if (n) {
4777 n = data.readInt32();
4778 if (n) {
4779 Dataspace dataspace = static_cast<Dataspace>(n);
4780 if (!validateCompositionDataspace(dataspace)) {
4781 return BAD_VALUE;
4782 }
4783 mDefaultCompositionDataspace = dataspace;
4784 }
4785 n = data.readInt32();
4786 if (n) {
4787 Dataspace dataspace = static_cast<Dataspace>(n);
4788 if (!validateCompositionDataspace(dataspace)) {
4789 return BAD_VALUE;
4790 }
4791 mWideColorGamutCompositionDataspace = dataspace;
4792 }
4793 } else {
4794 // restore composition data space.
4795 mDefaultCompositionDataspace = defaultCompositionDataspace;
4796 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4797 }
4798 return NO_ERROR;
4799 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004800 // Set trace flags
4801 case 1033: {
4802 n = data.readUint32();
4803 ALOGD("Updating trace flags to 0x%x", n);
4804 mTracing.setTraceFlags(n);
4805 reply->writeInt32(NO_ERROR);
4806 return NO_ERROR;
4807 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004808 case 1034: {
4809 // TODO(b/129297325): expose this via developer menu option
4810 n = data.readInt32();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004811 if (n && !mRefreshRateOverlay &&
4812 mRefreshRateConfigs->refreshRateSwitchingSupported()) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07004813 RefreshRateType type;
4814 {
4815 std::lock_guard<std::mutex> lock(mActiveConfigLock);
4816 type = mDesiredActiveConfig.type;
4817 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004818 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07004819 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004820 } else if (!n) {
4821 mRefreshRateOverlay.reset();
4822 }
4823 return NO_ERROR;
4824 }
Ady Abraham34392f72019-04-10 11:29:27 -07004825 case 1035: {
4826 n = data.readInt32();
4827 mDebugDisplayConfigSetByBackdoor = false;
4828 if (n >= 0) {
4829 const auto displayToken = getInternalDisplayToken();
4830 status_t result = setAllowedDisplayConfigs(displayToken, {n});
4831 if (result != NO_ERROR) {
4832 return result;
4833 }
4834 mDebugDisplayConfigSetByBackdoor = true;
4835 }
4836 return NO_ERROR;
4837 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004838 }
4839 }
4840 return err;
4841}
4842
Steven Thomas6d8110b2017-08-31 18:24:21 -07004843void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004844 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004845 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004846}
4847
Ana Krulec7d1d6832018-12-27 11:10:09 -08004848void SurfaceFlinger::repaintEverythingForHWC() {
4849 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004850 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004851}
4852
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004853// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4854class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004855public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004856 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4857 ~WindowDisconnector() {
4858 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004859 }
4860
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004861private:
4862 ANativeWindow* mWindow;
4863 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004864};
4865
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004866status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07004867 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
4868 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004869 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07004870 uint32_t reqWidth, uint32_t reqHeight,
4871 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08004872 ISurfaceComposer::Rotation rotation,
4873 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004874 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004875
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004876 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004877
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07004878 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
4879
Chia-I Wu20261cb2018-08-23 12:55:44 -07004880 sp<DisplayDevice> display;
4881 {
4882 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004883
Chia-I Wu20261cb2018-08-23 12:55:44 -07004884 display = getDisplayDeviceLocked(displayToken);
4885 if (!display) return BAD_VALUE;
4886
Chia-I Wucb023152018-08-28 12:57:23 -07004887 // set the requested width/height to the logical display viewport size
4888 // by default
4889 if (reqWidth == 0 || reqHeight == 0) {
4890 reqWidth = uint32_t(display->getViewport().width());
4891 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07004892 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004893 }
4894
Peiyong Lin0e003c92018-09-17 11:09:51 -07004895 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08004896 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004897
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08004898 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4899 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07004900 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07004901 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004902}
4903
chaviw93df2ea2019-04-30 16:45:12 -07004904static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
4905 switch (colorMode) {
4906 case ColorMode::DISPLAY_P3:
4907 case ColorMode::BT2100_PQ:
4908 case ColorMode::BT2100_HLG:
4909 case ColorMode::DISPLAY_BT2020:
4910 return Dataspace::DISPLAY_P3;
4911 default:
4912 return Dataspace::V0_SRGB;
4913 }
4914}
4915
4916const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
4917 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
4918 if (displayToken) {
4919 return getDisplayDeviceLocked(displayToken);
4920 }
4921 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
4922 // may not have a displayId.
4923 for (const auto& [token, display] : mDisplays) {
4924 if (display->getLayerStack() == displayOrLayerStack) {
4925 return display;
4926 }
4927 }
4928 return nullptr;
4929}
4930
4931status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
4932 sp<GraphicBuffer>* outBuffer) {
4933 sp<DisplayDevice> display;
4934 uint32_t width;
4935 uint32_t height;
4936 ui::Transform::orientation_flags captureOrientation;
4937 {
4938 Mutex::Autolock _l(mStateLock);
4939 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
4940 if (!display) {
4941 return BAD_VALUE;
4942 }
4943
4944 width = uint32_t(display->getViewport().width());
4945 height = uint32_t(display->getViewport().height());
4946
4947 captureOrientation = fromSurfaceComposerRotation(
4948 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07004949 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
4950 captureOrientation = ui::Transform::orientation_flags::ROT_270;
4951 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
4952 captureOrientation = ui::Transform::orientation_flags::ROT_90;
4953 }
chaviw93df2ea2019-04-30 16:45:12 -07004954 *outDataspace =
4955 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
4956 }
4957
4958 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
4959 false /* captureSecureLayers */);
4960
4961 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4962 std::placeholders::_1);
4963 bool ignored = false;
4964 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
4965 false /* useIdentityTransform */,
4966 ignored /* outCapturedSecureLayers */);
4967}
4968
Robert Carr866455f2019-04-02 16:28:26 -07004969status_t SurfaceFlinger::captureLayers(
4970 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
4971 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
4972 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
4973 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004974 ATRACE_CALL();
4975
4976 class LayerRenderArea : public RenderArea {
4977 public:
Robert Carr578038f2018-03-09 12:25:24 -08004978 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004979 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
4980 bool childrenOnly)
4981 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08004982 mLayer(layer),
4983 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004984 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08004985 mFlinger(flinger),
4986 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004987 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004988 Rect getBounds() const override {
4989 const Layer::State& layerState(mLayer->getDrawingState());
4990 return mLayer->getBufferSize(layerState);
4991 }
Marissa Wall61c58622018-07-18 10:12:20 -07004992 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004993 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07004994 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08004995 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004996 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08004997 }
chaviwa76b2712017-09-20 12:02:26 -07004998 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004999 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005000 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005001 Rect getSourceCrop() const override {
5002 if (mCrop.isEmpty()) {
5003 return getBounds();
5004 } else {
5005 return mCrop;
5006 }
5007 }
Robert Carr578038f2018-03-09 12:25:24 -08005008 class ReparentForDrawing {
5009 public:
5010 const sp<Layer>& oldParent;
5011 const sp<Layer>& newParent;
5012
Vishnu Nair4351ad52019-02-11 14:13:02 -08005013 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5014 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005015 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005016 // Compute and cache the bounds for the new parent layer.
5017 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005018 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005019 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005020 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005021 };
5022
5023 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005024 const Rect sourceCrop = getSourceCrop();
5025 // no need to check rotation because there is none
5026 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5027 sourceCrop.height() != getReqHeight();
5028
Robert Carr578038f2018-03-09 12:25:24 -08005029 if (!mChildrenOnly) {
5030 mTransform = mLayer->getTransform().inverse();
5031 drawLayers();
5032 } else {
5033 Rect bounds = getBounds();
chaviw32811fd2019-08-12 13:16:09 -07005034 // In the "childrenOnly" case we reparent the children to a screenshot
5035 // layer which has no properties set and which does not draw.
5036 sp<ContainerLayer> screenshotParentLayer =
5037 mFlinger->getFactory().createContainerLayer(
5038 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5039 bounds.getWidth(), bounds.getHeight(), 0,
5040 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005041
Vishnu Nair4351ad52019-02-11 14:13:02 -08005042 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005043 drawLayers();
5044 }
5045 }
chaviwa76b2712017-09-20 12:02:26 -07005046
chaviwa76b2712017-09-20 12:02:26 -07005047 private:
chaviw7206d492017-11-10 16:16:12 -08005048 const sp<Layer> mLayer;
5049 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005050
Peiyong Linefefaac2018-08-17 12:27:51 -07005051 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005052 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005053
5054 SurfaceFlinger* mFlinger;
5055 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005056 };
5057
Robert Carrc0df3122019-04-11 13:18:21 -07005058 int reqWidth = 0;
5059 int reqHeight = 0;
5060 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005061 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005062 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005063
Robert Carrc0df3122019-04-11 13:18:21 -07005064 {
5065 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005066
Robert Carrc0df3122019-04-11 13:18:21 -07005067 parent = fromHandle(layerHandleBinder);
5068 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5069 ALOGE("captureLayers called with an invalid or removed parent");
5070 return NAME_NOT_FOUND;
5071 }
5072
5073 const int uid = IPCThreadState::self()->getCallingUid();
5074 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5075 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5076 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5077 return PERMISSION_DENIED;
5078 }
5079
5080 if (sourceCrop.width() <= 0) {
5081 crop.left = 0;
5082 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5083 }
5084
5085 if (sourceCrop.height() <= 0) {
5086 crop.top = 0;
5087 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5088 }
5089 reqWidth = crop.width() * frameScale;
5090 reqHeight = crop.height() * frameScale;
5091
5092 for (const auto& handle : excludeHandles) {
5093 sp<Layer> excludeLayer = fromHandle(handle);
5094 if (excludeLayer != nullptr) {
5095 excludeLayers.emplace(excludeLayer);
5096 } else {
5097 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5098 return NAME_NOT_FOUND;
5099 }
5100 }
5101 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005102
Chia-I Wu20261cb2018-08-23 12:55:44 -07005103 // really small crop or frameScale
5104 if (reqWidth <= 0) {
5105 reqWidth = 1;
5106 }
5107 if (reqHeight <= 0) {
5108 reqHeight = 1;
5109 }
5110
Robert Carr866455f2019-04-02 16:28:26 -07005111 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5112 auto traverseLayers = [parent, childrenOnly,
5113 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005114 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5115 if (!layer->isVisible()) {
5116 return;
Robert Carr578038f2018-03-09 12:25:24 -08005117 } else if (childrenOnly && layer == parent.get()) {
5118 return;
chaviwa76b2712017-09-20 12:02:26 -07005119 }
Robert Carr866455f2019-04-02 16:28:26 -07005120
5121 sp<Layer> p = layer;
5122 while (p != nullptr) {
5123 if (excludeLayers.count(p) != 0) {
5124 return;
5125 }
5126 p = p->getParent();
5127 }
5128
chaviwa76b2712017-09-20 12:02:26 -07005129 visitor(layer);
5130 });
5131 };
Robert Carr108b2c72019-04-02 16:32:58 -07005132
5133 bool outCapturedSecureLayers = false;
5134 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5135 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005136}
5137
5138status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5139 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005140 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005141 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005142 bool useIdentityTransform,
5143 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005144 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005145
Peiyong Lin0e003c92018-09-17 11:09:51 -07005146 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005147 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5148 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005149 *outBuffer =
5150 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5151 static_cast<android_pixel_format>(reqPixelFormat), 1,
5152 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005153
Robert Carr108b2c72019-04-02 16:32:58 -07005154 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5155 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005156}
5157
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005158status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5159 TraverseLayersFunction traverseLayers,
5160 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005161 bool useIdentityTransform,
5162 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005163 // This mutex protects syncFd and captureResult for communication of the return values from the
5164 // main thread back to this Binder thread
5165 std::mutex captureMutex;
5166 std::condition_variable captureCondition;
5167 std::unique_lock<std::mutex> captureLock(captureMutex);
5168 int syncFd = -1;
5169 std::optional<status_t> captureResult;
5170
Robert Carr03480e22018-01-04 16:02:06 -08005171 const int uid = IPCThreadState::self()->getCallingUid();
5172 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5173
Dominik Laskowski8c001672018-05-30 16:52:06 -07005174 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005175 // If there is a refresh pending, bug out early and tell the binder thread to try again
5176 // after the refresh.
5177 if (mRefreshPending) {
5178 ATRACE_NAME("Skipping screenshot for now");
5179 std::unique_lock<std::mutex> captureLock(captureMutex);
5180 captureResult = std::make_optional<status_t>(EAGAIN);
5181 captureCondition.notify_one();
5182 return;
5183 }
5184
5185 status_t result = NO_ERROR;
5186 int fd = -1;
5187 {
5188 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005189 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005190 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005191 useIdentityTransform, forSystem, &fd,
5192 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005193 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005194 }
5195
5196 {
5197 std::unique_lock<std::mutex> captureLock(captureMutex);
5198 syncFd = fd;
5199 captureResult = std::make_optional<status_t>(result);
5200 captureCondition.notify_one();
5201 }
5202 });
5203
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005204 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005205 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005206 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005207 while (*captureResult == EAGAIN) {
5208 captureResult.reset();
5209 result = postMessageAsync(message);
5210 if (result != NO_ERROR) {
5211 return result;
5212 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005213 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005214 }
5215 result = *captureResult;
5216 }
5217
5218 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005219 sync_wait(syncFd, -1);
5220 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005221 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005222
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005223 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005224}
5225
chaviwa76b2712017-09-20 12:02:26 -07005226void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005227 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005228 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5229 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005230 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005231
chaviwa76b2712017-09-20 12:02:26 -07005232 const auto reqWidth = renderArea.getReqWidth();
5233 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005234 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005235 const auto transform = renderArea.getTransform();
5236 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005237
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005238 renderengine::DisplaySettings clientCompositionDisplay;
5239 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005240
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005241 // assume that bounds are never offset, and that they are the same as the
5242 // buffer bounds.
5243 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005244 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005245 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005246
5247 // Now take into account the rotation flag. We append a transform that
5248 // rotates the layer stack about the origin, then translate by buffer
5249 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005250 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005251 int displacementX = 0;
5252 int displacementY = 0;
5253 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5254 switch (rotation) {
5255 case ui::Transform::ROT_90:
5256 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005257 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005258 break;
5259 case ui::Transform::ROT_180:
5260 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005261 displacementY = renderArea.getBounds().getWidth();
5262 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005263 break;
5264 case ui::Transform::ROT_270:
5265 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005266 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005267 break;
5268 default:
5269 break;
5270 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005271
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005272 // We need to transform the clipping window into the right spot.
5273 // First, rotate the clipping rectangle by the rotation hint to get the
5274 // right orientation
5275 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5276 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5277 const vec4 rotClipTL = rotMatrix * clipTL;
5278 const vec4 rotClipBR = rotMatrix * clipBR;
5279 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5280 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5281 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5282 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5283
5284 // Now reposition the clipping rectangle with the displacement vector
5285 // computed above.
5286 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005287 clientCompositionDisplay.clip =
5288 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5289 newClipRight + displacementX, newClipBottom + displacementY);
5290
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005291 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005292 clientCompositionDisplay.globalTransform =
5293 clipTransform * clientCompositionDisplay.globalTransform;
5294
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005295 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5296 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005297
chaviw50da5042018-04-09 13:49:37 -07005298 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005299
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005300 renderengine::LayerSettings fillLayer;
5301 fillLayer.source.buffer.buffer = nullptr;
5302 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5303 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5304 fillLayer.alpha = half(alpha);
5305 clientCompositionLayers.push_back(fillLayer);
5306
5307 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005308 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005309 const bool supportProtectedContent = false;
5310 Region clip(renderArea.getBounds());
5311 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5312 clip,
5313 useIdentityTransform,
5314 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5315 renderArea.isSecure(),
5316 supportProtectedContent,
5317 clearRegion,
5318 };
5319 auto result = layer->prepareClientComposition(targetSettings);
5320 if (result) {
5321 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005322 }
chaviwa76b2712017-09-20 12:02:26 -07005323 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005324
5325 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005326 // Use an empty fence for the buffer fence, since we just created the buffer so
5327 // there is no need for synchronization with the GPU.
5328 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005329 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005330 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005331 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005332 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005333
5334 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005335}
5336
chaviwa76b2712017-09-20 12:02:26 -07005337status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5338 TraverseLayersFunction traverseLayers,
5339 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005340 bool useIdentityTransform, bool forSystem,
5341 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005342 ATRACE_CALL();
5343
chaviwa76b2712017-09-20 12:02:26 -07005344 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005345 outCapturedSecureLayers =
5346 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005347 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005348
Robert Carr03480e22018-01-04 16:02:06 -08005349 // We allow the system server to take screenshots of secure layers for
5350 // use in situations like the Screen-rotation animation and place
5351 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005352 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005353 ALOGW("FB is protected: PERMISSION_DENIED");
5354 return PERMISSION_DENIED;
5355 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005356 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005357 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005358}
5359
chaviw95ef3c42019-02-14 10:55:09 -08005360void SurfaceFlinger::setInputWindowsFinished() {
5361 Mutex::Autolock _l(mStateLock);
5362
5363 mPendingSyncInputWindows = false;
5364 mTransactionCV.broadcast();
5365}
chaviw5f21a5e2019-02-14 10:00:34 -08005366
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005367// ---------------------------------------------------------------------------
5368
Dan Stoza412903f2017-04-27 13:42:17 -07005369void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5370 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005371}
5372
Dan Stoza412903f2017-04-27 13:42:17 -07005373void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5374 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005375}
5376
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005377void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005378 const LayerVector::Visitor& visitor) {
5379 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005380 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005381 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005382 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005383 continue;
5384 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005385 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005386 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005387 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005388 return;
5389 }
chaviwa76b2712017-09-20 12:02:26 -07005390 if (!layer->isVisible()) {
5391 return;
5392 }
5393 visitor(layer);
5394 });
5395 }
5396}
5397
Dominik Laskowski22488f62019-03-28 09:53:04 -07005398void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5399 const std::vector<int32_t>& allowedConfigs) {
5400 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08005401 return;
5402 }
5403
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005404 const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
5405 allowedConfigs.end());
5406 if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
5407 return;
5408 }
5409
Ady Abraham838de062019-02-04 10:24:03 -08005410 ALOGV("Updating allowed configs");
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005411 mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
5412
5413 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5414 // that listeners that care about a change in allowed configs can get the notification.
5415 // Giving current ActiveConfig so that most other listeners would just drop the event
5416 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5417 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08005418
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005419 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5420 const auto& type = mScheduler->getPreferredRefreshRateType();
5421 const auto& config = mRefreshRateConfigs->getRefreshRateFromType(type);
5422 if (isDisplayConfigAllowed(config.configId)) {
5423 ALOGV("switching to Scheduler preferred config %d", config.configId);
5424 setDesiredActiveConfig({type, config.configId, Scheduler::ConfigEvent::Changed});
5425 } else {
5426 // Set the highest allowed config by iterating backwards on available refresh rates
5427 const auto& refreshRates = mRefreshRateConfigs->getRefreshRateMap();
5428 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
5429 if (isDisplayConfigAllowed(iter->second.configId)) {
5430 ALOGV("switching to allowed config %d", iter->second.configId);
5431 setDesiredActiveConfig(
5432 {iter->first, iter->second.configId, Scheduler::ConfigEvent::Changed});
5433 break;
5434 }
5435 }
5436 }
5437 } else if (!allowedConfigs.empty()) {
5438 ALOGV("switching to config %d", allowedConfigs[0]);
5439 setDesiredActiveConfig(
5440 {RefreshRateType::DEFAULT, allowedConfigs[0], Scheduler::ConfigEvent::Changed});
5441 }
Ady Abraham838de062019-02-04 10:24:03 -08005442}
5443
Dominik Laskowski22488f62019-03-28 09:53:04 -07005444status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005445 const std::vector<int32_t>& allowedConfigs) {
5446 ATRACE_CALL();
5447
Dominik Laskowski22488f62019-03-28 09:53:04 -07005448 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005449 return BAD_VALUE;
5450 }
5451
Ady Abraham34392f72019-04-10 11:29:27 -07005452 if (mDebugDisplayConfigSetByBackdoor) {
5453 // ignore this request as config is overridden by backdoor
5454 return NO_ERROR;
5455 }
5456
Ady Abraham838de062019-02-04 10:24:03 -08005457 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005458 const auto display = getDisplayDeviceLocked(displayToken);
5459 if (!display) {
5460 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5461 displayToken.get());
5462 } else if (display->isVirtual()) {
5463 ALOGW("Attempt to set allowed display configs for virtual display");
5464 } else {
5465 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5466 }
Ady Abraham838de062019-02-04 10:24:03 -08005467 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005468
Ady Abraham838de062019-02-04 10:24:03 -08005469 return NO_ERROR;
5470}
5471
Dominik Laskowski22488f62019-03-28 09:53:04 -07005472status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005473 std::vector<int32_t>* outAllowedConfigs) {
5474 ATRACE_CALL();
5475
Dominik Laskowski22488f62019-03-28 09:53:04 -07005476 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005477 return BAD_VALUE;
5478 }
5479
Dominik Laskowski22488f62019-03-28 09:53:04 -07005480 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005481
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005482 const auto display = getDisplayDeviceLocked(displayToken);
5483 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005484 return NAME_NOT_FOUND;
5485 }
5486
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005487 if (display->isPrimary()) {
5488 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
5489 }
5490
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005491 return NO_ERROR;
5492}
5493
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005494void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005495 mFlinger->setInputWindowsFinished();
5496}
5497
Robert Carrc0df3122019-04-11 13:18:21 -07005498sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5499 BBinder *b = handle->localBinder();
5500 if (b == nullptr) {
5501 return nullptr;
5502 }
5503 auto it = mLayersByLocalBinderToken.find(b);
5504 if (it != mLayersByLocalBinderToken.end()) {
5505 return it->second.promote();
5506 }
5507 return nullptr;
5508}
5509
Alec Mouri4545a8a2019-08-08 20:05:32 -07005510void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5511 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5512}
5513
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005514} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005515
Mathias Agopian3f844832013-08-07 21:24:32 -07005516#if defined(__gl_h_)
5517#error "don't include gl/gl.h in this file"
5518#endif
5519
5520#if defined(__gl2_h_)
5521#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005522#endif