blob: 8b2f5e1af8baca371c1963bb5db7d5eb44a8d979 [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080041#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070042#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070043#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080044#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070049#include <gui/DebugEGLImageTracker.h>
50
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070087#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070098#include "FrameTracer/FrameTracer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -070099#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700100#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700101#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700102#include "Scheduler/EventControlThread.h"
103#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700104#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700105#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700106#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800107#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700108
Mathias Agopianff2ed702013-09-01 21:36:12 -0700109#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700110
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700111#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800112#include "android-base/stringprintf.h"
113
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800115#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
116#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700117#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900118#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119
chaviw1d044282017-09-27 12:19:28 -0700120#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900121#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700124
Jaesoo Lee43518572017-01-23 19:03:16 +0900125using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900126using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900127using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800128
Ady Abraham8532d012019-05-08 14:50:56 -0700129using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800130using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700131using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700132using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800133using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700134using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700135using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900136
Steven Thomasb02664d2017-07-26 18:48:28 -0700137namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700138
139#pragma clang diagnostic push
140#pragma clang diagnostic error "-Wswitch-enum"
141
142bool isWideColorMode(const ColorMode colorMode) {
143 switch (colorMode) {
144 case ColorMode::DISPLAY_P3:
145 case ColorMode::ADOBE_RGB:
146 case ColorMode::DCI_P3:
147 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700148 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700149 case ColorMode::BT2100_PQ:
150 case ColorMode::BT2100_HLG:
151 return true;
152 case ColorMode::NATIVE:
153 case ColorMode::STANDARD_BT601_625:
154 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
155 case ColorMode::STANDARD_BT601_525:
156 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
157 case ColorMode::STANDARD_BT709:
158 case ColorMode::SRGB:
159 return false;
160 }
161 return false;
162}
163
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700164ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
165 switch (rotation) {
166 case ISurfaceComposer::eRotateNone:
167 return ui::Transform::ROT_0;
168 case ISurfaceComposer::eRotate90:
169 return ui::Transform::ROT_90;
170 case ISurfaceComposer::eRotate180:
171 return ui::Transform::ROT_180;
172 case ISurfaceComposer::eRotate270:
173 return ui::Transform::ROT_270;
174 }
175 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
176 return ui::Transform::ROT_0;
177}
178
Peiyong Linfca547f2018-07-09 13:03:33 -0700179#pragma clang diagnostic pop
180
Steven Thomasb02664d2017-07-26 18:48:28 -0700181class ConditionalLock {
182public:
183 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
184 if (lock) {
185 mMutex.lock();
186 }
187 }
188 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
189private:
190 Mutex& mMutex;
191 bool mLocked;
192};
Peiyong Linfca547f2018-07-09 13:03:33 -0700193
Peiyong Lin9d846a52018-11-05 13:18:20 -0800194// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
195bool validateCompositionDataspace(Dataspace dataspace) {
196 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
197}
198
Steven Thomasb02664d2017-07-26 18:48:28 -0700199} // namespace anonymous
200
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800201// ---------------------------------------------------------------------------
202
Mathias Agopian99b49842011-06-27 16:05:52 -0700203const String16 sHardwareTest("android.permission.HARDWARE_TEST");
204const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
205const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
206const String16 sDump("android.permission.DUMP");
207
208// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700209int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700210bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800211uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800212bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800213bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800214int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600215bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700216int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700217bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700218bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700219Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
220ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
221Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
222ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700223
Kalle Raitaa099a242017-01-11 11:17:29 -0800224std::string getHwcServiceName() {
225 char value[PROPERTY_VALUE_MAX] = {};
226 property_get("debug.sf.hwc_service_name", value, "default");
227 ALOGI("Using HWComposer service: '%s'", value);
228 return std::string(value);
229}
230
231bool useTrebleTestingOverride() {
232 char value[PROPERTY_VALUE_MAX] = {};
233 property_get("debug.sf.treble_testing_override", value, "false");
234 ALOGI("Treble testing override: '%s'", value);
235 return std::string(value) == "true";
236}
237
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800238std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
239 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800240 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700241 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800242 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700243 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800244 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Enhanced");
246 default:
247 return std::string("Unknown ") +
248 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800249 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800250}
251
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700252SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800253
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700254SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
255 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700256 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700257 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700258 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700259 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700260 mCompositionEngine(mFactory.createCompositionEngine()),
261 mPhaseOffsets(mFactory.createPhaseOffsets()) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800262
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700263SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800264 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800265
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900266 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800267
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900268 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700269
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900270 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700271
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900272 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800273
Steven Thomas050b2c82017-03-06 11:45:16 -0800274 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800276
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800278
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900279 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700280
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900281 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600282
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900283 mDefaultCompositionDataspace =
284 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700285 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
286 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900287 defaultCompositionDataspace = mDefaultCompositionDataspace;
288 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
289 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
290 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
291 wideColorGamutCompositionPixelFormat =
292 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700293
Yichi Chenda901bf2019-06-28 14:58:27 +0800294 mColorSpaceAgnosticDataspace =
295 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
296
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900297 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
300 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
301 switch (tmpPrimaryDisplayOrientation) {
302 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700303 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800304 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900305 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700306 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800307 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700309 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800310 break;
311 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700312 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800313 break;
314 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700315 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800316
Sundong Ahn85131bd2019-02-18 15:51:53 +0900317 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800318
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800319 // debugging stuff...
320 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700321
Mathias Agopianb4b17302013-03-20 18:36:41 -0700322 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700323 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700324
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800325 property_get("debug.sf.showupdates", value, "0");
326 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700327
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700328 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000329
330 // DDMS debugging deprecated (b/120782499)
331 property_get("debug.sf.ddms", value, "0");
332 int debugDdms = atoi(value);
333 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700334
335 property_get("debug.sf.disable_backpressure", value, "0");
336 mPropagateBackpressure = !atoi(value);
337 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700338
Ady Abrahamadb9a992019-09-19 21:21:55 +0000339 property_get("debug.sf.enable_gl_backpressure", value, "0");
340 mPropagateBackpressureClientComposition = atoi(value);
341 ALOGI_IF(mPropagateBackpressureClientComposition,
342 "Enabling backpressure propagation for Client Composition");
343
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800344 property_get("debug.sf.enable_hwc_vds", value, "0");
345 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800346 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800347
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800348 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800349 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800350 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700351
Yiwei Zhang243b3782018-05-15 17:40:04 -0700352 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700353 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
354 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
355
Ana Krulece5a06e02019-03-06 17:09:03 -0800356 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800357 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800358
359 int int_value = atoi(value);
360 if (int_value) {
361 mUseSmart90ForVideo = true;
362 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800363
Dan Stozaec460082018-12-17 15:35:09 -0800364 property_get("debug.sf.luma_sampling", value, "1");
365 mLumaSampling = atoi(value);
366
Romain Guy11d63f42017-07-20 12:47:14 -0700367 // We should be reading 'persist.sys.sf.color_saturation' here
368 // but since /data may be encrypted, we need to wait until after vold
369 // comes online to attempt to read the property. The property is
370 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800371
372 if (useTrebleTestingOverride()) {
373 // Without the override SurfaceFlinger cannot connect to HIDL
374 // services that are not listed in the manifests. Considered
375 // deriving the setting from the set service name, but it
376 // would be brittle if the name that's not 'default' is used
377 // for production purposes later on.
378 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
379 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800380}
381
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800382void SurfaceFlinger::onFirstRef()
383{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800384 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800385}
386
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700387SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800388
Dan Stozac7014012014-02-14 15:03:43 -0800389void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800390{
391 // the window manager died on us. prepare its eulogy.
392
Andy McFadden13a082e2012-08-24 10:16:42 -0700393 // restore initial conditions (default device unblank, etc)
394 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800395
396 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700397 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800398}
399
Robert Carr1db73f62016-12-21 12:58:51 -0800400static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700401 status_t err = client->initCheck();
402 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800403 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800404 }
Robert Carr1db73f62016-12-21 12:58:51 -0800405 return nullptr;
406}
407
408sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
409 return initClient(new Client(this));
410}
411
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700412sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
413 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700414{
415 class DisplayToken : public BBinder {
416 sp<SurfaceFlinger> flinger;
417 virtual ~DisplayToken() {
418 // no more references, this display must be terminated
419 Mutex::Autolock _l(flinger->mStateLock);
420 flinger->mCurrentState.displays.removeItem(this);
421 flinger->setTransactionFlags(eDisplayTransactionNeeded);
422 }
423 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700424 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700425 : flinger(flinger) {
426 }
427 };
428
429 sp<BBinder> token = new DisplayToken(this);
430
431 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700432 // Display ID is assigned when virtual display is allocated by HWC.
433 DisplayDeviceState state;
434 state.isSecure = secure;
435 state.displayName = displayName;
436 mCurrentState.displays.add(token, state);
437 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700438 return token;
439}
440
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700441void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700442 Mutex::Autolock _l(mStateLock);
443
Dominik Laskowski075d3172018-05-24 15:50:06 -0700444 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
445 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700446 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700447 return;
448 }
449
Dominik Laskowski075d3172018-05-24 15:50:06 -0700450 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
451 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700452 ALOGE("destroyDisplay called for non-virtual display");
453 return;
454 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700455 mInterceptor->saveDisplayDeletion(state.sequenceId);
456 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700457 setTransactionFlags(eDisplayTransactionNeeded);
458}
459
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800460std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
461 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700462
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800463 const auto internalDisplayId = getInternalDisplayIdLocked();
464 if (!internalDisplayId) {
465 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700466 }
467
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800468 std::vector<PhysicalDisplayId> displayIds;
469 displayIds.reserve(mPhysicalDisplayTokens.size());
470 displayIds.push_back(internalDisplayId->value);
471
472 for (const auto& [id, token] : mPhysicalDisplayTokens) {
473 if (id != *internalDisplayId) {
474 displayIds.push_back(id.value);
475 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700476 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700477
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800478 return displayIds;
479}
480
481sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
482 Mutex::Autolock lock(mStateLock);
483 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700484}
485
Ady Abraham37965d42018-11-01 13:43:32 -0700486status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
487 if (!outGetColorManagement) {
488 return BAD_VALUE;
489 }
490 *outGetColorManagement = useColorManagement;
491 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700492}
493
Lloyd Pique441d5042018-10-18 16:49:51 -0700494HWComposer& SurfaceFlinger::getHwComposer() const {
495 return mCompositionEngine->getHwComposer();
496}
497
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700498renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
499 return mCompositionEngine->getRenderEngine();
500}
501
Lloyd Pique70d91362018-10-18 16:02:55 -0700502compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
503 return *mCompositionEngine.get();
504}
505
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800506void SurfaceFlinger::bootFinished()
507{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700508 if (mStartPropertySetThread->join() != NO_ERROR) {
509 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800510 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800511 const nsecs_t now = systemTime();
512 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000513 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700514
Mikael Pessa90092f42019-08-26 17:22:04 -0700515 mFrameTracer->initialize();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700516
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700517 // wait patiently for the window manager death
518 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700519 mWindowManager = defaultServiceManager()->getService(name);
520 if (mWindowManager != 0) {
521 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700522 }
Robert Carr720e5062018-07-30 17:45:14 -0700523 sp<IBinder> input(defaultServiceManager()->getService(
524 String16("inputflinger")));
525 if (input == nullptr) {
526 ALOGE("Failed to link to input service");
527 } else {
528 mInputFlinger = interface_cast<IInputFlinger>(input);
529 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700530
Steven Thomas050b2c82017-03-06 11:45:16 -0800531 if (mVrFlinger) {
532 mVrFlinger->OnBootFinished();
533 }
534
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700535 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700536 // formerly we would just kill the process, but we now ask it to exit so it
537 // can choose where to stop the animation.
538 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700539
540 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
541 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
542 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700543
Ana Krulecbd6654b2019-02-15 15:18:15 -0800544 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800545 readPersistentProperties();
546 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800547
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700548 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
549 // set the refresh rate according to the policy
550 const auto& performanceRefreshRate =
551 mRefreshRateConfigs->getRefreshRateFromType(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800552
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700553 if (isDisplayConfigAllowed(performanceRefreshRate.configId)) {
554 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
555 } else {
556 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
557 }
Ana Krulecbd6654b2019-02-15 15:18:15 -0800558 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800559 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800560}
561
Dan Stoza436ccf32018-06-21 12:10:12 -0700562uint32_t SurfaceFlinger::getNewTexture() {
563 {
564 std::lock_guard lock(mTexturePoolMutex);
565 if (!mTexturePool.empty()) {
566 uint32_t name = mTexturePool.back();
567 mTexturePool.pop_back();
568 ATRACE_INT("TexturePoolSize", mTexturePool.size());
569 return name;
570 }
571
572 // The pool was too small, so increase it for the future
573 ++mTexturePoolSize;
574 }
575
576 // The pool was empty, so we need to get a new texture name directly using a
577 // blocking call to the main thread
578 uint32_t name = 0;
579 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
580 return name;
581}
582
Mathias Agopian3f844832013-08-07 21:24:32 -0700583void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700584 std::lock_guard lock(mTexturePoolMutex);
585 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
586 // to actually delete this or not based on mTexturePoolSize
587 mTexturePool.push_back(texture);
588 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700589}
590
Wei Wangf9b05ee2017-07-19 20:59:39 -0700591// Do not call property_set on main thread which will be blocked by init
592// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700593void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700594 ALOGI( "SurfaceFlinger's main thread ready to run. "
595 "Initializing graphics H/W...");
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700596 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900597
Steven Thomasb02664d2017-07-26 18:48:28 -0700598 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800599
Steven Thomasb02664d2017-07-26 18:48:28 -0700600 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700601 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700602 renderEngineFeature |= (useColorManagement ?
603 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700604 renderEngineFeature |= (useContextPriority ?
605 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700606 renderEngineFeature |=
607 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
608 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700609
610 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800611 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700612 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700613 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800614 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700615
616 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
617 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700618 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
619 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800620 // Process any initial hotplug and resulting display changes.
621 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700622 const auto display = getDefaultDisplayDeviceLocked();
623 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700624 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700625 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800626
Steven Thomas050b2c82017-03-06 11:45:16 -0800627 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700628 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700629 // This callback is called from the vr flinger dispatch thread. We
630 // need to call signalTransaction(), which requires holding
631 // mStateLock when we're not on the main thread. Acquiring
632 // mStateLock from the vr flinger dispatch thread might trigger a
633 // deadlock in surface flinger (see b/66916578), so post a message
634 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700635 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700636 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
637 mVrFlingerRequestsDisplay = requestDisplay;
638 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700639 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800640 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700641 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
642 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700643 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700644 .value_or(0),
645 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800646 if (!mVrFlinger) {
647 ALOGE("Failed to start vrflinger");
648 }
649 }
650
Mathias Agopian92a979a2012-08-02 18:32:23 -0700651 // initialize our drawing state
652 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700653
Andy McFadden13a082e2012-08-24 10:16:42 -0700654 // set initial conditions (e.g. unblank default device)
655 initializeDisplays();
656
Steven Thomas137d4bc2019-07-25 16:55:14 -0700657 char primeShaderCache[PROPERTY_VALUE_MAX];
658 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
659 if (atoi(primeShaderCache)) {
660 getRenderEngine().primeCache();
661 }
Dan Stoza4e637772016-07-28 13:31:51 -0700662
Wei Wangf9b05ee2017-07-19 20:59:39 -0700663 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700664
665 const bool presentFenceReliable =
666 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
667 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700668
669 if (mStartPropertySetThread->Start() != NO_ERROR) {
670 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800671 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800672
Dan Stoza9e56aa02015-11-02 13:00:03 -0800673 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700674}
675
Romain Guy11d63f42017-07-20 12:47:14 -0700676void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700677 Mutex::Autolock _l(mStateLock);
678
Romain Guy11d63f42017-07-20 12:47:14 -0700679 char value[PROPERTY_VALUE_MAX];
680
681 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800682 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700683 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800684 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100685
686 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700687 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800688
689 property_get("persist.sys.sf.color_mode", value, "0");
690 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700691}
692
Mathias Agopiana67e4182012-06-19 17:26:12 -0700693void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800694 // Start boot animation service by setting a property mailbox
695 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700696 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800697 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700698 if (mStartPropertySetThread->join() != NO_ERROR) {
699 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800700 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700701}
702
Mathias Agopian875d8e12013-06-07 15:35:48 -0700703size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700704 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700705}
706
Mathias Agopian875d8e12013-06-07 15:35:48 -0700707size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700708 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700709}
710
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800711// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800712
Jamie Gennis582270d2011-08-17 18:19:00 -0700713bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800714 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800715 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800716 return authenticateSurfaceTextureLocked(bufferProducer);
717}
718
719bool SurfaceFlinger::authenticateSurfaceTextureLocked(
720 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800721 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800722 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800723}
724
Brian Anderson6b376712017-04-04 10:51:39 -0700725status_t SurfaceFlinger::getSupportedFrameTimestamps(
726 std::vector<FrameEvent>* outSupported) const {
727 *outSupported = {
728 FrameEvent::REQUESTED_PRESENT,
729 FrameEvent::ACQUIRE,
730 FrameEvent::LATCH,
731 FrameEvent::FIRST_REFRESH_START,
732 FrameEvent::LAST_REFRESH_START,
733 FrameEvent::GPU_COMPOSITION_DONE,
734 FrameEvent::DEQUEUE_READY,
735 FrameEvent::RELEASE,
736 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700737 ConditionalLock _l(mStateLock,
738 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700739 if (!getHwComposer().hasCapability(
740 HWC2::Capability::PresentFenceIsNotReliable)) {
741 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
742 }
743 return NO_ERROR;
744}
745
Dominik Laskowski22488f62019-03-28 09:53:04 -0700746status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
747 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700748 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700749 return BAD_VALUE;
750 }
751
Dominik Laskowski22488f62019-03-28 09:53:04 -0700752 Mutex::Autolock lock(mStateLock);
753
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800754 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700755 if (!displayId) {
756 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700757 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700758
Mathias Agopian8b736f12012-08-13 17:54:26 -0700759 // TODO: Not sure if display density should handled by SF any longer
760 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700761 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700762 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700763 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800764 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700765 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700766 }
767 return density;
768 }
769 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700770 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700771 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700772 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700773 return getDensityFromProperty("ro.sf.lcd_density"); }
774 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700775
Dan Stoza7f7da322014-05-02 15:26:25 -0700776 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700777
Dominik Laskowski075d3172018-05-24 15:50:06 -0700778 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700779 DisplayInfo info = DisplayInfo();
780
Dan Stoza9e56aa02015-11-02 13:00:03 -0800781 float xdpi = hwConfig->getDpiX();
782 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700783
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700784 info.w = hwConfig->getWidth();
785 info.h = hwConfig->getHeight();
786 // Default display viewport to display width and height
787 info.viewportW = info.w;
788 info.viewportH = info.h;
789
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800790 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700791 // The density of the device is provided by a build property
792 float density = Density::getBuildDensity() / 160.0f;
793 if (density == 0) {
794 // the build doesn't provide a density -- this is wrong!
795 // use xdpi instead
796 ALOGE("ro.sf.lcd_density must be defined as a build property");
797 density = xdpi / 160.0f;
798 }
799 if (Density::getEmuDensity()) {
800 // if "qemu.sf.lcd_density" is specified, it overrides everything
801 xdpi = ydpi = density = Density::getEmuDensity();
802 density /= 160.0f;
803 }
804 info.density = density;
805
806 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700807 const auto display = getDefaultDisplayDeviceLocked();
808 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700809
810 // This is for screenrecord
811 const Rect viewport = display->getViewport();
812 if (viewport.isValid()) {
813 info.viewportW = uint32_t(viewport.getWidth());
814 info.viewportH = uint32_t(viewport.getHeight());
815 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700816 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700817 } else {
818 // TODO: where should this value come from?
819 static const int TV_DENSITY = 213;
820 info.density = TV_DENSITY / 160.0f;
821 info.orientation = 0;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700822
823 const auto display = getDisplayDeviceLocked(displayToken);
824 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700825 }
826
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 info.xdpi = xdpi;
828 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800829 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700830 const auto refreshRateType =
831 mRefreshRateConfigs->getRefreshRateTypeFromHwcConfigId(hwConfig->getId());
Ady Abraham796beb02019-04-11 15:23:07 -0700832 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
833 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800834
Andy McFadden91b2ca82014-06-13 14:04:23 -0700835 // This is how far in advance a buffer must be queued for
836 // presentation at a given time. If you want a buffer to appear
837 // on the screen at time N, you must submit the buffer before
838 // (N - presentationDeadline).
839 //
840 // Normally it's one full refresh period (to give SF a chance to
841 // latch the buffer), but this can be reduced by configuring a
842 // DispSync offset. Any additional delays introduced by the hardware
843 // composer or panel must be accounted for here.
844 //
845 // We add an additional 1ms to allow for processing time and
846 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700847 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700848
849 // All non-virtual displays are currently considered secure.
850 info.secure = true;
851
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800852 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700853 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800854 std::swap(info.w, info.h);
855 }
856
Michael Wright28f24d02016-07-12 13:30:53 -0700857 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700858 }
859
Dan Stoza7f7da322014-05-02 15:26:25 -0700860 return NO_ERROR;
861}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700862
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700863status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
864 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700865 return BAD_VALUE;
866 }
867
Ana Krulecc2870422019-01-29 19:00:58 -0800868 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700869 return NO_ERROR;
870}
871
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700872int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
873 const auto display = getDisplayDevice(displayToken);
874 if (!display) {
875 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800876 return BAD_VALUE;
877 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700878
Steven Thomasc9098452019-09-30 17:15:05 -0700879 if (display->isPrimary()) {
880 std::lock_guard<std::mutex> lock(mActiveConfigLock);
881 if (mDesiredActiveConfigChanged) {
882 return mDesiredActiveConfig.configId;
883 } else {
884 return display->getActiveConfig();
885 }
886 } else {
887 return display->getActiveConfig();
888 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700889}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700890
Ady Abraham03b02dd2019-03-21 15:40:11 -0700891void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800892 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800893
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800894 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800895 // config twice. However event generation config might have changed so we need to update it
896 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800897 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700898 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
899 mDesiredActiveConfig = info;
900 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800901
902 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800903 // This will trigger HWC refresh without resetting the idle timer.
904 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700905 // Start receiving vsync samples now, so that we can detect a period
906 // switch.
907 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700908 // As we called to set period, we will call to onRefreshRateChangeCompleted once
909 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700910 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700911 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700912 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800913 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800914 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700915
916 if (mRefreshRateOverlay) {
917 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
918 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800919}
920
921status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
922 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800923
924 std::vector<int32_t> allowedConfig;
925 allowedConfig.push_back(mode);
926
927 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800928}
929
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800930void SurfaceFlinger::setActiveConfigInternal() {
931 ATRACE_CALL();
932
Dominik Laskowski22488f62019-03-28 09:53:04 -0700933 const auto display = getDefaultDisplayDeviceLocked();
934 if (!display) {
935 return;
936 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800937
Dominik Laskowski22488f62019-03-28 09:53:04 -0700938 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700939 mRefreshRateConfigs->setCurrentConfig(mUpcomingActiveConfig.configId);
940 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700941
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800942 display->setActiveConfig(mUpcomingActiveConfig.configId);
943
Alec Mouri754c98a2019-03-18 18:53:42 -0700944 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700945 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800946 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700947
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800948 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800949 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
950 mUpcomingActiveConfig.configId);
951 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800952}
953
Ady Abraham53852a52019-05-28 18:07:44 -0700954void SurfaceFlinger::desiredActiveConfigChangeDone() {
955 std::lock_guard<std::mutex> lock(mActiveConfigLock);
956 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
957 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700958
959 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
960 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700961 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700962}
963
Dominik Laskowski22488f62019-03-28 09:53:04 -0700964bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800965 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800966 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700967 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800968 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700969 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800970 return true;
971 }
972
973 // We received the present fence from the HWC, so we assume it successfully updated
974 // the config, hence we update SF.
975 mCheckPendingFence = false;
976 setActiveConfigInternal();
977 }
978
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800979 // Store the local variable to release the lock.
980 ActiveConfigInfo desiredActiveConfig;
981 {
982 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800983 if (!mDesiredActiveConfigChanged) {
984 return false;
985 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800986 desiredActiveConfig = mDesiredActiveConfig;
987 }
988
Dominik Laskowski22488f62019-03-28 09:53:04 -0700989 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800990 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
991 // display is not valid or we are already in the requested mode
992 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -0700993 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800994 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800995 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800996
Ady Abraham838de062019-02-04 10:24:03 -0800997 // Desired active config was set, it is different than the config currently in use, however
998 // allowed configs might have change by the time we process the refresh.
999 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001000 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001001 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001002 return false;
1003 }
Alec Mouri7f015182019-07-11 13:56:22 -07001004
Ady Abrahamb838aed2019-02-12 15:30:16 -08001005 mUpcomingActiveConfig = desiredActiveConfig;
1006 const auto displayId = display->getId();
1007 LOG_ALWAYS_FATAL_IF(!displayId);
1008
1009 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1010 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1011
1012 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001013 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001014 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001015 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001016}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001017
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001018status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1019 Vector<ColorMode>* outColorModes) {
1020 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001021 return BAD_VALUE;
1022 }
1023
Peiyong Lina52f0292018-03-14 17:26:31 -07001024 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001025 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001026 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001027 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1028
1029 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1030 if (!displayId) {
1031 return NAME_NOT_FOUND;
1032 }
1033
Dominik Laskowski075d3172018-05-24 15:50:06 -07001034 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001035 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001036 }
Michael Wright28f24d02016-07-12 13:30:53 -07001037 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001038
1039 // If it's built-in display and the configuration claims it's not wide color capable,
1040 // filter out all wide color modes. The typical reason why this happens is that the
1041 // hardware is not good enough to support GPU composition of wide color, and thus the
1042 // OEMs choose to disable this capability.
1043 if (isInternalDisplay && !hasWideColorDisplay) {
1044 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1045 isWideColorMode);
1046 } else {
1047 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1048 }
Michael Wright28f24d02016-07-12 13:30:53 -07001049
1050 return NO_ERROR;
1051}
1052
Daniel Solomon42d04562019-01-20 21:03:19 -08001053status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1054 ui::DisplayPrimaries &primaries) {
1055 if (!displayToken) {
1056 return BAD_VALUE;
1057 }
1058
1059 // Currently we only support this API for a single internal display.
1060 if (getInternalDisplayToken() != displayToken) {
1061 return BAD_VALUE;
1062 }
1063
1064 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1065 return NO_ERROR;
1066}
1067
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001068ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1069 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001070 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001071 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001072 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001073}
1074
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001075status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001076 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001077 Vector<ColorMode> modes;
1078 getDisplayColorModes(displayToken, &modes);
1079 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1080 if (mode < ColorMode::NATIVE || !exists) {
1081 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1082 decodeColorMode(mode).c_str(), mode, displayToken.get());
1083 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001084 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001085 const auto display = getDisplayDevice(displayToken);
1086 if (!display) {
1087 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1088 decodeColorMode(mode).c_str(), mode, displayToken.get());
1089 } else if (display->isVirtual()) {
1090 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1091 decodeColorMode(mode).c_str(), mode);
1092 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001093 display->getCompositionDisplay()->setColorProfile(
1094 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1095 RenderIntent::COLORIMETRIC,
1096 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001097 }
1098 }));
1099
Michael Wright28f24d02016-07-12 13:30:53 -07001100 return NO_ERROR;
1101}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001102
Svetoslavd85084b2014-03-20 10:28:31 -07001103status_t SurfaceFlinger::clearAnimationFrameStats() {
1104 Mutex::Autolock _l(mStateLock);
1105 mAnimFrameTracker.clearStats();
1106 return NO_ERROR;
1107}
1108
1109status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1110 Mutex::Autolock _l(mStateLock);
1111 mAnimFrameTracker.getStats(outStats);
1112 return NO_ERROR;
1113}
1114
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001115status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1116 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001117 Mutex::Autolock _l(mStateLock);
1118
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001119 const auto display = getDisplayDeviceLocked(displayToken);
1120 if (!display) {
1121 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001122 return BAD_VALUE;
1123 }
1124
Peiyong Linfb069302018-04-25 14:34:31 -07001125 // At this point the DisplayDeivce should already be set up,
1126 // meaning the luminance information is already queried from
1127 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001129 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1130 capabilities.getDesiredMaxLuminance(),
1131 capabilities.getDesiredMaxAverageLuminance(),
1132 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001133
1134 return NO_ERROR;
1135}
1136
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001137status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1138 ui::PixelFormat* outFormat,
1139 ui::Dataspace* outDataspace,
1140 uint8_t* outComponentMask) const {
1141 if (!outFormat || !outDataspace || !outComponentMask) {
1142 return BAD_VALUE;
1143 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001144 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001145 if (!display || !display->getId()) {
1146 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1147 return BAD_VALUE;
1148 }
1149 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1150 outDataspace, outComponentMask);
1151}
1152
Kevin DuBois74e53772018-11-19 10:52:38 -08001153status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1154 bool enable, uint8_t componentMask,
1155 uint64_t maxFrames) const {
1156 const auto display = getDisplayDevice(displayToken);
1157 if (!display || !display->getId()) {
1158 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1159 return BAD_VALUE;
1160 }
1161
1162 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1163 componentMask, maxFrames);
1164}
1165
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001166status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1167 uint64_t maxFrames, uint64_t timestamp,
1168 DisplayedFrameStats* outStats) const {
1169 const auto display = getDisplayDevice(displayToken);
1170 if (!display || !display->getId()) {
1171 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1172 return BAD_VALUE;
1173 }
1174
1175 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1176 outStats);
1177}
1178
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001179status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1180 if (!outSupported) {
1181 return BAD_VALUE;
1182 }
1183 *outSupported = getRenderEngine().supportsProtectedContent();
1184 return NO_ERROR;
1185}
1186
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001187status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1188 bool* outIsWideColorDisplay) const {
1189 if (!displayToken || !outIsWideColorDisplay) {
1190 return BAD_VALUE;
1191 }
1192 Mutex::Autolock _l(mStateLock);
1193 const auto display = getDisplayDeviceLocked(displayToken);
1194 if (!display) {
1195 return BAD_VALUE;
1196 }
Peiyong Linff84a152019-05-17 18:36:19 -07001197
1198 // Use hasWideColorDisplay to override built-in display.
1199 const auto displayId = display->getId();
1200 if (displayId && displayId == getInternalDisplayIdLocked()) {
1201 *outIsWideColorDisplay = hasWideColorDisplay;
1202 return NO_ERROR;
1203 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001204 *outIsWideColorDisplay = display->hasWideColorGamut();
1205 return NO_ERROR;
1206}
1207
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001208status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001209 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001210 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001211
Dominik Laskowski6505f792019-09-18 11:10:05 -07001212 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1213 mEventQueue->setEventConnection(
1214 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001215 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001216 }));
1217
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001218 return NO_ERROR;
1219}
1220
1221status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001222 Mutex::Autolock lock(mStateLock);
1223 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001224}
1225
Lloyd Pique755e3192018-01-31 16:46:15 -08001226status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1227 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001228 // Try to acquire a lock for 1s, fail gracefully
1229 const status_t err = mStateLock.timedLock(s2ns(1));
1230 const bool locked = (err == NO_ERROR);
1231 if (!locked) {
1232 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1233 return TIMED_OUT;
1234 }
1235
1236 outLayers->clear();
1237 mCurrentState.traverseInZOrder([&](Layer* layer) {
1238 outLayers->push_back(layer->getLayerDebugInfo());
1239 });
1240
1241 mStateLock.unlock();
1242 return NO_ERROR;
1243}
1244
Peiyong Linc6780972018-10-28 15:24:08 -07001245status_t SurfaceFlinger::getCompositionPreference(
1246 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1247 Dataspace* outWideColorGamutDataspace,
1248 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001249 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001250 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001251 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001252 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001253 return NO_ERROR;
1254}
1255
Dan Stozaec460082018-12-17 15:35:09 -08001256status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1257 const sp<IBinder>& stopLayerHandle,
1258 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001259 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001260 return BAD_VALUE;
1261 }
1262 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001263 return NO_ERROR;
1264}
1265
Dan Stozaec460082018-12-17 15:35:09 -08001266status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001267 if (!listener) {
1268 return BAD_VALUE;
1269 }
Dan Stozaec460082018-12-17 15:35:09 -08001270 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001271 return NO_ERROR;
1272}
Dan Gittik57e63c52019-01-18 16:37:54 +00001273
1274status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1275 bool* outSupport) const {
1276 if (!displayToken || !outSupport) {
1277 return BAD_VALUE;
1278 }
1279 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1280 if (!displayId) {
1281 return NAME_NOT_FOUND;
1282 }
1283 *outSupport =
1284 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1285 return NO_ERROR;
1286}
1287
1288status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1289 float brightness) const {
1290 if (!displayToken) {
1291 return BAD_VALUE;
1292 }
1293 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1294 if (!displayId) {
1295 return NAME_NOT_FOUND;
1296 }
1297 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1298}
1299
Ady Abraham8532d012019-05-08 14:50:56 -07001300status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1301 PowerHint powerHint = static_cast<PowerHint>(hintId);
1302
1303 if (powerHint == PowerHint::INTERACTION) {
1304 mScheduler->notifyTouchEvent();
1305 }
1306
1307 return NO_ERROR;
1308}
1309
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001310// ----------------------------------------------------------------------------
1311
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001312sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001313 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001314 const auto& handle =
1315 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001316
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001317 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001318}
1319
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001320// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001321
1322void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001323 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001324}
1325
1326void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001327 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001328 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001329}
1330
1331void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001332 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001333 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001334}
1335
1336void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001337 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001338 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001339}
1340
1341status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001342 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001343 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001344}
1345
1346status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001347 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001348 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001349 if (res == NO_ERROR) {
1350 msg->wait();
1351 }
1352 return res;
1353}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001354
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001355void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001356 do {
1357 waitForEvent();
1358 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001359}
1360
Dominik Laskowski83b88212018-12-11 13:34:06 -08001361nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001362 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001363 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1364 return 0;
1365 }
1366
1367 const auto config = getHwComposer().getActiveConfig(*displayId);
1368 return config ? config->getVsyncPeriod() : 0;
1369}
1370
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001371void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1372 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001373 ATRACE_NAME("SF onVsync");
1374
Steven Thomas3cfac282017-02-06 12:29:30 -08001375 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001376 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001377 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001378 return;
1379 }
1380
Dominik Laskowski075d3172018-05-24 15:50:06 -07001381 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001382 return;
1383 }
1384
Dominik Laskowski075d3172018-05-24 15:50:06 -07001385 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001386 // For now, we don't do anything with external display vsyncs.
1387 return;
1388 }
1389
Alec Mourif8e689c2019-05-20 18:32:22 -07001390 bool periodFlushed = false;
1391 mScheduler->addResyncSample(timestamp, &periodFlushed);
1392 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001393 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001394 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001395}
1396
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001397void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001398 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1399 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001400}
1401
Ady Abraham261614e2019-07-10 17:53:12 -07001402bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001403 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001404}
1405
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001406void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001407 const auto display = getDefaultDisplayDeviceLocked();
1408 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001409 return;
1410 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001411 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001412
Ana Krulec7d1d6832018-12-27 11:10:09 -08001413 // Don't do any updating if the current fps is the same as the new one.
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001414 const auto& refreshRateConfig = mRefreshRateConfigs->getRefreshRateFromType(refreshRate);
1415 const int desiredConfigId = refreshRateConfig.configId;
Alec Mouri0a1cc962019-03-14 12:33:02 -07001416
Dominik Laskowski22488f62019-03-28 09:53:04 -07001417 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001418 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1419 return;
1420 }
1421
Dominik Laskowski22488f62019-03-28 09:53:04 -07001422 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001423}
1424
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001425void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001426 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001427 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001428 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001429
Lloyd Piqueba04e622017-12-14 17:11:26 -08001430 // Ignore events that do not have the right sequenceId.
1431 if (sequenceId != getBE().mComposerSequenceId) {
1432 return;
1433 }
1434
Steven Thomasb02664d2017-07-26 18:48:28 -07001435 // Only lock if we're not on the main thread. This function is normally
1436 // called on a hwbinder thread, but for the primary display it's called on
1437 // the main thread with the state lock already held, so don't attempt to
1438 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001439 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001440
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001441 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001442
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001443 if (std::this_thread::get_id() == mMainThreadId) {
1444 // Process all pending hot plug events immediately if we are on the main thread.
1445 processDisplayHotplugEventsLocked();
1446 }
1447
Lloyd Piqueba04e622017-12-14 17:11:26 -08001448 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001449}
1450
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001451void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001452 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001453 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001454 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001455 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001456 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001457}
1458
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001459void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001460 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001461
1462 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1463 // display power state.
1464 postMessageAsync(new LambdaMessage(
1465 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1466}
1467
1468void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1469 ATRACE_CALL();
1470
Ady Abraham27c70212019-06-11 10:52:26 -07001471 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1472
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001473 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001474 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1475 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001476 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001477 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001478 }
Mathias Agopian86303202012-07-24 22:46:10 -07001479}
1480
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001481// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001482void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001483 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001484 // Clear the drawing state so that the logic inside of
1485 // handleTransactionLocked will fire. It will determine the delta between
1486 // mCurrentState and mDrawingState and re-apply all changes when we make the
1487 // transition.
1488 mDrawingState.displays.clear();
1489 mDisplays.clear();
1490}
1491
Steven Thomas050b2c82017-03-06 11:45:16 -08001492void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001493 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001494 if (!mVrFlinger)
1495 return;
1496 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001497 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001498 return;
1499 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001500
Lloyd Pique441d5042018-10-18 16:49:51 -07001501 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001502 ALOGE("Vr flinger is only supported for remote hardware composer"
1503 " service connections. Ignoring request to transition to vr"
1504 " flinger.");
1505 mVrFlingerRequestsDisplay = false;
1506 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001507 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001508
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001509 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001510
Steven Thomas0123ac62018-07-12 11:32:34 -07001511 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001512 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001513
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001514 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001515
1516 // Clear out all the output layers from the composition engine for all
1517 // displays before destroying the hardware composer interface. This ensures
1518 // any HWC layers are destroyed through that interface before it becomes
1519 // invalid.
1520 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001521 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001522 }
1523
Steven Thomas0123ac62018-07-12 11:32:34 -07001524 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1525 // called below. Clear the reference now so we don't accidentally use it
1526 // later.
1527 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001528
Steven Thomasb02664d2017-07-26 18:48:28 -07001529 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001530 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001531 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001532
Steven Thomasb02664d2017-07-26 18:48:28 -07001533 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001534 // Delete the current instance before creating the new one
1535 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1536 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1537 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1538 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001539
Lloyd Pique441d5042018-10-18 16:49:51 -07001540 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001541 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001542
1543 if (vrFlingerRequestsDisplay) {
1544 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001545 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001546
1547 mVisibleRegionsDirty = true;
1548 invalidateHwcGeometry();
1549
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001550 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001551 display = getDefaultDisplayDeviceLocked();
1552 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001553 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001554
Steven Thomasb02664d2017-07-26 18:48:28 -07001555 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001556 const nsecs_t vsyncPeriod = getVsyncPeriod();
1557 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001558
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001559 // The present fences returned from vr_hwc are not an accurate
1560 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001561 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001562
Steven Thomasb02664d2017-07-26 18:48:28 -07001563 // Use phase of 0 since phase is not known.
1564 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001565 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001566 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001567
Ana Krulecc2870422019-01-29 19:00:58 -08001568 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001569
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001570 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001571 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001572}
1573
Ady Abraham11579302019-09-19 12:35:58 -07001574bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1575 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001576 // We are storing the last 2 present fences. If sf's phase offset is to be
1577 // woken up before the actual vsync but targeting the next vsync, we need to check
1578 // fence N-2
1579 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001580 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001581 ? mPreviousPresentFences[0]
1582 : mPreviousPresentFences[1];
1583
Ady Abraham11579302019-09-19 12:35:58 -07001584 if (fence == Fence::NO_FENCE) {
1585 return false;
1586 }
1587
1588 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1589 fence->wait(graceTimeMs);
1590 }
1591
1592 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001593}
1594
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001595void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001596 DisplayStatInfo stats;
1597 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001598 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001599 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001600 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001601 mPhaseOffsets->getOffsetThresholdForNextVsync()
1602 ? presentTime
1603 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001604}
1605
Dominik Laskowski22488f62019-03-28 09:53:04 -07001606void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001607 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001608 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001609 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001610 // calculate the expected present time once and use the cached
1611 // value throughout this frame to make sure all layers are
1612 // seeing this same value.
1613 populateExpectedPresentTime();
1614
Ady Abraham11579302019-09-19 12:35:58 -07001615 // When Backpressure propagation is enabled we want to give a small grace period
1616 // for the present fence to fire instead of just giving up on this frame to handle cases
1617 // where present fence is just about to get signaled.
1618 const int graceTimeForPresentFenceMs =
1619 (mPropagateBackpressure &&
1620 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1621 ? 1
1622 : 0;
1623 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1624 previousFrameMissed(
1625 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001626 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1627 mHadDeviceComposition && frameMissed};
1628 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1629 mHadClientComposition && frameMissed};
1630
Alec Mouricc0fc602019-02-26 21:45:19 -08001631 if (frameMissed) {
1632 mFrameMissedCount++;
1633 mTimeStats->incrementMissedFrames();
1634 }
1635
Alec Mouri40189b02019-03-05 15:07:54 -08001636 if (hwcFrameMissed) {
1637 mHwcFrameMissedCount++;
1638 }
1639
1640 if (gpuFrameMissed) {
1641 mGpuFrameMissedCount++;
1642 }
1643
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001644 if (mUseSmart90ForVideo) {
1645 // This call is made each time SF wakes up and creates a new frame. It is part
1646 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001647 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001648 }
1649
Ady Abrahamb838aed2019-02-12 15:30:16 -08001650 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001651 break;
1652 }
1653
Ady Abrahamadb9a992019-09-19 21:21:55 +00001654 if (frameMissed && mPropagateBackpressure) {
1655 if ((hwcFrameMissed && !gpuFrameMissed) ||
1656 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001657 signalLayerUpdate();
1658 break;
1659 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001660 }
Dan Stoza50182882016-07-08 12:02:20 -07001661
Steven Thomas050b2c82017-03-06 11:45:16 -08001662 // Now that we're going to make it to the handleMessageTransaction()
1663 // call below it's safe to call updateVrFlinger(), which will
1664 // potentially trigger a display handoff.
1665 updateVrFlinger();
1666
Dan Stoza6b9454d2014-11-07 16:00:59 -08001667 bool refreshNeeded = handleMessageTransaction();
1668 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001669
1670 updateCursorAsync();
1671 updateInputFlinger();
1672
Dan Stoza58784442014-12-02 16:58:17 -08001673 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001674 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001675 // Signal a refresh if a transaction modified the window state,
1676 // a new buffer was latched, or if HWC has requested a full
1677 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001678 signalRefresh();
1679 }
1680 break;
1681 }
1682 case MessageQueue::REFRESH: {
1683 handleMessageRefresh();
1684 break;
1685 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001686 }
1687}
1688
Dan Stoza6b9454d2014-11-07 16:00:59 -08001689bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001690 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001691 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001692
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001693 bool flushedATransaction = flushTransactionQueues();
1694
1695 bool runHandleTransaction = transactionFlags &&
1696 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1697
1698 if (runHandleTransaction) {
1699 handleTransaction(eTransactionMask);
1700 } else {
1701 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001702 }
1703
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001704 if (transactionFlushNeeded()) {
1705 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001706 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001707
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001708 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001709}
1710
Mathias Agopian4fec8732012-06-29 14:12:52 -07001711void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001712 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001713
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001714 mRefreshPending = false;
1715
Lloyd Piqueab039b52019-02-13 14:22:42 -08001716 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001717 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001718 for (const auto& [_, display] : mDisplays) {
1719 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1720 }
1721 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1722 auto compositionLayer = layer->getCompositionLayer();
1723 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1724 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001725 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1726 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1727 auto compositionLayer = layer->getCompositionLayer();
1728 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
1729 }
1730
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001731 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001732 refreshArgs.outputColorSetting = useColorManagement
1733 ? mDisplayColorSetting
1734 : compositionengine::OutputColorSetting::kUnmanaged;
1735 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1736 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001737
1738 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1739 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001740
1741 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1742 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1743 mDrawingState.colorMatrixChanged = false;
1744 }
1745
1746 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1747
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001748 if (mDebugRegion != 0) {
1749 refreshArgs.devOptFlashDirtyRegionsDelay =
1750 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1751 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001752
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001753 mGeometryInvalid = false;
1754
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001755 mCompositionEngine->present(refreshArgs);
1756
David Sodmanfa9b2af2017-12-24 13:28:59 -08001757 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001758 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001759
Lloyd Pique66d68602019-02-13 14:23:31 -08001760 mHadClientComposition =
1761 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1762 auto& displayDevice = tokenDisplayPair.second;
1763 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1764 });
1765 mHadDeviceComposition =
1766 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1767 auto& displayDevice = tokenDisplayPair.second;
1768 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1769 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001770
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001771 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001772
David Sodman7e4ae112018-02-09 15:02:28 -08001773 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001774 if (mVisibleRegionsDirty) {
1775 mVisibleRegionsDirty = false;
1776 if (mTracingEnabled) {
1777 mTracing.notify("visibleRegionsDirty");
1778 }
1779 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001780
1781 if (mCompositionEngine->needsAnotherUpdate()) {
1782 signalLayerUpdate();
1783 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001784}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001785
David Sodmanfa9b2af2017-12-24 13:28:59 -08001786
1787bool SurfaceFlinger::handleMessageInvalidate() {
1788 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001789 bool refreshNeeded = handlePageFlip();
1790
Vishnu Nair4351ad52019-02-11 14:13:02 -08001791 if (mVisibleRegionsDirty) {
1792 computeLayerBounds();
1793 }
1794
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001795 for (auto& layer : mLayersPendingRefresh) {
1796 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001797 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001798 invalidateLayerStack(layer, visibleReg);
1799 }
1800 mLayersPendingRefresh.clear();
1801 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001802}
1803
Ana Krulece588e312018-09-18 12:32:24 -07001804void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1805 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001806 // Update queue of past composite+present times and determine the
1807 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001808 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001809 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001810 while (!getBE().mCompositePresentTimes.empty()) {
1811 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001812 // Cached values should have been updated before calling this method,
1813 // which helps avoid duplicate syscalls.
1814 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1815 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1816 break;
1817 }
1818 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001819 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001820 }
1821
1822 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001823 while (getBE().mCompositePresentTimes.size() > 16) {
1824 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001825 }
1826
Ana Krulece588e312018-09-18 12:32:24 -07001827 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001828}
1829
Ana Krulece588e312018-09-18 12:32:24 -07001830void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1831 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001832 // Integer division and modulo round toward 0 not -inf, so we need to
1833 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001834 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1835 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1836 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001837
Ana Krulec757f63a2019-01-25 10:46:18 -08001838 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001839 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001840 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001841 }
1842
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001843 // Snap the latency to a value that removes scheduling jitter from the
1844 // composition and present times, which often have >1ms of jitter.
1845 // Reducing jitter is important if an app attempts to extrapolate
1846 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001847 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001848 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001849 nsecs_t bias = stats.vsyncPeriod / 2;
1850 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1851 nsecs_t snappedCompositeToPresentLatency =
1852 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001853
David Sodman99974d22017-11-28 12:04:33 -08001854 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001855 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1856 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001857 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001858}
1859
David Sodman2b406362017-12-15 13:33:47 -08001860void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001861{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001862 ATRACE_CALL();
1863 ALOGV("postComposition");
1864
Brian Anderson3546a3f2016-07-14 11:51:14 -07001865 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001866 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001867 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001868 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001869 }
1870
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001871 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001872 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001873
David Sodman73beded2017-11-15 11:56:06 -08001874 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001875 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08001876 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001877 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001878 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1879 ->getRenderSurface()
1880 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001881 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001882 } else {
1883 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1884 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001885
David Sodman73beded2017-11-15 11:56:06 -08001886 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001887 mPreviousPresentFences[1] = mPreviousPresentFences[0];
1888 mPreviousPresentFences[0] = displayDevice
1889 ? getHwComposer().getPresentFence(*displayDevice->getId())
1890 : Fence::NO_FENCE;
1891 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08001892 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001893
Ana Krulece588e312018-09-18 12:32:24 -07001894 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08001895 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001896
Lloyd Piqueab039b52019-02-13 14:22:42 -08001897 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
1898 // be sampled a little later than when we started doing work for this frame,
1899 // but that should be okay since updateCompositorTiming has snapping logic.
1900 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
1901 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001902 CompositorTiming compositorTiming;
1903 {
David Sodman99974d22017-11-28 12:04:33 -08001904 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1905 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001906 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001907
Robert Carr2047fae2016-11-28 14:09:09 -08001908 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001909 bool frameLatched =
1910 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
1911 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001912 if (frameLatched) {
Robert Carr2047fae2016-11-28 14:09:09 -08001913 recordBufferingStats(layer->getName().string(),
1914 layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001915 }
Robert Carr2047fae2016-11-28 14:09:09 -08001916 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001917
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001918 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001919 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001920 }
1921
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001922 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001923 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1924 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001925 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001926 }
1927 }
1928
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001929 if (mAnimCompositionPending) {
1930 mAnimCompositionPending = false;
1931
Brian Anderson4e606e32017-03-16 15:34:57 -07001932 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001933 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001934 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07001935 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001936 // The HWC doesn't support present fences, so use the refresh
1937 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07001938 const nsecs_t presentTime =
1939 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001940 mAnimFrameTracker.setActualPresentTime(presentTime);
1941 }
1942 mAnimFrameTracker.advanceFrame();
1943 }
Dan Stozab90cf072015-03-05 11:05:59 -08001944
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001945 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001946 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001947 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001948 }
1949
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001950 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001951
Lloyd Pique32cbe282018-10-19 13:09:22 -07001952 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1953 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001954 return;
1955 }
1956
1957 nsecs_t currentTime = systemTime();
1958 if (mHasPoweredOff) {
1959 mHasPoweredOff = false;
1960 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001961 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001962 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001963 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1964 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001965 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001966 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001967 }
David Sodman4a36e932017-11-07 14:29:47 -08001968 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001969 }
David Sodman4a36e932017-11-07 14:29:47 -08001970 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001971
1972 {
1973 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07001974 if (mTexturePool.size() < mTexturePoolSize) {
1975 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07001976 const size_t offset = mTexturePool.size();
1977 mTexturePool.resize(mTexturePoolSize);
1978 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1979 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07001980 } else if (mTexturePool.size() > mTexturePoolSize) {
1981 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
1982 const size_t offset = mTexturePoolSize;
1983 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
1984 mTexturePool.resize(mTexturePoolSize);
1985 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07001986 }
1987 }
Marissa Walle2ffb422018-10-12 11:33:52 -07001988
Ady Abrahambe0f9482019-04-24 15:41:53 -07001989 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07001990 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08001991
Kevin DuBois413287f2019-02-25 08:46:47 -08001992 if (mLumaSampling && mRegionSamplingThread) {
1993 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08001994 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07001995
1996 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
1997 // side-effect of getTotalSize(), so we check that again here
1998 if (ATRACE_ENABLED()) {
1999 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2000 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002001}
2002
Vishnu Nair4351ad52019-02-11 14:13:02 -08002003void SurfaceFlinger::computeLayerBounds() {
2004 for (const auto& pair : mDisplays) {
2005 const auto& displayDevice = pair.second;
2006 const auto display = displayDevice->getCompositionDisplay();
2007 for (const auto& layer : mDrawingState.layersSortedByZ) {
2008 // only consider the layers on the given layer stack
2009 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002010 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002011 }
2012
2013 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2014 }
2015 }
2016}
2017
David Sodmanfa9b2af2017-12-24 13:28:59 -08002018void SurfaceFlinger::postFrame()
2019{
2020 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002021 const auto display = getDefaultDisplayDeviceLocked();
2022 if (display && getHwComposer().isConnected(*display->getId())) {
2023 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002024 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2025 logFrameStats();
2026 }
2027 }
2028}
2029
Mathias Agopian87baae12012-07-31 12:38:26 -07002030void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002031{
Mathias Agopian841cde52012-03-01 15:44:37 -08002032 ATRACE_CALL();
2033
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002034 // here we keep a copy of the drawing state (that is the state that's
2035 // going to be overwritten by handleTransactionLocked()) outside of
2036 // mStateLock so that the side-effects of the State assignment
2037 // don't happen with mStateLock held (which can cause deadlocks).
2038 State drawingState(mDrawingState);
2039
Mathias Agopianca4d3602011-05-19 15:38:14 -07002040 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002041 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002042
Mathias Agopianca4d3602011-05-19 15:38:14 -07002043 // Here we're guaranteed that some transaction flags are set
2044 // so we can call handleTransactionLocked() unconditionally.
2045 // We call getTransactionFlags(), which will also clear the flags,
2046 // with mStateLock held to guarantee that mCurrentState won't change
2047 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002048
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002049 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002050 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002051 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002052
Mathias Agopianca4d3602011-05-19 15:38:14 -07002053 mDebugInTransaction = 0;
2054 invalidateHwcGeometry();
2055 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002056}
2057
Lloyd Piqueba04e622017-12-14 17:11:26 -08002058void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2059 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002060 const std::optional<DisplayIdentificationInfo> info =
2061 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002062
Dominik Laskowski075d3172018-05-24 15:50:06 -07002063 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002064 continue;
2065 }
2066
Lloyd Piqueba04e622017-12-14 17:11:26 -08002067 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002068 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002069 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002070 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2071 initScheduler(info->id);
2072 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002073 mPhysicalDisplayTokens[info->id] = new BBinder();
2074 DisplayDeviceState state;
2075 state.displayId = info->id;
2076 state.isSecure = true; // All physical displays are currently considered secure.
2077 state.displayName = info->name;
2078 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2079 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002080 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002081 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002082 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002083
Dominik Laskowski075d3172018-05-24 15:50:06 -07002084 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2085 if (index >= 0) {
2086 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2087 mInterceptor->saveDisplayDeletion(state.sequenceId);
2088 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002089 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002090 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002091 }
2092
2093 processDisplayChangesLocked();
2094 }
2095
2096 mPendingHotplugEvents.clear();
2097}
2098
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002099void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002100 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2101 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002102}
2103
Lloyd Pique99d3da52018-01-22 17:48:03 -08002104sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002105 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002106 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002107 const sp<IGraphicBufferProducer>& producer) {
2108 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002109 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002110 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002111 creationArgs.isSecure = state.isSecure;
2112 creationArgs.displaySurface = dispSurface;
2113 creationArgs.hasWideColorGamut = false;
2114 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002115 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002116
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002117 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002118 creationArgs.isPrimary = isInternalDisplay;
2119
2120 if (useColorManagement && displayId) {
2121 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002122 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002123 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002124 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002125 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002126
Dominik Laskowski7e045462018-05-30 13:02:02 -07002127 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002128 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002129 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002130 }
tangrobin6753a022018-08-10 10:58:54 +08002131 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002132
Dominik Laskowski075d3172018-05-24 15:50:06 -07002133 if (displayId) {
2134 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002135 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002136 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002137 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002138
Lloyd Pique90c115d2018-09-18 21:39:42 -07002139 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002140 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002141 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002142
Lloyd Pique99d3da52018-01-22 17:48:03 -08002143 // Make sure that composition can never be stalled by a virtual display
2144 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002145 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002146 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002147 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2148 }
2149
Dominik Laskowski075d3172018-05-24 15:50:06 -07002150 creationArgs.displayInstallOrientation =
2151 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002152
Lloyd Pique99d3da52018-01-22 17:48:03 -08002153 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002154 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002155
Lloyd Pique90c115d2018-09-18 21:39:42 -07002156 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002157
2158 if (maxFrameBufferAcquiredBuffers >= 3) {
2159 nativeWindowSurface->preallocateBuffers();
2160 }
2161
2162 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002163 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002164 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002165 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002166 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002167 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002168 display->getCompositionDisplay()->setColorProfile(
2169 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2170 RenderIntent::COLORIMETRIC,
2171 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002172 if (!state.isVirtual()) {
2173 LOG_ALWAYS_FATAL_IF(!displayId);
2174 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002175 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002176
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002177 display->setLayerStack(state.layerStack);
2178 display->setProjection(state.orientation, state.viewport, state.frame);
2179 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002180
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002181 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002182}
2183
Lloyd Pique347200f2017-12-14 17:00:15 -08002184void SurfaceFlinger::processDisplayChangesLocked() {
2185 // here we take advantage of Vector's copy-on-write semantics to
2186 // improve performance by skipping the transaction entirely when
2187 // know that the lists are identical
2188 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2189 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2190 if (!curr.isIdenticalTo(draw)) {
2191 mVisibleRegionsDirty = true;
2192 const size_t cc = curr.size();
2193 size_t dc = draw.size();
2194
2195 // find the displays that were removed
2196 // (ie: in drawing state but not in current state)
2197 // also handle displays that changed
2198 // (ie: displays that are in both lists)
2199 for (size_t i = 0; i < dc;) {
2200 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2201 if (j < 0) {
2202 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002203 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002204 // Save display ID before disconnecting.
2205 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002206 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002207
2208 if (!display->isVirtual()) {
2209 LOG_ALWAYS_FATAL_IF(!displayId);
2210 dispatchDisplayHotplugEvent(displayId->value, false);
2211 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002212 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002213
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002214 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002215 } else {
2216 // this display is in both lists. see if something changed.
2217 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002218 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002219 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2220 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2221 if (state_binder != draw_binder) {
2222 // changing the surface is like destroying and
2223 // recreating the DisplayDevice, so we just remove it
2224 // from the drawing state, so that it get re-added
2225 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002226 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002227 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002228 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002229 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002230 mDrawingState.displays.removeItemsAt(i);
2231 dc--;
2232 // at this point we must loop to the next item
2233 continue;
2234 }
2235
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002236 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002237 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002238 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002239 }
2240 if ((state.orientation != draw[i].orientation) ||
2241 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002242 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002243 }
2244 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002245 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002246 }
2247 }
2248 }
2249 ++i;
2250 }
2251
2252 // find displays that were added
2253 // (ie: in current state but not in drawing state)
2254 for (size_t i = 0; i < cc; i++) {
2255 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2256 const DisplayDeviceState& state(curr[i]);
2257
Lloyd Pique542307f2018-10-19 13:24:08 -07002258 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002259 sp<IGraphicBufferProducer> producer;
2260 sp<IGraphicBufferProducer> bqProducer;
2261 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002262 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002263
Dominik Laskowski075d3172018-05-24 15:50:06 -07002264 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002265 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002266 // Virtual displays without a surface are dormant:
2267 // they have external state (layer stack, projection,
2268 // etc.) but no internal state (i.e. a DisplayDevice).
2269 if (state.surface != nullptr) {
2270 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002271 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002272 int width = 0;
2273 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2274 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2275 int height = 0;
2276 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2277 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2278 int intFormat = 0;
2279 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2280 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002281 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002282
Dominik Laskowski075d3172018-05-24 15:50:06 -07002283 displayId =
2284 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002285 }
2286
2287 // TODO: Plumb requested format back up to consumer
2288
2289 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002290 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002291 bqProducer, bqConsumer,
2292 state.displayName);
2293
2294 dispSurface = vds;
2295 producer = vds;
2296 }
2297 } else {
2298 ALOGE_IF(state.surface != nullptr,
2299 "adding a supported display, but rendering "
2300 "surface is provided (%p), ignoring it",
2301 state.surface.get());
2302
Dominik Laskowski075d3172018-05-24 15:50:06 -07002303 displayId = state.displayId;
2304 LOG_ALWAYS_FATAL_IF(!displayId);
2305 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002306 producer = bqProducer;
2307 }
2308
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002309 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002310 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002311 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002312 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002313 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002314 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002315 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002316 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002317 }
2318 }
2319 }
2320 }
2321 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002322
2323 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002324}
2325
Mathias Agopian87baae12012-07-31 12:38:26 -07002326void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002327{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002328 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2329
Dan Stoza7dde5992015-05-22 09:51:44 -07002330 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002331 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2332 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002333 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002334
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002335 /*
2336 * Traversal of the children
2337 * (perform the transaction for each of them if needed)
2338 */
2339
Marissa Wall06255332019-03-27 13:48:27 -07002340 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002341 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002342 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002343 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344
2345 const uint32_t flags = layer->doTransaction(0);
2346 if (flags & Layer::eVisibleRegion)
2347 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002348
2349 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002350 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002351 }
Robert Carr2047fae2016-11-28 14:09:09 -08002352 });
Marissa Wall06255332019-03-27 13:48:27 -07002353 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002354 }
2355
2356 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002357 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002358 */
2359
Mathias Agopiane57f2922012-08-09 16:29:12 -07002360 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002361 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002362 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002363 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002365 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002366 // The transform hint might have changed for some layers
2367 // (either because a display has changed, or because a layer
2368 // as changed).
2369 //
2370 // Walk through all the layers in currentLayers,
2371 // and update their transform hint.
2372 //
2373 // If a layer is visible only on a single display, then that
2374 // display is used to calculate the hint, otherwise we use the
2375 // default display.
2376 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002377 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002378 // the hint is set before we acquire a buffer from the surface texture.
2379 //
2380 // NOTE: layer transactions have taken place already, so we use their
2381 // drawing state. However, SurfaceFlinger's own transaction has not
2382 // happened yet, so we must use the current state layer list
2383 // (soon to become the drawing state list).
2384 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002385 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002386 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002387 bool first = true;
2388 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002389 // NOTE: we rely on the fact that layers are sorted by
2390 // layerStack first (so we don't have to traverse the list
2391 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002392 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002393 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002394 currentlayerStack = layerStack;
2395 // figure out if this layerstack is mirrored
2396 // (more than one display) if so, pick the default display,
2397 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002398 hintDisplay = nullptr;
2399 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002400 if (display->getCompositionDisplay()
2401 ->belongsInOutput(layer->getLayerStack(),
2402 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002403 if (hintDisplay) {
2404 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002405 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002406 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002407 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002408 }
2409 }
2410 }
2411 }
Chet Haase91d25932013-04-11 15:24:55 -07002412
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002413 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002414 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2415 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002416
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002417 // could be null when this layer is using a layerStack
2418 // that is not visible on any display. Also can occur at
2419 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002420 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002421 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002422
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002423 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002424 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002425 if (hintDisplay) {
2426 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002427 }
Robert Carr2047fae2016-11-28 14:09:09 -08002428
2429 first = false;
2430 });
Mathias Agopian84300952012-11-21 16:02:13 -08002431 }
2432
2433
Mathias Agopian3559b072012-08-15 13:46:03 -07002434 /*
2435 * Perform our own transaction if needed
2436 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002437
2438 if (mLayersAdded) {
2439 mLayersAdded = false;
2440 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002441 mVisibleRegionsDirty = true;
2442 }
2443
2444 // some layers might have been removed, so
2445 // we need to update the regions they're exposing.
2446 if (mLayersRemoved) {
2447 mLayersRemoved = false;
2448 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002449 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002450 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002451 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002452 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002453 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002454 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002455 }
Robert Carr2047fae2016-11-28 14:09:09 -08002456 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002457 }
2458
Vishnu Nairec0ab382019-02-13 15:32:56 -08002459 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002460 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002461}
2462
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002463void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002464 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002465 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002466 return;
2467 }
2468
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002469 if (mVisibleRegionsDirty || mInputInfoChanged) {
2470 mInputInfoChanged = false;
2471 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002472 } else if (mInputWindowCommands.syncInputWindows) {
2473 // If the caller requested to sync input windows, but there are no
2474 // changes to input windows, notify immediately.
2475 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002476 }
2477
Arthur Hung6cbb9752019-09-05 16:38:18 +08002478 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002479}
2480
2481void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002482 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002483
2484 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2485 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002486 // When calculating the screen bounds we ignore the transparent region since it may
2487 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002488 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002489 }
2490 });
chaviw291d88a2019-02-14 10:33:58 -08002491
2492 mInputFlinger->setInputWindows(inputHandles,
2493 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2494 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002495}
2496
Vishnu Nairec0ab382019-02-13 15:32:56 -08002497void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002498 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002499 mPendingInputWindowCommands.clear();
2500}
2501
Riley Andrews03414a12014-07-01 14:22:59 -07002502void SurfaceFlinger::updateCursorAsync()
2503{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002504 compositionengine::CompositionRefreshArgs refreshArgs;
2505 for (const auto& [_, display] : mDisplays) {
2506 if (display->getId()) {
2507 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002508 }
2509 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002510
2511 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002512}
2513
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002514void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2515 if (mScheduler) {
2516 // In practice it's not allowed to hotplug in/out the primary display once it's been
2517 // connected during startup, but some tests do it, so just warn and return.
2518 ALOGW("Can't re-init scheduler");
2519 return;
2520 }
2521
2522 int currentConfig = getHwComposer().getActiveConfigIndex(primaryDisplayId);
2523 mRefreshRateConfigs =
2524 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2525 getHwComposer().getConfigs(
2526 primaryDisplayId),
2527 currentConfig);
2528 mRefreshRateStats =
2529 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2530 currentConfig, HWC_POWER_MODE_OFF);
2531 mRefreshRateStats->setConfigMode(currentConfig);
2532
2533 // start the EventThread
2534 mScheduler =
2535 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
2536 *mRefreshRateConfigs);
2537 mAppConnectionHandle =
2538 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
2539 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2540 impl::EventThread::InterceptVSyncsCallback());
2541 mSfConnectionHandle =
2542 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
2543 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2544 [this](nsecs_t timestamp) {
2545 mInterceptor->saveVSyncEvent(timestamp);
2546 });
2547
2548 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2549 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
2550 mPhaseOffsets->getCurrentOffsets());
2551
2552 mRegionSamplingThread =
2553 new RegionSamplingThread(*this, *mScheduler,
2554 RegionSamplingThread::EnvironmentTimingTunables());
2555
2556 mScheduler->setChangeRefreshRateCallback(
2557 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
2558 Mutex::Autolock lock(mStateLock);
2559 setRefreshRateTo(type, event);
2560 });
2561}
2562
Mathias Agopian4fec8732012-06-29 14:12:52 -07002563void SurfaceFlinger::commitTransaction()
2564{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002565 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002566
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002567 mTransactionPending = false;
2568 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002569 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002570}
2571
Lloyd Pique58e24a32019-08-01 15:50:14 -07002572void SurfaceFlinger::commitTransactionLocked() {
2573 if (!mLayersPendingRemoval.isEmpty()) {
2574 // Notify removed layers now that they can't be drawn from
2575 for (const auto& l : mLayersPendingRemoval) {
2576 recordBufferingStats(l->getName().string(), l->getOccupancyHistory(true));
2577
2578 // Ensure any buffers set to display on any children are released.
2579 if (l->isRemovedFromCurrentState()) {
2580 l->latchAndReleaseBuffer();
2581 }
2582
2583 // If the layer has been removed and has no parent, then it will not be reachable
2584 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2585 // ensure we can copy its current to drawing state.
2586 if (!l->getParent()) {
2587 mOffscreenLayers.emplace(l.get());
2588 }
2589 }
2590 mLayersPendingRemoval.clear();
2591 }
2592
2593 // If this transaction is part of a window animation then the next frame
2594 // we composite should be considered an animation as well.
2595 mAnimCompositionPending = mAnimTransactionPending;
2596
2597 mDrawingState = mCurrentState;
2598 // clear the "changed" flags in current state
2599 mCurrentState.colorMatrixChanged = false;
2600
2601 mDrawingState.traverseInZOrder([&](Layer* layer) {
2602 layer->commitChildList();
2603
2604 // If the layer can be reached when traversing mDrawingState, then the layer is no
2605 // longer offscreen. Remove the layer from the offscreenLayer set.
2606 if (mOffscreenLayers.count(layer)) {
2607 mOffscreenLayers.erase(layer);
2608 }
2609 });
2610
2611 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002612 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002613}
2614
Nataniel Borges2b796da2019-02-15 13:32:18 -08002615void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2616 if (mTracingEnabledChanged) {
2617 mTracingEnabled = mTracing.isEnabled();
2618 mTracingEnabledChanged = false;
2619 }
2620
2621 // Synchronize with Tracing thread
2622 std::unique_lock<std::mutex> lock;
2623 if (mTracingEnabled) {
2624 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2625 }
2626
2627 lockedOperation();
2628
2629 // Synchronize with Tracing thread
2630 if (mTracingEnabled) {
2631 lock.unlock();
2632 }
2633}
2634
chaviw74d90ad2019-04-26 14:45:26 -07002635void SurfaceFlinger::commitOffscreenLayers() {
2636 for (Layer* offscreenLayer : mOffscreenLayers) {
2637 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2638 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2639 if (!trFlags) return;
2640
2641 layer->doTransaction(0);
2642 layer->commitChildList();
2643 });
2644 }
2645}
2646
Chia-I Wuab0c3192017-08-01 11:29:00 -07002647void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002648 for (const auto& [token, displayDevice] : mDisplays) {
2649 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002650 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002651 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002652 }
2653 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002654}
2655
Dan Stoza6b9454d2014-11-07 16:00:59 -08002656bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002657{
Ady Abraham09bd3922019-04-08 10:44:56 -07002658 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002659 ALOGV("handlePageFlip");
2660
Brian Andersond6927fb2016-07-23 23:37:30 -07002661 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662
Mathias Agopian4fec8732012-06-29 14:12:52 -07002663 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002664 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002665 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002666
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002667 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2668
Eric Penner51c59cd2014-07-28 19:51:58 -07002669 // Store the set of layers that need updates. This set must not change as
2670 // buffers are being latched, as this could result in a deadlock.
2671 // Example: Two producers share the same command stream and:
2672 // 1.) Layer 0 is latched
2673 // 2.) Layer 0 gets a new frame
2674 // 2.) Layer 1 gets a new frame
2675 // 3.) Layer 1 is latched.
2676 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2677 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002678 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002679 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002680 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002681 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002682 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002683 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002684 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002685 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002686 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002687 } else {
2688 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002689 }
Robert Carr2047fae2016-11-28 14:09:09 -08002690 });
2691
chaviw49a108c2019-08-12 11:23:06 -07002692 // The client can continue submitting buffers for offscreen layers, but they will not
2693 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2694 // layers to ensure dequeueBuffer doesn't block indefinitely.
2695 for (Layer* offscreenLayer : mOffscreenLayers) {
2696 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2697 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2698 }
2699
Lloyd Piquef2c79392018-12-20 16:23:33 -08002700 if (!mLayersWithQueuedFrames.empty()) {
2701 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2702 // writes to Layer current state. See also b/119481871
2703 Mutex::Autolock lock(mStateLock);
2704
2705 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002706 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002707 mLayersPendingRefresh.push_back(layer);
2708 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002709 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002710 if (layer->isBufferLatched()) {
2711 newDataLatched = true;
2712 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002713 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002714 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002715
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002716 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002717
2718 // If we will need to wake up at some time in the future to deal with a
2719 // queued frame that shouldn't be displayed during this vsync period, wake
2720 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002721 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002722 signalLayerUpdate();
2723 }
2724
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002725 // enter boot animation on first buffer latch
2726 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2727 ALOGI("Enter boot animation");
2728 mBootStage = BootStage::BOOTANIMATION;
2729 }
2730
chaviw74b03172019-08-19 11:09:03 -07002731 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2732
Dan Stoza6b9454d2014-11-07 16:00:59 -08002733 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002734 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002735}
2736
Mathias Agopianad456f92011-01-13 17:53:01 -08002737void SurfaceFlinger::invalidateHwcGeometry()
2738{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002739 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002740}
2741
Robert Carrc0df3122019-04-11 13:18:21 -07002742status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2743 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2744 const sp<IBinder>& parentHandle,
2745 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002746 // add this layer to the current state list
2747 {
2748 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002749 sp<Layer> parent;
2750 if (parentHandle != nullptr) {
2751 parent = fromHandle(parentHandle);
2752 if (parent == nullptr) {
2753 return NAME_NOT_FOUND;
2754 }
2755 } else {
2756 parent = parentLayer;
2757 }
2758
Robert Carr1f0a16a2016-10-24 16:27:39 -07002759 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002760 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002761 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002762 return NO_MEMORY;
2763 }
Robert Carrc0df3122019-04-11 13:18:21 -07002764
2765 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2766
Robert Carrb89ea9d2018-12-10 13:01:14 -08002767 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002768 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002769 } else if (parent == nullptr) {
2770 lbc->onRemovedFromCurrentState();
2771 } else if (parent->isRemovedFromCurrentState()) {
2772 parent->addChild(lbc);
2773 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002774 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002775 parent->addChild(lbc);
2776 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002777
Yiwei Zhang243b3782018-05-15 17:40:04 -07002778 if (gbc != nullptr) {
2779 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2780 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2781 mMaxGraphicBufferProducerListSize,
2782 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2783 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002784 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002785 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002786 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002787 }
2788
Mathias Agopian96f08192010-06-02 23:28:45 -07002789 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002790 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002791
Dan Stoza7d89d062015-04-30 13:29:25 -07002792 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002793}
2794
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002795uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002796 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002797}
2798
Mathias Agopian3f844832013-08-07 21:24:32 -07002799uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002800 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002801}
2802
Mathias Agopian3f844832013-08-07 21:24:32 -07002803uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002804 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002805}
2806
2807uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002808 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002809 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002810 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002812 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813 }
2814 return old;
2815}
2816
Marissa Wall713b63f2018-10-17 15:42:43 -07002817bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002818 // to prevent onHandleDestroyed from being called while the lock is held,
2819 // we must keep a copy of the transactions (specifically the composer
2820 // states) around outside the scope of the lock
2821 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002822 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002823 {
2824 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002825
Valerie Haufce31b82019-04-30 16:41:14 -07002826 auto it = mTransactionQueues.begin();
2827 while (it != mTransactionQueues.end()) {
2828 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002829
Valerie Haufce31b82019-04-30 16:41:14 -07002830 while (!transactionQueue.empty()) {
2831 const auto& transaction = transactionQueue.front();
2832 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002833 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002834 transaction.states)) {
2835 setTransactionFlags(eTransactionFlushNeeded);
2836 break;
2837 }
2838 transactions.push_back(transaction);
2839 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2840 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002841 transaction.buffer, transaction.postTime,
2842 transaction.privileged, transaction.hasListenerCallbacks,
2843 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002844 transactionQueue.pop();
2845 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002846 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002847
Valerie Haufce31b82019-04-30 16:41:14 -07002848 if (transactionQueue.empty()) {
2849 it = mTransactionQueues.erase(it);
2850 mTransactionCV.broadcast();
2851 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002852 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002853 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002854 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002855 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002856 return flushedATransaction;
2857}
2858
2859bool SurfaceFlinger::transactionFlushNeeded() {
2860 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07002861}
2862
chaviwca27f252018-02-06 16:46:39 -08002863
Marissa Wall17b4e452018-12-26 16:32:34 -08002864bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002865 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08002866 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002867 if (!useCachedExpectedPresentTime)
2868 populateExpectedPresentTime();
2869
2870 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08002871 // Do not present if the desiredPresentTime has not passed unless it is more than one second
2872 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
2873 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
2874 desiredPresentTime < expectedPresentTime + s2ns(1)) {
2875 return false;
2876 }
2877
Marissa Wall713b63f2018-10-17 15:42:43 -07002878 for (const ComposerState& state : states) {
2879 const layer_state_t& s = state.state;
2880 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
2881 continue;
2882 }
2883 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08002884 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07002885 }
2886 }
Marissa Wall17b4e452018-12-26 16:32:34 -08002887 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002888}
2889
Valerie Hau9dab9732019-08-20 09:29:25 -07002890void SurfaceFlinger::setTransactionState(
2891 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2892 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
2893 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
2894 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002895 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08002896
Valerie Haubc6ddb12019-03-08 11:10:15 -08002897 const int64_t postTime = systemTime();
2898
Robert Carr14167e02019-02-13 13:50:55 -08002899 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
2900
Mathias Agopian698c0872011-06-28 19:09:31 -07002901 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07002902
Marissa Wall713b63f2018-10-17 15:42:43 -07002903 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07002904 auto itr = mTransactionQueues.find(applyToken);
2905 // if this is an animation frame, wait until prior animation frame has
2906 // been applied by SF
2907 if (flags & eAnimation) {
2908 while (itr != mTransactionQueues.end()) {
2909 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2910 if (CC_UNLIKELY(err != NO_ERROR)) {
2911 ALOGW_IF(err == TIMED_OUT,
2912 "setTransactionState timed out "
2913 "waiting for animation frame to apply");
2914 break;
2915 }
2916 itr = mTransactionQueues.find(applyToken);
2917 }
2918 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002919
2920 // Expected present time is computed and cached on invalidate, so it may be stale.
2921 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
2922 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08002923 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002924 uncacheBuffer, postTime, privileged,
2925 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002926 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002927 return;
2928 }
2929
Valerie Haubc6ddb12019-03-08 11:10:15 -08002930 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002931 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
2932 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07002933}
2934
Valerie Hau9dab9732019-08-20 09:29:25 -07002935void SurfaceFlinger::applyTransactionState(
2936 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2937 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
2938 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
2939 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
2940 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07002941 uint32_t transactionFlags = 0;
2942
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002943 if (flags & eAnimation) {
2944 // For window updates that are part of an animation we must wait for
2945 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07002946 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002947 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002948 if (CC_UNLIKELY(err != NO_ERROR)) {
2949 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002950 // caller after a few seconds.
2951 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2952 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002953 mAnimTransactionPending = false;
2954 break;
2955 }
2956 }
2957 }
2958
chaviwca27f252018-02-06 16:46:39 -08002959 for (const DisplayState& display : displays) {
2960 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002961 }
2962
Valerie Hau9dab9732019-08-20 09:29:25 -07002963 // start and end registration for listeners w/ no surface so they can get their callback. Note
2964 // that listeners with SurfaceControls will start registration during setClientStateLocked
2965 // below.
2966 for (const auto& listener : listenerCallbacks) {
2967 mTransactionCompletedThread.startRegistration(listener);
2968 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07002969 }
2970
Valerie Hau9dab9732019-08-20 09:29:25 -07002971 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07002972 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08002973 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07002974 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
2975 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07002976 }
2977
Valerie Hau9dab9732019-08-20 09:29:25 -07002978 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07002979 mTransactionCompletedThread.endRegistration(listenerCallback);
2980 }
2981
Marissa Walle2ffb422018-10-12 11:33:52 -07002982 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07002983 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07002984 mTransactionCompletedThread.sendCallbacks();
2985 }
2986 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08002987
chaviw273171b2018-12-26 11:46:30 -08002988 transactionFlags |= addInputWindowCommands(inputWindowCommands);
2989
Marissa Wall947d34e2019-03-29 14:03:53 -07002990 if (uncacheBuffer.isValid()) {
2991 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07002992 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07002993 }
2994
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002995 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2996 // anyway. This can be used as a flush mechanism for previous async transactions.
2997 // Empty animation transaction can be used to simulate back-pressure, so also force a
2998 // transaction for empty animation transactions.
2999 if (transactionFlags == 0 &&
3000 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003001 transactionFlags = eTransactionNeeded;
3002 }
3003
Marissa Wall06255332019-03-27 13:48:27 -07003004 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3005 // so we don't have to wake up again next frame to preform an uneeded traversal.
3006 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3007 transactionFlags = transactionFlags & (~eTraversalNeeded);
3008 mTraversalNeededMainThread = true;
3009 }
3010
Mathias Agopian386aa982011-11-07 21:58:03 -08003011 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003012 if (mInterceptor->isEnabled()) {
3013 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003014 }
Irvel468051e2016-06-13 16:44:44 -07003015
Mathias Agopian386aa982011-11-07 21:58:03 -08003016 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003017 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3018 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003019 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003020
3021 // if this is a synchronous transaction, wait for it to take effect
3022 // before returning.
3023 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003024 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003025 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003026 if (flags & eAnimation) {
3027 mAnimTransactionPending = true;
3028 }
chaviw4fe36852019-04-15 16:25:49 -07003029 if (mPendingInputWindowCommands.syncInputWindows) {
3030 mPendingSyncInputWindows = true;
3031 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003032
3033 // applyTransactionState can be called by either the main SF thread or by
3034 // another process through setTransactionState. While a given process may wish
3035 // to wait on synchronous transactions, the main SF thread should never
3036 // be blocked. Therefore, we only wait if isMainThread is false.
3037 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003038 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3039 if (CC_UNLIKELY(err != NO_ERROR)) {
3040 // just in case something goes wrong in SF, return to the
3041 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003042 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3043 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003044 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003045 break;
3046 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003047 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003048 }
3049}
3050
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003051uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3052 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3053 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003054
Mathias Agopiane57f2922012-08-09 16:29:12 -07003055 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003056 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3057
3058 const uint32_t what = s.what;
3059 if (what & DisplayState::eSurfaceChanged) {
3060 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3061 state.surface = s.surface;
3062 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003063 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003064 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003065 if (what & DisplayState::eLayerStackChanged) {
3066 if (state.layerStack != s.layerStack) {
3067 state.layerStack = s.layerStack;
3068 flags |= eDisplayTransactionNeeded;
3069 }
3070 }
3071 if (what & DisplayState::eDisplayProjectionChanged) {
3072 if (state.orientation != s.orientation) {
3073 state.orientation = s.orientation;
3074 flags |= eDisplayTransactionNeeded;
3075 }
3076 if (state.frame != s.frame) {
3077 state.frame = s.frame;
3078 flags |= eDisplayTransactionNeeded;
3079 }
3080 if (state.viewport != s.viewport) {
3081 state.viewport = s.viewport;
3082 flags |= eDisplayTransactionNeeded;
3083 }
3084 }
3085 if (what & DisplayState::eDisplaySizeChanged) {
3086 if (state.width != s.width) {
3087 state.width = s.width;
3088 flags |= eDisplayTransactionNeeded;
3089 }
3090 if (state.height != s.height) {
3091 state.height = s.height;
3092 flags |= eDisplayTransactionNeeded;
3093 }
3094 }
3095
Mathias Agopiane57f2922012-08-09 16:29:12 -07003096 return flags;
3097}
3098
Robert Carr14167e02019-02-13 13:50:55 -08003099bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003100 IPCThreadState* ipc = IPCThreadState::self();
3101 const int pid = ipc->getCallingPid();
3102 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003103 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003104 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003105 return false;
3106 }
3107 return true;
3108}
3109
Marissa Wall3dad52d2019-03-22 14:03:19 -07003110uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003111 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3112 bool privileged,
3113 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003114 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003115
Valerie Hau9dab9732019-08-20 09:29:25 -07003116 for (auto& listener : s.listeners) {
3117 // note that startRegistration will not re-register if the listener has
3118 // already be registered for a prior surface control
3119 mTransactionCompletedThread.startRegistration(listener);
3120 listenerCallbacks.insert(listener);
3121 }
3122
Vishnu Nairf03652d2019-07-16 17:56:56 -07003123 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003124 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003125 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003126 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003127 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003128 }
chaviw8b3871a2017-11-01 17:41:01 -07003129 return 0;
3130 }
3131
chaviw8b3871a2017-11-01 17:41:01 -07003132 uint32_t flags = 0;
3133
Garfield Tan8a3083e2018-12-03 13:21:07 -08003134 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003135
3136 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3137 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003138 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003139 layer->pushPendingState();
3140 }
3141
chaviw8b3871a2017-11-01 17:41:01 -07003142 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003143 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003144 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003145 }
chaviw8b3871a2017-11-01 17:41:01 -07003146 }
3147 if (what & layer_state_t::eLayerChanged) {
3148 // NOTE: index needs to be calculated before we update the state
3149 const auto& p = layer->getParent();
3150 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003151 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003152 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003153 mCurrentState.layersSortedByZ.removeAt(idx);
3154 mCurrentState.layersSortedByZ.add(layer);
3155 // we need traversal (state changed)
3156 // AND transaction (list changed)
3157 flags |= eTransactionNeeded|eTraversalNeeded;
3158 }
chaviw8b3871a2017-11-01 17:41:01 -07003159 } else {
3160 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003161 flags |= eTransactionNeeded|eTraversalNeeded;
3162 }
3163 }
chaviw8b3871a2017-11-01 17:41:01 -07003164 }
3165 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003166 // NOTE: index needs to be calculated before we update the state
3167 const auto& p = layer->getParent();
3168 if (p == nullptr) {
3169 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3170 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3171 mCurrentState.layersSortedByZ.removeAt(idx);
3172 mCurrentState.layersSortedByZ.add(layer);
3173 // we need traversal (state changed)
3174 // AND transaction (list changed)
3175 flags |= eTransactionNeeded|eTraversalNeeded;
3176 }
3177 } else {
3178 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3179 flags |= eTransactionNeeded|eTraversalNeeded;
3180 }
chaviw8b3871a2017-11-01 17:41:01 -07003181 }
3182 }
3183 if (what & layer_state_t::eSizeChanged) {
3184 if (layer->setSize(s.w, s.h)) {
3185 flags |= eTraversalNeeded;
3186 }
3187 }
3188 if (what & layer_state_t::eAlphaChanged) {
3189 if (layer->setAlpha(s.alpha))
3190 flags |= eTraversalNeeded;
3191 }
3192 if (what & layer_state_t::eColorChanged) {
3193 if (layer->setColor(s.color))
3194 flags |= eTraversalNeeded;
3195 }
Peiyong Lind3788632018-09-18 16:01:31 -07003196 if (what & layer_state_t::eColorTransformChanged) {
3197 if (layer->setColorTransform(s.colorTransform)) {
3198 flags |= eTraversalNeeded;
3199 }
3200 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003201 if (what & layer_state_t::eBackgroundColorChanged) {
3202 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3203 flags |= eTraversalNeeded;
3204 }
3205 }
chaviw8b3871a2017-11-01 17:41:01 -07003206 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003207 // TODO: b/109894387
3208 //
3209 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3210 // rotation. To see the problem observe that if we have a square parent, and a child
3211 // of the same size, then we rotate the child 45 degrees around it's center, the child
3212 // must now be cropped to a non rectangular 8 sided region.
3213 //
3214 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3215 // private API, and the WindowManager only uses rotation in one case, which is on a top
3216 // level layer in which cropping is not an issue.
3217 //
3218 // However given that abuse of rotation matrices could lead to surfaces extending outside
3219 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3220 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3221 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003222 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003223 flags |= eTraversalNeeded;
3224 }
3225 if (what & layer_state_t::eTransparentRegionChanged) {
3226 if (layer->setTransparentRegionHint(s.transparentRegion))
3227 flags |= eTraversalNeeded;
3228 }
3229 if (what & layer_state_t::eFlagsChanged) {
3230 if (layer->setFlags(s.flags, s.mask))
3231 flags |= eTraversalNeeded;
3232 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003233 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003234 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003235 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003236 if (what & layer_state_t::eCornerRadiusChanged) {
3237 if (layer->setCornerRadius(s.cornerRadius))
3238 flags |= eTraversalNeeded;
3239 }
chaviw8b3871a2017-11-01 17:41:01 -07003240 if (what & layer_state_t::eLayerStackChanged) {
3241 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3242 // We only allow setting layer stacks for top level layers,
3243 // everything else inherits layer stack from its parent.
3244 if (layer->hasParent()) {
3245 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
3246 layer->getName().string());
3247 } else if (idx < 0) {
3248 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
3249 "that also does not appear in the top level layer list. Something"
3250 " has gone wrong.", layer->getName().string());
3251 } else if (layer->setLayerStack(s.layerStack)) {
3252 mCurrentState.layersSortedByZ.removeAt(idx);
3253 mCurrentState.layersSortedByZ.add(layer);
3254 // we need traversal (state changed)
3255 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003256 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003257 }
3258 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003259 if (what & layer_state_t::eDeferTransaction_legacy) {
3260 if (s.barrierHandle_legacy != nullptr) {
3261 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3262 } else if (s.barrierGbp_legacy != nullptr) {
3263 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003264 if (authenticateSurfaceTextureLocked(gbp)) {
3265 const auto& otherLayer =
3266 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003267 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003268 } else {
3269 ALOGE("Attempt to defer transaction to to an"
3270 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003271 }
3272 }
chaviw8b3871a2017-11-01 17:41:01 -07003273 // We don't trigger a traversal here because if no other state is
3274 // changed, we don't want this to cause any more work
3275 }
chaviw8b3871a2017-11-01 17:41:01 -07003276 if (what & layer_state_t::eReparentChildren) {
3277 if (layer->reparentChildren(s.reparentHandle)) {
3278 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003279 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003280 }
chaviw8b3871a2017-11-01 17:41:01 -07003281 if (what & layer_state_t::eDetachChildren) {
3282 layer->detachChildren();
3283 }
3284 if (what & layer_state_t::eOverrideScalingModeChanged) {
3285 layer->setOverrideScalingMode(s.overrideScalingMode);
3286 // We don't trigger a traversal here because if no other state is
3287 // changed, we don't want this to cause any more work
3288 }
Marissa Wall61c58622018-07-18 10:12:20 -07003289 if (what & layer_state_t::eTransformChanged) {
3290 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3291 }
3292 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3293 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3294 flags |= eTraversalNeeded;
3295 }
3296 if (what & layer_state_t::eCropChanged) {
3297 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3298 }
Marissa Wall861616d2018-10-22 12:52:23 -07003299 if (what & layer_state_t::eFrameChanged) {
3300 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3301 }
Marissa Wall61c58622018-07-18 10:12:20 -07003302 if (what & layer_state_t::eAcquireFenceChanged) {
3303 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3304 }
3305 if (what & layer_state_t::eDataspaceChanged) {
3306 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3307 }
3308 if (what & layer_state_t::eHdrMetadataChanged) {
3309 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3310 }
3311 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3312 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3313 }
3314 if (what & layer_state_t::eApiChanged) {
3315 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3316 }
3317 if (what & layer_state_t::eSidebandStreamChanged) {
3318 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3319 }
Robert Carr720e5062018-07-30 17:45:14 -07003320 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003321 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003322 layer->setInputInfo(s.inputInfo);
3323 flags |= eTraversalNeeded;
3324 } else {
3325 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3326 }
Robert Carr720e5062018-07-30 17:45:14 -07003327 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003328 if (what & layer_state_t::eMetadataChanged) {
3329 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3330 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003331 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3332 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3333 flags |= eTraversalNeeded;
3334 }
3335 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003336 // This has to happen after we reparent children because when we reparent to null we remove
3337 // child layers from current state and remove its relative z. If the children are reparented in
3338 // the same transaction, then we have to make sure we reparent the children first so we do not
3339 // lose its relative z order.
3340 if (what & layer_state_t::eReparent) {
3341 bool hadParent = layer->hasParent();
3342 if (layer->reparent(s.parentHandleForChild)) {
3343 if (!hadParent) {
3344 mCurrentState.layersSortedByZ.remove(layer);
3345 }
3346 flags |= eTransactionNeeded | eTraversalNeeded;
3347 }
3348 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003349 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003350 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3351 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003352 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3353 }
3354 }
Marissa Wall78b72202019-03-15 14:58:34 -07003355 bool bufferChanged = what & layer_state_t::eBufferChanged;
3356 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3357 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003358 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003359 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003360 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3361 if (success) {
3362 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3363 success = ClientCache::getInstance()
3364 .registerErasedRecipient(s.cachedBuffer,
3365 wp<ClientCache::ErasedRecipient>(this));
3366 if (!success) {
3367 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3368 }
3369 }
Marissa Wall78b72202019-03-15 14:58:34 -07003370 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003371 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003372 } else if (bufferChanged) {
3373 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003374 }
Marissa Wall78b72202019-03-15 14:58:34 -07003375 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003376 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003377 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003378 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003379 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003380 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3381 // Do not put anything that updates layer state or modifies flags after
3382 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003383 return flags;
3384}
3385
chaviw273171b2018-12-26 11:46:30 -08003386uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3387 uint32_t flags = 0;
3388 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3389 flags |= eTraversalNeeded;
3390 }
3391
chaviwa911b102019-02-14 10:18:33 -08003392 if (inputWindowCommands.syncInputWindows) {
3393 flags |= eTraversalNeeded;
3394 }
3395
Vishnu Nairec0ab382019-02-13 15:32:56 -08003396 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003397 return flags;
3398}
3399
Marissa Wall2d814fb2019-04-09 18:52:57 +00003400status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3401 uint32_t h, PixelFormat format, uint32_t flags,
3402 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003403 sp<IGraphicBufferProducer>* gbp,
3404 const sp<IBinder>& parentHandle,
3405 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003406 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003407 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003408 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003409 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003410 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003411
Robert Carrc0df3122019-04-11 13:18:21 -07003412 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3413 "Expected only one of parentLayer or parentHandle to be non-null. "
3414 "Programmer error?");
3415
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003416 status_t result = NO_ERROR;
3417
3418 sp<Layer> layer;
3419
Cody Northropbc755282017-03-31 12:00:08 -06003420 String8 uniqueName = getUniqueLayerName(name);
3421
Evan Roskya1f1e152019-01-24 16:17:46 -08003422 bool primaryDisplayOnly = false;
3423
3424 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3425 // TODO b/64227542
3426 if (metadata.has(METADATA_WINDOW_TYPE)) {
3427 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3428 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003429 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003430 primaryDisplayOnly = true;
3431 }
3432 }
3433
Mathias Agopian3165cc22012-08-08 19:42:09 -07003434 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003435 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Evan Roskya1f1e152019-01-24 16:17:46 -08003436 result = createBufferQueueLayer(client, uniqueName, w, h, flags, std::move(metadata),
3437 format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003438
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003439 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003440 case ISurfaceComposerClient::eFXSurfaceBufferState:
Evan Roskya1f1e152019-01-24 16:17:46 -08003441 result = createBufferStateLayer(client, uniqueName, w, h, flags, std::move(metadata),
3442 handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003443 break;
chaviw13fdc492017-06-27 12:40:18 -07003444 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003445 // check if buffer size is set for color layer.
3446 if (w > 0 || h > 0) {
3447 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3448 int(w), int(h));
3449 return BAD_VALUE;
3450 }
3451
Evan Roskya1f1e152019-01-24 16:17:46 -08003452 result = createColorLayer(client, uniqueName, w, h, flags, std::move(metadata), handle,
3453 &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003454 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003455 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003456 // check if buffer size is set for container layer.
3457 if (w > 0 || h > 0) {
3458 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3459 int(w), int(h));
3460 return BAD_VALUE;
3461 }
Evan Roskya1f1e152019-01-24 16:17:46 -08003462 result = createContainerLayer(client, uniqueName, w, h, flags, std::move(metadata),
3463 handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003464 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003465 default:
3466 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003467 break;
3468 }
3469
Dan Stoza7d89d062015-04-30 13:29:25 -07003470 if (result != NO_ERROR) {
3471 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003472 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003473
Evan Roskya1f1e152019-01-24 16:17:46 -08003474 if (primaryDisplayOnly) {
3475 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003476 }
3477
Robert Carrb89ea9d2018-12-10 13:01:14 -08003478 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003479 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3480 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003481 if (result != NO_ERROR) {
3482 return result;
3483 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003484 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003485
3486 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003487 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003488}
3489
Cody Northropbc755282017-03-31 12:00:08 -06003490String8 SurfaceFlinger::getUniqueLayerName(const String8& name)
3491{
3492 bool matchFound = true;
3493 uint32_t dupeCounter = 0;
3494
3495 // Tack on our counter whether there is a hit or not, so everyone gets a tag
3496 String8 uniqueName = name + "#" + String8(std::to_string(dupeCounter).c_str());
3497
Dan Stoza436ccf32018-06-21 12:10:12 -07003498 // Grab the state lock since we're accessing mCurrentState
3499 Mutex::Autolock lock(mStateLock);
3500
Cody Northropbc755282017-03-31 12:00:08 -06003501 // Loop over layers until we're sure there is no matching name
3502 while (matchFound) {
3503 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003504 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003505 if (layer->getName() == uniqueName) {
3506 matchFound = true;
3507 uniqueName = name + "#" + String8(std::to_string(++dupeCounter).c_str());
3508 }
3509 });
3510 }
3511
Marissa Wallf1de4bd2018-05-22 13:05:01 -07003512 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name.c_str(),
3513 uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003514
3515 return uniqueName;
3516}
3517
Marissa Wallfd668622018-05-10 10:21:13 -07003518status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, const String8& name,
3519 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003520 LayerMetadata metadata, PixelFormat& format,
3521 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003522 sp<IGraphicBufferProducer>* gbp,
3523 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003524 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003525 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003526 case PIXEL_FORMAT_TRANSPARENT:
3527 case PIXEL_FORMAT_TRANSLUCENT:
3528 format = PIXEL_FORMAT_RGBA_8888;
3529 break;
3530 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003531 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003532 break;
3533 }
3534
chaviwb4c6e582019-08-16 14:35:07 -07003535 sp<BufferQueueLayer> layer;
3536 LayerCreationArgs args =
3537 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata));
3538 args.textureName = getNewTexture();
3539 {
3540 // Grab the SF state lock during this since it's the only safe way to access
3541 // RenderEngine when creating a BufferLayerConsumer
3542 // TODO: Check if this lock is still needed here
3543 Mutex::Autolock lock(mStateLock);
3544 layer = getFactory().createBufferQueueLayer(args);
3545 }
3546
Marissa Wallfd668622018-05-10 10:21:13 -07003547 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003548 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003549 *handle = layer->getHandle();
3550 *gbp = layer->getProducer();
3551 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003552 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003553
Marissa Wallfd668622018-05-10 10:21:13 -07003554 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003555 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003556}
3557
Marissa Wall61c58622018-07-18 10:12:20 -07003558status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, const String8& name,
3559 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003560 LayerMetadata metadata, sp<IBinder>* handle,
3561 sp<Layer>* outLayer) {
chaviwb4c6e582019-08-16 14:35:07 -07003562 LayerCreationArgs args =
3563 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata));
3564 args.displayDevice = getDefaultDisplayDevice();
3565 args.textureName = getNewTexture();
3566 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07003567 *handle = layer->getHandle();
3568 *outLayer = layer;
3569
3570 return NO_ERROR;
3571}
3572
Evan Roskya1f1e152019-01-24 16:17:46 -08003573status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, const String8& name, uint32_t w,
3574 uint32_t h, uint32_t flags, LayerMetadata metadata,
3575 sp<IBinder>* handle, sp<Layer>* outLayer) {
3576 *outLayer = getFactory().createColorLayer(
3577 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003578 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003579 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003580}
3581
Evan Roskya1f1e152019-01-24 16:17:46 -08003582status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, const String8& name,
3583 uint32_t w, uint32_t h, uint32_t flags,
3584 LayerMetadata metadata, sp<IBinder>* handle,
3585 sp<Layer>* outLayer) {
3586 *outLayer = getFactory().createContainerLayer(
3587 LayerCreationArgs(this, client, name, w, h, flags, std::move(metadata)));
Robert Carr6b3f6c52018-08-13 13:05:17 -07003588 *handle = (*outLayer)->getHandle();
3589 return NO_ERROR;
3590}
3591
3592
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003593void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003594 mLayersPendingRemoval.add(layer);
3595 mLayersRemoved = true;
3596 setTransactionFlags(eTransactionNeeded);
3597}
3598
Robert Carr695d5282018-12-18 15:27:58 -08003599void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003600{
Robert Carr2e102c92018-10-23 12:11:15 -07003601 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003602 // If a layer has a parent, we allow it to out-live it's handle
3603 // with the idea that the parent holds a reference and will eventually
3604 // be cleaned up. However no one cleans up the top-level so we do so
3605 // here.
3606 if (layer->getParent() == nullptr) {
3607 mCurrentState.layersSortedByZ.remove(layer);
3608 }
3609 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003610
3611 auto it = mLayersByLocalBinderToken.begin();
3612 while (it != mLayersByLocalBinderToken.end()) {
3613 if (it->second == layer) {
3614 it = mLayersByLocalBinderToken.erase(it);
3615 } else {
3616 it++;
3617 }
3618 }
3619
Robert Carr695d5282018-12-18 15:27:58 -08003620 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003621}
3622
Mathias Agopianb60314a2012-04-10 22:09:54 -07003623// ---------------------------------------------------------------------------
3624
Andy McFadden13a082e2012-08-24 10:16:42 -07003625void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003626 const auto display = getDefaultDisplayDeviceLocked();
3627 if (!display) return;
3628
3629 const sp<IBinder> token = display->getDisplayToken().promote();
3630 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003631
Jesse Hall01e29052013-02-19 16:13:35 -08003632 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003633 Vector<ComposerState> state;
3634 Vector<DisplayState> displays;
3635 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003636 d.what = DisplayState::eDisplayProjectionChanged |
3637 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003638 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003639 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003640 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003641 d.frame.makeInvalid();
3642 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003643 d.width = 0;
3644 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003645 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003646 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3647 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003648
Dominik Laskowskie9774092018-12-11 10:04:24 -08003649 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003650
Dominik Laskowski83b88212018-12-11 13:34:06 -08003651 const nsecs_t vsyncPeriod = getVsyncPeriod();
3652 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003653
Brian Andersond0010582017-03-07 13:20:31 -08003654 // Use phase of 0 since phase is not known.
3655 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003656 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003657 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003658}
3659
3660void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003661 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003662 postMessageAsync(
3663 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003664}
3665
Ady Abraham27c70212019-06-11 10:52:26 -07003666void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3667 if (mHWCVsyncState != enabled) {
3668 getHwComposer().setVsyncEnabled(displayId, enabled);
3669 mHWCVsyncState = enabled;
3670 }
3671}
3672
Dominik Laskowskie9774092018-12-11 10:04:24 -08003673void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003674 if (display->isVirtual()) {
3675 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003676 return;
3677 }
3678
Dominik Laskowski075d3172018-05-24 15:50:06 -07003679 const auto displayId = display->getId();
3680 LOG_ALWAYS_FATAL_IF(!displayId);
3681
Dominik Laskowski34157762018-10-31 13:07:19 -07003682 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003683
3684 int currentMode = display->getPowerMode();
3685 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003686 return;
3687 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003688
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003689 display->setPowerMode(mode);
3690
Lloyd Pique4dccc412018-01-22 17:21:36 -08003691 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003692 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003693 }
3694
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003695 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003696 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003697 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003698 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003699 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003700 mScheduler->onScreenAcquired(mAppConnectionHandle);
3701 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003702 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003703
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003704 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003705 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003706 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003707
3708 struct sched_param param = {0};
3709 param.sched_priority = 1;
3710 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3711 ALOGW("Couldn't set SCHED_FIFO on display on");
3712 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003713 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003714 // Turn off the display
3715 struct sched_param param = {0};
3716 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3717 ALOGW("Couldn't set SCHED_OTHER on display off");
3718 }
3719
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003720 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003721 mScheduler->disableHardwareVsync(true);
3722 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003723 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003724
Ady Abraham27c70212019-06-11 10:52:26 -07003725 // Make sure HWVsync is disabled before turning off the display
3726 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3727
Dominik Laskowski075d3172018-05-24 15:50:06 -07003728 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003729 mVisibleRegionsDirty = true;
3730 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003731 } else if (mode == HWC_POWER_MODE_DOZE ||
3732 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003733 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003734 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003735 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003736 mScheduler->onScreenAcquired(mAppConnectionHandle);
3737 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003738 }
3739 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3740 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003741 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003742 mScheduler->disableHardwareVsync(true);
3743 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003744 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003745 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003746 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003747 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003748 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003749 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003750
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003751 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003752 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003753 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003754 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003755 }
3756
Dominik Laskowski34157762018-10-31 13:07:19 -07003757 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003758}
3759
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003760void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003761 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003762 const auto display = getDisplayDevice(displayToken);
3763 if (!display) {
3764 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3765 displayToken.get());
3766 } else if (display->isVirtual()) {
3767 ALOGW("Attempt to set power mode %d for virtual display", mode);
3768 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003769 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003770 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003771 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003772}
3773
3774// ---------------------------------------------------------------------------
3775
Dominik Laskowskic2867142019-01-21 11:33:38 -08003776status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3777 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003778 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003779
Mathias Agopianbd115332013-04-18 16:41:04 -07003780 IPCThreadState* ipc = IPCThreadState::self();
3781 const int pid = ipc->getCallingPid();
3782 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003783
Mathias Agopianbd115332013-04-18 16:41:04 -07003784 if ((uid != AID_SHELL) &&
3785 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003786 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3787 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003788 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003789 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003790 // (this would indicate SF is stuck, but we want to be able to
3791 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003792 status_t err = mStateLock.timedLock(s2ns(1));
3793 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003794 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003795 StringAppendF(&result,
3796 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3797 "(no locks held)\n",
3798 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003799 }
3800
Dominik Laskowskic2867142019-01-21 11:33:38 -08003801 using namespace std::string_literals;
chaviwa3d7bd32017-11-03 09:41:53 -07003802
Dominik Laskowskic2867142019-01-21 11:33:38 -08003803 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003804 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003805 {"--dispsync"s,
3806 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003807 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003808 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3809 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3810 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3811 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3812 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3813 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003814 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003815 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3816 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003817
Dominik Laskowskic2867142019-01-21 11:33:38 -08003818 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003819
Dominik Laskowski46470112019-08-02 13:13:11 -07003820 const auto it = dumpers.find(flag);
3821 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003822 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07003823 } else if (!asProto) {
3824 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003825 }
3826
Mathias Agopian9795c422009-08-26 16:36:26 -07003827 if (locked) {
3828 mStateLock.unlock();
3829 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003830
Dominik Laskowski46470112019-08-02 13:13:11 -07003831 if (it == dumpers.end()) {
3832 const LayersProto layersProto = dumpProtoFromMainThread();
3833 if (asProto) {
3834 result.append(layersProto.SerializeAsString());
3835 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07003836 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07003837 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3838 result.append(LayerProtoParser::layerTreeToString(layerTree));
3839 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07003840 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07003841 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003842 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003843 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08003844 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003845 return NO_ERROR;
3846}
3847
Nataniel Borges8e7dc722019-02-28 15:10:28 -08003848status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
3849 if (asProto && mTracing.isEnabled()) {
3850 mTracing.writeToFileAsync();
3851 }
3852
3853 return doDump(fd, DumpArgs(), asProto);
3854}
3855
Dominik Laskowskic2867142019-01-21 11:33:38 -08003856void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003857 mCurrentState.traverseInZOrder(
3858 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getName().string()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003859}
3860
Dominik Laskowskic2867142019-01-21 11:33:38 -08003861void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003862 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003863
Dominik Laskowskic2867142019-01-21 11:33:38 -08003864 if (args.size() > 1) {
3865 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08003866 mCurrentState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003867 if (name == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003868 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003869 }
Robert Carr2047fae2016-11-28 14:09:09 -08003870 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08003871 } else {
3872 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003873 }
3874}
3875
Dominik Laskowskic2867142019-01-21 11:33:38 -08003876void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Robert Carr2047fae2016-11-28 14:09:09 -08003877 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003878 if (args.size() < 2 || String8(args[1]) == layer->getName()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003879 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003880 }
Robert Carr2047fae2016-11-28 14:09:09 -08003881 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003882
Svetoslavd85084b2014-03-20 10:28:31 -07003883 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003884}
3885
Dominik Laskowskic2867142019-01-21 11:33:38 -08003886void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
3887 mTimeStats->parseArgs(asProto, args, result);
3888}
3889
Jamie Gennis6547ff42013-07-16 20:12:42 -07003890// This should only be called from the main thread. Otherwise it would need
3891// the lock and should use mCurrentState rather than mDrawingState.
3892void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003893 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003894 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003895 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003896
3897 mAnimFrameTracker.logAndResetStats(String8("<win-anim>"));
3898}
3899
Yiwei Zhang5434a782018-12-05 18:06:32 -08003900void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003901 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003902
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003903 if (isLayerTripleBufferingDisabled())
3904 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003905
Yiwei Zhang5434a782018-12-05 18:06:32 -08003906 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
3907 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
3908 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
3909 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
3910 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3911 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003912 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003913}
3914
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003915void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07003916 mScheduler->dump(result);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003917 StringAppendF(&result, "+ Refresh rate switching: %s\n",
3918 mRefreshRateConfigs->refreshRateSwitchingSupported() ? "on" : "off");
Dominik Laskowski98041832019-08-01 18:35:59 -07003919 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
3920
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003921 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07003922 result.append("\n");
3923
Ana Krulec757f63a2019-01-25 10:46:18 -08003924 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003925 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07003926 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08003927 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003928
Ady Abraham42b3beb2019-07-09 18:09:52 -07003929 StringAppendF(&result, "Allowed Display Configs: ");
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003930 for (int32_t configId : mAllowedDisplayConfigs) {
3931 StringAppendF(&result, "%" PRIu32 " Hz, ",
3932 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07003933 }
3934 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
3935 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07003936
Ana Krulecc2870422019-01-29 19:00:58 -08003937 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003938}
3939
Yiwei Zhang5434a782018-12-05 18:06:32 -08003940void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
3941 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003942 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3943 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003944 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003945 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003946 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003947 }
David Sodman4a36e932017-11-07 14:29:47 -08003948 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003949 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003950 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003951 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
3952 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003953}
3954
Dan Stozae77c7662016-05-13 11:37:28 -07003955void SurfaceFlinger::recordBufferingStats(const char* layerName,
3956 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003957 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3958 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003959 for (const auto& segment : history) {
3960 if (!segment.usedThirdBuffer) {
3961 stats.twoBufferTime += segment.totalTime;
3962 }
3963 if (segment.occupancyAverage < 1.0f) {
3964 stats.doubleBufferedTime += segment.totalTime;
3965 } else if (segment.occupancyAverage < 2.0f) {
3966 stats.tripleBufferedTime += segment.totalTime;
3967 }
3968 ++stats.numSegments;
3969 stats.totalTime += segment.totalTime;
3970 }
3971}
3972
Yiwei Zhang5434a782018-12-05 18:06:32 -08003973void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
3974 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07003975
3976 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
3977 const size_t count = currentLayers.size();
3978 for (size_t i=0 ; i<count ; i++) {
3979 currentLayers[i]->dumpFrameEvents(result);
3980 }
3981}
3982
Yiwei Zhang5434a782018-12-05 18:06:32 -08003983void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07003984 result.append("Buffering stats:\n");
3985 result.append(" [Layer name] <Active time> <Two buffer> "
3986 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08003987 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07003988 typedef std::tuple<std::string, float, float, float> BufferTuple;
3989 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08003990 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07003991 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08003992 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07003993 if (stats.numSegments == 0) {
3994 continue;
3995 }
3996 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
3997 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
3998 stats.totalTime;
3999 float doubleBufferRatio = static_cast<float>(
4000 stats.doubleBufferedTime) / stats.totalTime;
4001 float tripleBufferRatio = static_cast<float>(
4002 stats.tripleBufferedTime) / stats.totalTime;
4003 sorted.insert({activeTime, {name, twoBufferRatio,
4004 doubleBufferRatio, tripleBufferRatio}});
4005 }
4006 for (const auto& sortedPair : sorted) {
4007 float activeTime = sortedPair.first;
4008 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004009 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4010 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004011 }
4012 result.append("\n");
4013}
4014
Yiwei Zhang5434a782018-12-05 18:06:32 -08004015void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004016 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004017 const auto displayId = display->getId();
4018 if (!displayId) {
4019 continue;
4020 }
4021 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004022 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004023 continue;
4024 }
4025
Yiwei Zhang5434a782018-12-05 18:06:32 -08004026 StringAppendF(&result,
4027 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4028 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004029 uint8_t port;
4030 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004031 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004032 result.append("no identification data\n");
4033 continue;
4034 }
4035
4036 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004037 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004038 continue;
4039 }
4040
4041 const auto edid = parseEdid(data);
4042 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004043 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004044 continue;
4045 }
4046
Yiwei Zhang5434a782018-12-05 18:06:32 -08004047 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004048 result.append(edid->displayName.data(), edid->displayName.length());
4049 result.append("\"\n");
4050 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004051}
4052
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004053void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4054 std::string& result) const {
4055 hwc2_display_t hwcDisplayId;
4056 uint8_t port;
4057 DisplayIdentificationData data;
4058
4059 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4060 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4061 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4062 }
4063}
4064
Yiwei Zhang5434a782018-12-05 18:06:32 -08004065void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004066 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004067 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4068 StringAppendF(&result, "DisplayColorSetting: %s\n",
4069 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004070
4071 // TODO: print out if wide-color mode is active or not
4072
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004073 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004074 const auto displayId = display->getId();
4075 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004076 continue;
4077 }
4078
Yiwei Zhang5434a782018-12-05 18:06:32 -08004079 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004080 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004081 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004082 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004083 }
4084
Lloyd Pique32cbe282018-10-19 13:09:22 -07004085 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004086 StringAppendF(&result, " Current color mode: %s (%d)\n",
4087 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004088 }
4089 result.append("\n");
4090}
4091
Vishnu Nair8406fd72019-07-30 11:29:31 -07004092LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004093 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004094 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004095 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004096 layer->writeToProtoDrawingState(layerProto, traceFlags);
4097 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004098 });
4099
4100 return layersProto;
4101}
4102
Vishnu Nair0f085c62019-08-30 08:49:12 -07004103void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4104 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4105 // it.
4106 LayerProto* rootProto = layersProto.add_layers();
4107 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4108 rootProto->set_id(offscreenRootLayerId);
4109 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004110 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004111
4112 for (Layer* offscreenLayer : mOffscreenLayers) {
4113 // Add layer as child of the fake root
4114 rootProto->add_children(offscreenLayer->sequence);
4115
4116 // Add layer
4117 LayerProto* layerProto = layersProto.add_layers();
4118 offscreenLayer->writeToProtoDrawingState(layerProto, traceFlags);
4119 offscreenLayer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing,
4120 traceFlags);
4121 layerProto->set_parent(offscreenRootLayerId);
4122
4123 // Add children
4124 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4125 if (layer == offscreenLayer) {
4126 return;
4127 }
4128 LayerProto* childProto = layersProto.add_layers();
4129 layer->writeToProtoDrawingState(childProto, traceFlags);
4130 layer->writeToProtoCommonState(childProto, LayerVector::StateSet::Drawing, traceFlags);
4131 });
4132 }
4133}
4134
Vishnu Nair8406fd72019-07-30 11:29:31 -07004135LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4136 LayersProto layersProto;
4137 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4138 return layersProto;
4139}
4140
Vishnu Nair0f085c62019-08-30 08:49:12 -07004141void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4142 result.append("Offscreen Layers:\n");
4143 postMessageSync(new LambdaMessage([&]() {
4144 for (Layer* offscreenLayer : mOffscreenLayers) {
4145 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4146 layer->dumpCallingUidPid(result);
4147 });
4148 }
4149 }));
4150}
4151
Dominik Laskowskic2867142019-01-21 11:33:38 -08004152void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4153 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004154 Colorizer colorizer(colorize);
4155
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004156 // figure out if we're stuck somewhere
4157 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004158 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004159 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4160
4161 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004162 * Dump library configuration.
4163 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004164
4165 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004166 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004167 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004168 appendSfConfigString(result);
4169 appendUiConfigString(result);
4170 appendGuiConfigString(result);
4171 result.append("\n");
4172
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004173 result.append("\nDisplay identification data:\n");
4174 dumpDisplayIdentificationData(result);
4175
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004176 result.append("\nWide-Color information:\n");
4177 dumpWideColorInfo(result);
4178
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004179 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004180 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004181 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004182 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004183 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004184
Andy McFadden41d67d72014-04-25 16:58:34 -07004185 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004186 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004187 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004188 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004189 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004190
Dan Stozab90cf072015-03-05 11:05:59 -08004191 dumpStaticScreenStats(result);
4192 result.append("\n");
4193
Alec Mouri40189b02019-03-05 15:07:54 -08004194 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4195 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4196 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004197
Dan Stozae77c7662016-05-13 11:37:28 -07004198 dumpBufferingStats(result);
4199
Andy McFadden4803b742012-09-24 19:07:20 -07004200 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004201 * Dump the visible layer list
4202 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004203 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004204 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004205 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4206 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004207 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004208
Chia-I Wu2f884132018-09-13 15:17:58 -07004209 {
Lloyd Pique207def92019-02-28 16:09:52 -08004210 StringAppendF(&result, "Composition layers\n");
4211 mDrawingState.traverseInZOrder([&](Layer* layer) {
4212 auto compositionLayer = layer->getCompositionLayer();
4213 if (compositionLayer) compositionLayer->dump(result);
4214 });
4215 }
4216
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004217 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004218 * Dump Display state
4219 */
4220
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004221 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004222 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004223 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004224 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004225 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004226 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004227 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004228
4229 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004230 * Dump CompositionEngine state
4231 */
4232
4233 mCompositionEngine->dump(result);
4234
4235 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004236 * Dump SurfaceFlinger global state
4237 */
4238
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004239 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004240 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004241 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004242
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004243 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004244
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004245 DebugEGLImageTracker::getInstance()->dump(result);
4246
Dominik Laskowski075d3172018-05-24 15:50:06 -07004247 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004248 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4249 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004250 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4251 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004252 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004253 StringAppendF(&result,
4254 " transaction-flags : %08x\n"
4255 " gpu_to_cpu_unsupported : %d\n",
4256 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004257
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004258 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004259 displayId && getHwComposer().isConnected(*displayId)) {
4260 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004261 StringAppendF(&result,
4262 " refresh-rate : %f fps\n"
4263 " x-dpi : %f\n"
4264 " y-dpi : %f\n",
4265 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4266 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004267 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004268
Yiwei Zhang5434a782018-12-05 18:06:32 -08004269 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004270
Dan Stozae22aec72016-08-01 13:20:59 -07004271 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004272 * Tracing state
4273 */
4274 mTracing.dump(result);
4275 result.append("\n");
4276
4277 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004278 * HWC layer minidump
4279 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004280 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004281 const auto displayId = display->getId();
4282 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004283 continue;
4284 }
4285
Yiwei Zhang5434a782018-12-05 18:06:32 -08004286 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004287 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004288 const sp<DisplayDevice> displayDevice = display;
4289 mCurrentState.traverseInZOrder(
4290 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004291 result.append("\n");
4292 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004293
4294 /*
4295 * Dump HWComposer state
4296 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004297 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004298 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004299 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004300 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004301 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004302 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004303
4304 /*
4305 * Dump gralloc state
4306 */
4307 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4308 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004309
4310 /*
4311 * Dump VrFlinger state if in use.
4312 */
4313 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4314 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004315 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004316 result.append("\n");
4317 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004318
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004319 result.append(mTimeStats->miniDump());
4320 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004321}
4322
Chia-I Wu28f320b2018-05-03 11:02:56 -07004323void SurfaceFlinger::updateColorMatrixLocked() {
4324 mat4 colorMatrix;
4325 if (mGlobalSaturationFactor != 1.0f) {
4326 // Rec.709 luma coefficients
4327 float3 luminance{0.213f, 0.715f, 0.072f};
4328 luminance *= 1.0f - mGlobalSaturationFactor;
4329 mat4 saturationMatrix = mat4(
4330 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4331 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4332 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4333 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4334 );
4335 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4336 } else {
4337 colorMatrix = mClientColorMatrix * mDaltonizer();
4338 }
4339
4340 if (mCurrentState.colorMatrix != colorMatrix) {
4341 mCurrentState.colorMatrix = colorMatrix;
4342 mCurrentState.colorMatrixChanged = true;
4343 setTransactionFlags(eTransactionNeeded);
4344 }
4345}
4346
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004347status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004348#pragma clang diagnostic push
4349#pragma clang diagnostic error "-Wswitch-enum"
4350 switch (static_cast<ISurfaceComposerTag>(code)) {
4351 // These methods should at minimum make sure that the client requested
4352 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004353 case BOOT_FINISHED:
4354 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004355 case CREATE_DISPLAY:
4356 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004357 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004358 case GET_ANIMATION_FRAME_STATS:
4359 case GET_HDR_CAPABILITIES:
4360 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004361 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004362 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004363 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004364 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004365 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004366 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004367 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004368 case GET_DISPLAYED_CONTENT_SAMPLE:
4369 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004370 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4371 IPCThreadState* ipc = IPCThreadState::self();
4372 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4373 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004374 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004375 }
Robert Carr1db73f62016-12-21 12:58:51 -08004376 return OK;
4377 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004378 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004379 IPCThreadState* ipc = IPCThreadState::self();
4380 const int pid = ipc->getCallingPid();
4381 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004382 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4383 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004384 return PERMISSION_DENIED;
4385 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004386 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004387 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004388 // Used by apps to hook Choreographer to SurfaceFlinger.
4389 case CREATE_DISPLAY_EVENT_CONNECTION:
4390 // The following calls are currently used by clients that do not
4391 // request necessary permissions. However, they do not expose any secret
4392 // information, so it is OK to pass them.
4393 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004394 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004395 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004396 case GET_PHYSICAL_DISPLAY_IDS:
4397 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004398 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004399 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004400 case GET_DISPLAY_CONFIGS:
4401 case GET_DISPLAY_STATS:
4402 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4403 // Calling setTransactionState is safe, because you need to have been
4404 // granted a reference to Client* and Handle* to do anything with it.
4405 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004406 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004407 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004408 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004409 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004410 case IS_WIDE_COLOR_DISPLAY:
4411 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4412 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004413 return OK;
4414 }
Chong Zhangda6c1592019-07-16 13:45:06 -07004415 case CAPTURE_LAYERS: {
4416 IPCThreadState* ipc = IPCThreadState::self();
4417 const int pid = ipc->getCallingPid();
4418 const int uid = ipc->getCallingUid();
4419 // allow media to capture layer for video thumbnails
4420 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
4421 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4422 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
4423 return PERMISSION_DENIED;
4424 }
4425 return OK;
4426 }
Dan Stoza84ab9372018-12-17 15:27:57 -08004427 case CAPTURE_SCREEN:
4428 case ADD_REGION_SAMPLING_LISTENER:
4429 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004430 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004431 IPCThreadState* ipc = IPCThreadState::self();
4432 const int pid = ipc->getCallingPid();
4433 const int uid = ipc->getCallingUid();
4434 if ((uid != AID_GRAPHICS) &&
4435 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4436 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4437 return PERMISSION_DENIED;
4438 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004439 return OK;
4440 }
4441 // The following codes are deprecated and should never be allowed to access SF.
4442 case CONNECT_DISPLAY_UNUSED:
4443 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4444 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4445 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004446 }
chaviw93df2ea2019-04-30 16:45:12 -07004447 case CAPTURE_SCREEN_BY_ID: {
4448 IPCThreadState* ipc = IPCThreadState::self();
4449 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004450 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004451 return OK;
4452 }
4453 return PERMISSION_DENIED;
4454 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004455 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004456
4457 // These codes are used for the IBinder protocol to either interrogate the recipient
4458 // side of the transaction for its canonical interface descriptor or to dump its state.
4459 // We let them pass by default.
4460 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4461 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4462 code == IBinder::SYSPROPS_TRANSACTION) {
4463 return OK;
4464 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004465 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004466 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004467 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004468 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4469 return OK;
4470 }
4471 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4472 return PERMISSION_DENIED;
4473#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004474}
4475
Ana Krulec13be8ad2018-08-21 02:43:56 +00004476status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4477 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004478 status_t credentialCheck = CheckTransactCodeCredentials(code);
4479 if (credentialCheck != OK) {
4480 return credentialCheck;
4481 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004482
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004483 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4484 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004485 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004486 IPCThreadState* ipc = IPCThreadState::self();
4487 const int uid = ipc->getCallingUid();
4488 if (CC_UNLIKELY(uid != AID_SYSTEM
4489 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004490 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004491 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004492 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004493 return PERMISSION_DENIED;
4494 }
4495 int n;
4496 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004497 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004498 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004499 return NO_ERROR;
4500 case 1002: // SHOW_UPDATES
4501 n = data.readInt32();
4502 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004503 invalidateHwcGeometry();
4504 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004505 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004506 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004507 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004508 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004509 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004510 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004511 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004512 setTransactionFlags(
4513 eTransactionNeeded|
4514 eDisplayTransactionNeeded|
4515 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004516 return NO_ERROR;
4517 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004518 case 1006:{ // send empty update
4519 signalRefresh();
4520 return NO_ERROR;
4521 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004522 case 1008: // toggle use of hw composer
4523 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004524 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004525 invalidateHwcGeometry();
4526 repaintEverything();
4527 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004528 case 1009: // toggle use of transform hint
4529 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004530 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004531 invalidateHwcGeometry();
4532 repaintEverything();
4533 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004534 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004535 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004536 reply->writeInt32(0);
4537 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004538 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004539 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004540 return NO_ERROR;
4541 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004542 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004543 if (!display) {
4544 return NAME_NOT_FOUND;
4545 }
4546
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004547 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004548 return NO_ERROR;
4549 }
4550 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004551 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004552 // daltonize
4553 n = data.readInt32();
4554 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004555 case 1:
4556 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4557 break;
4558 case 2:
4559 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4560 break;
4561 case 3:
4562 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4563 break;
4564 default:
4565 mDaltonizer.setType(ColorBlindnessType::None);
4566 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004567 }
4568 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004569 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004570 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004571 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004572 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004573
4574 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004575 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004576 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004577 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004578 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004579 // apply a color matrix
4580 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004581 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004582 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004583 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004584 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004585 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004586 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004587 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004588 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004589 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004590 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004591
4592 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4593 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004594 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004595 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4596 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4597 }
4598
Chia-I Wu28f320b2018-05-03 11:02:56 -07004599 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004600 return NO_ERROR;
4601 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004602 case 1016: { // Unused.
4603 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004604 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004605 case 1017: {
4606 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004607 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004608 return NO_ERROR;
4609 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004610 case 1018: { // Modify Choreographer's phase offset
4611 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004612 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004613 return NO_ERROR;
4614 }
4615 case 1019: { // Modify SurfaceFlinger's phase offset
4616 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004617 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004618 return NO_ERROR;
4619 }
Irvel468051e2016-06-13 16:44:44 -07004620 case 1020: { // Layer updates interceptor
4621 n = data.readInt32();
4622 if (n) {
4623 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004624 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004625 }
4626 else{
4627 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004628 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004629 }
4630 return NO_ERROR;
4631 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004632 case 1021: { // Disable HWC virtual displays
4633 n = data.readInt32();
4634 mUseHwcVirtualDisplays = !n;
4635 return NO_ERROR;
4636 }
Romain Guy0147a172017-06-01 13:53:56 -07004637 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004638 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004639 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004640
Chia-I Wu28f320b2018-05-03 11:02:56 -07004641 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004642 return NO_ERROR;
4643 }
Romain Guy54f154a2017-10-24 21:40:32 +01004644 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004645 int32_t colorMode;
4646
Chia-I Wu0d711262018-05-21 15:19:35 -07004647 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004648 if (data.readInt32(&colorMode) == NO_ERROR) {
4649 mForceColorMode = static_cast<ColorMode>(colorMode);
4650 }
Romain Guy54f154a2017-10-24 21:40:32 +01004651 invalidateHwcGeometry();
4652 repaintEverything();
4653 return NO_ERROR;
4654 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004655 // Deprecate, use 1030 to check whether the device is color managed.
4656 case 1024: {
4657 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004658 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004659 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004660 n = data.readInt32();
4661 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004662 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004663 Mutex::Autolock lock(mStateLock);
4664 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004665 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004666 reply->writeInt32(NO_ERROR);
4667 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004668 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004669 bool writeFile = false;
4670 {
4671 Mutex::Autolock lock(mStateLock);
4672 mTracingEnabledChanged = true;
4673 writeFile = mTracing.disable();
4674 }
4675
4676 if (writeFile) {
4677 reply->writeInt32(mTracing.writeToFile());
4678 } else {
4679 reply->writeInt32(NO_ERROR);
4680 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004681 }
4682 return NO_ERROR;
4683 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004684 case 1026: { // Get layer tracing status
4685 reply->writeBool(mTracing.isEnabled());
4686 return NO_ERROR;
4687 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004688 // Is a DisplayColorSetting supported?
4689 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004690 const auto display = getDefaultDisplayDevice();
4691 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004692 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004693 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004694
4695 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4696 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004697 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004698 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004699 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004700 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004701 reply->writeBool(true);
4702 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004703 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004704 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004705 break;
4706 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004707 reply->writeBool(
4708 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004709 break;
4710 }
4711 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004712 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004713 // Is VrFlinger active?
4714 case 1028: {
4715 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004716 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004717 return NO_ERROR;
4718 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004719 // Set buffer size for SF tracing (value in KB)
4720 case 1029: {
4721 n = data.readInt32();
4722 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4723 ALOGW("Invalid buffer size: %d KB", n);
4724 reply->writeInt32(BAD_VALUE);
4725 return BAD_VALUE;
4726 }
4727
4728 ALOGD("Updating trace buffer to %d KB", n);
4729 mTracing.setBufferSize(n * 1024);
4730 reply->writeInt32(NO_ERROR);
4731 return NO_ERROR;
4732 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004733 // Is device color managed?
4734 case 1030: {
4735 reply->writeBool(useColorManagement);
4736 return NO_ERROR;
4737 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004738 // Override default composition data space
4739 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4740 // && adb shell stop zygote && adb shell start zygote
4741 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4742 // adb shell stop zygote && adb shell start zygote
4743 case 1031: {
4744 Mutex::Autolock _l(mStateLock);
4745 n = data.readInt32();
4746 if (n) {
4747 n = data.readInt32();
4748 if (n) {
4749 Dataspace dataspace = static_cast<Dataspace>(n);
4750 if (!validateCompositionDataspace(dataspace)) {
4751 return BAD_VALUE;
4752 }
4753 mDefaultCompositionDataspace = dataspace;
4754 }
4755 n = data.readInt32();
4756 if (n) {
4757 Dataspace dataspace = static_cast<Dataspace>(n);
4758 if (!validateCompositionDataspace(dataspace)) {
4759 return BAD_VALUE;
4760 }
4761 mWideColorGamutCompositionDataspace = dataspace;
4762 }
4763 } else {
4764 // restore composition data space.
4765 mDefaultCompositionDataspace = defaultCompositionDataspace;
4766 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4767 }
4768 return NO_ERROR;
4769 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004770 // Set trace flags
4771 case 1033: {
4772 n = data.readUint32();
4773 ALOGD("Updating trace flags to 0x%x", n);
4774 mTracing.setTraceFlags(n);
4775 reply->writeInt32(NO_ERROR);
4776 return NO_ERROR;
4777 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004778 case 1034: {
4779 // TODO(b/129297325): expose this via developer menu option
4780 n = data.readInt32();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004781 if (n && !mRefreshRateOverlay &&
4782 mRefreshRateConfigs->refreshRateSwitchingSupported()) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07004783 RefreshRateType type;
4784 {
4785 std::lock_guard<std::mutex> lock(mActiveConfigLock);
4786 type = mDesiredActiveConfig.type;
4787 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004788 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07004789 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004790 } else if (!n) {
4791 mRefreshRateOverlay.reset();
4792 }
4793 return NO_ERROR;
4794 }
Ady Abraham34392f72019-04-10 11:29:27 -07004795 case 1035: {
4796 n = data.readInt32();
4797 mDebugDisplayConfigSetByBackdoor = false;
4798 if (n >= 0) {
4799 const auto displayToken = getInternalDisplayToken();
4800 status_t result = setAllowedDisplayConfigs(displayToken, {n});
4801 if (result != NO_ERROR) {
4802 return result;
4803 }
4804 mDebugDisplayConfigSetByBackdoor = true;
4805 }
4806 return NO_ERROR;
4807 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004808 }
4809 }
4810 return err;
4811}
4812
Steven Thomas6d8110b2017-08-31 18:24:21 -07004813void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004814 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004815 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004816}
4817
Ana Krulec7d1d6832018-12-27 11:10:09 -08004818void SurfaceFlinger::repaintEverythingForHWC() {
4819 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004820 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004821}
4822
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004823// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4824class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004825public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004826 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4827 ~WindowDisconnector() {
4828 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004829 }
4830
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004831private:
4832 ANativeWindow* mWindow;
4833 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004834};
4835
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004836status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07004837 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
4838 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004839 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07004840 uint32_t reqWidth, uint32_t reqHeight,
4841 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08004842 ISurfaceComposer::Rotation rotation,
4843 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004844 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004845
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004846 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004847
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07004848 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
4849
Chia-I Wu20261cb2018-08-23 12:55:44 -07004850 sp<DisplayDevice> display;
4851 {
4852 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004853
Chia-I Wu20261cb2018-08-23 12:55:44 -07004854 display = getDisplayDeviceLocked(displayToken);
4855 if (!display) return BAD_VALUE;
4856
Chia-I Wucb023152018-08-28 12:57:23 -07004857 // set the requested width/height to the logical display viewport size
4858 // by default
4859 if (reqWidth == 0 || reqHeight == 0) {
4860 reqWidth = uint32_t(display->getViewport().width());
4861 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07004862 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004863 }
4864
Peiyong Lin0e003c92018-09-17 11:09:51 -07004865 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08004866 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004867
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08004868 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4869 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07004870 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07004871 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004872}
4873
chaviw93df2ea2019-04-30 16:45:12 -07004874static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
4875 switch (colorMode) {
4876 case ColorMode::DISPLAY_P3:
4877 case ColorMode::BT2100_PQ:
4878 case ColorMode::BT2100_HLG:
4879 case ColorMode::DISPLAY_BT2020:
4880 return Dataspace::DISPLAY_P3;
4881 default:
4882 return Dataspace::V0_SRGB;
4883 }
4884}
4885
4886const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
4887 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
4888 if (displayToken) {
4889 return getDisplayDeviceLocked(displayToken);
4890 }
4891 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
4892 // may not have a displayId.
4893 for (const auto& [token, display] : mDisplays) {
4894 if (display->getLayerStack() == displayOrLayerStack) {
4895 return display;
4896 }
4897 }
4898 return nullptr;
4899}
4900
4901status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
4902 sp<GraphicBuffer>* outBuffer) {
4903 sp<DisplayDevice> display;
4904 uint32_t width;
4905 uint32_t height;
4906 ui::Transform::orientation_flags captureOrientation;
4907 {
4908 Mutex::Autolock _l(mStateLock);
4909 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
4910 if (!display) {
4911 return BAD_VALUE;
4912 }
4913
4914 width = uint32_t(display->getViewport().width());
4915 height = uint32_t(display->getViewport().height());
4916
4917 captureOrientation = fromSurfaceComposerRotation(
4918 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07004919 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
4920 captureOrientation = ui::Transform::orientation_flags::ROT_270;
4921 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
4922 captureOrientation = ui::Transform::orientation_flags::ROT_90;
4923 }
chaviw93df2ea2019-04-30 16:45:12 -07004924 *outDataspace =
4925 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
4926 }
4927
4928 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
4929 false /* captureSecureLayers */);
4930
4931 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4932 std::placeholders::_1);
4933 bool ignored = false;
4934 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
4935 false /* useIdentityTransform */,
4936 ignored /* outCapturedSecureLayers */);
4937}
4938
Robert Carr866455f2019-04-02 16:28:26 -07004939status_t SurfaceFlinger::captureLayers(
4940 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
4941 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
4942 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
4943 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004944 ATRACE_CALL();
4945
4946 class LayerRenderArea : public RenderArea {
4947 public:
Robert Carr578038f2018-03-09 12:25:24 -08004948 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004949 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
4950 bool childrenOnly)
4951 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08004952 mLayer(layer),
4953 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004954 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08004955 mFlinger(flinger),
4956 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004957 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004958 Rect getBounds() const override {
4959 const Layer::State& layerState(mLayer->getDrawingState());
4960 return mLayer->getBufferSize(layerState);
4961 }
Marissa Wall61c58622018-07-18 10:12:20 -07004962 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004963 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07004964 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08004965 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004966 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08004967 }
chaviwa76b2712017-09-20 12:02:26 -07004968 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004969 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004970 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004971 Rect getSourceCrop() const override {
4972 if (mCrop.isEmpty()) {
4973 return getBounds();
4974 } else {
4975 return mCrop;
4976 }
4977 }
Robert Carr578038f2018-03-09 12:25:24 -08004978 class ReparentForDrawing {
4979 public:
4980 const sp<Layer>& oldParent;
4981 const sp<Layer>& newParent;
4982
Vishnu Nair4351ad52019-02-11 14:13:02 -08004983 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
4984 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08004985 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08004986 // Compute and cache the bounds for the new parent layer.
4987 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07004988 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08004989 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08004990 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08004991 };
4992
4993 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004994 const Rect sourceCrop = getSourceCrop();
4995 // no need to check rotation because there is none
4996 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
4997 sourceCrop.height() != getReqHeight();
4998
Robert Carr578038f2018-03-09 12:25:24 -08004999 if (!mChildrenOnly) {
5000 mTransform = mLayer->getTransform().inverse();
5001 drawLayers();
5002 } else {
5003 Rect bounds = getBounds();
chaviw32811fd2019-08-12 13:16:09 -07005004 // In the "childrenOnly" case we reparent the children to a screenshot
5005 // layer which has no properties set and which does not draw.
5006 sp<ContainerLayer> screenshotParentLayer =
5007 mFlinger->getFactory().createContainerLayer(
5008 LayerCreationArgs(mFlinger, nullptr, String8("Screenshot Parent"),
5009 bounds.getWidth(), bounds.getHeight(), 0,
5010 LayerMetadata()));
Robert Carr578038f2018-03-09 12:25:24 -08005011
Vishnu Nair4351ad52019-02-11 14:13:02 -08005012 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005013 drawLayers();
5014 }
5015 }
chaviwa76b2712017-09-20 12:02:26 -07005016
chaviwa76b2712017-09-20 12:02:26 -07005017 private:
chaviw7206d492017-11-10 16:16:12 -08005018 const sp<Layer> mLayer;
5019 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005020
Peiyong Linefefaac2018-08-17 12:27:51 -07005021 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005022 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005023
5024 SurfaceFlinger* mFlinger;
5025 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005026 };
5027
Robert Carrc0df3122019-04-11 13:18:21 -07005028 int reqWidth = 0;
5029 int reqHeight = 0;
5030 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005031 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005032 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005033
Robert Carrc0df3122019-04-11 13:18:21 -07005034 {
5035 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005036
Robert Carrc0df3122019-04-11 13:18:21 -07005037 parent = fromHandle(layerHandleBinder);
5038 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5039 ALOGE("captureLayers called with an invalid or removed parent");
5040 return NAME_NOT_FOUND;
5041 }
5042
5043 const int uid = IPCThreadState::self()->getCallingUid();
5044 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5045 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5046 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5047 return PERMISSION_DENIED;
5048 }
5049
5050 if (sourceCrop.width() <= 0) {
5051 crop.left = 0;
5052 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5053 }
5054
5055 if (sourceCrop.height() <= 0) {
5056 crop.top = 0;
5057 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5058 }
5059 reqWidth = crop.width() * frameScale;
5060 reqHeight = crop.height() * frameScale;
5061
5062 for (const auto& handle : excludeHandles) {
5063 sp<Layer> excludeLayer = fromHandle(handle);
5064 if (excludeLayer != nullptr) {
5065 excludeLayers.emplace(excludeLayer);
5066 } else {
5067 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5068 return NAME_NOT_FOUND;
5069 }
5070 }
5071 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005072
Chia-I Wu20261cb2018-08-23 12:55:44 -07005073 // really small crop or frameScale
5074 if (reqWidth <= 0) {
5075 reqWidth = 1;
5076 }
5077 if (reqHeight <= 0) {
5078 reqHeight = 1;
5079 }
5080
Robert Carr866455f2019-04-02 16:28:26 -07005081 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5082 auto traverseLayers = [parent, childrenOnly,
5083 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005084 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5085 if (!layer->isVisible()) {
5086 return;
Robert Carr578038f2018-03-09 12:25:24 -08005087 } else if (childrenOnly && layer == parent.get()) {
5088 return;
chaviwa76b2712017-09-20 12:02:26 -07005089 }
Robert Carr866455f2019-04-02 16:28:26 -07005090
5091 sp<Layer> p = layer;
5092 while (p != nullptr) {
5093 if (excludeLayers.count(p) != 0) {
5094 return;
5095 }
5096 p = p->getParent();
5097 }
5098
chaviwa76b2712017-09-20 12:02:26 -07005099 visitor(layer);
5100 });
5101 };
Robert Carr108b2c72019-04-02 16:32:58 -07005102
5103 bool outCapturedSecureLayers = false;
5104 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5105 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005106}
5107
5108status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5109 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005110 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005111 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005112 bool useIdentityTransform,
5113 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005114 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005115
Peiyong Lin0e003c92018-09-17 11:09:51 -07005116 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005117 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5118 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005119 *outBuffer =
5120 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5121 static_cast<android_pixel_format>(reqPixelFormat), 1,
5122 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005123
Robert Carr108b2c72019-04-02 16:32:58 -07005124 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5125 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005126}
5127
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005128status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5129 TraverseLayersFunction traverseLayers,
5130 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005131 bool useIdentityTransform,
5132 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005133 // This mutex protects syncFd and captureResult for communication of the return values from the
5134 // main thread back to this Binder thread
5135 std::mutex captureMutex;
5136 std::condition_variable captureCondition;
5137 std::unique_lock<std::mutex> captureLock(captureMutex);
5138 int syncFd = -1;
5139 std::optional<status_t> captureResult;
5140
Robert Carr03480e22018-01-04 16:02:06 -08005141 const int uid = IPCThreadState::self()->getCallingUid();
5142 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5143
Dominik Laskowski8c001672018-05-30 16:52:06 -07005144 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005145 // If there is a refresh pending, bug out early and tell the binder thread to try again
5146 // after the refresh.
5147 if (mRefreshPending) {
5148 ATRACE_NAME("Skipping screenshot for now");
5149 std::unique_lock<std::mutex> captureLock(captureMutex);
5150 captureResult = std::make_optional<status_t>(EAGAIN);
5151 captureCondition.notify_one();
5152 return;
5153 }
5154
5155 status_t result = NO_ERROR;
5156 int fd = -1;
5157 {
5158 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005159 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005160 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005161 useIdentityTransform, forSystem, &fd,
5162 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005163 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005164 }
5165
5166 {
5167 std::unique_lock<std::mutex> captureLock(captureMutex);
5168 syncFd = fd;
5169 captureResult = std::make_optional<status_t>(result);
5170 captureCondition.notify_one();
5171 }
5172 });
5173
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005174 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005175 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005176 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005177 while (*captureResult == EAGAIN) {
5178 captureResult.reset();
5179 result = postMessageAsync(message);
5180 if (result != NO_ERROR) {
5181 return result;
5182 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005183 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005184 }
5185 result = *captureResult;
5186 }
5187
5188 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005189 sync_wait(syncFd, -1);
5190 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005191 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005192
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005193 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005194}
5195
chaviwa76b2712017-09-20 12:02:26 -07005196void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005197 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005198 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5199 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005200 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005201
chaviwa76b2712017-09-20 12:02:26 -07005202 const auto reqWidth = renderArea.getReqWidth();
5203 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005204 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005205 const auto transform = renderArea.getTransform();
5206 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005207
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005208 renderengine::DisplaySettings clientCompositionDisplay;
5209 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005210
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005211 // assume that bounds are never offset, and that they are the same as the
5212 // buffer bounds.
5213 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005214 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005215 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005216
5217 // Now take into account the rotation flag. We append a transform that
5218 // rotates the layer stack about the origin, then translate by buffer
5219 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005220 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005221 int displacementX = 0;
5222 int displacementY = 0;
5223 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5224 switch (rotation) {
5225 case ui::Transform::ROT_90:
5226 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005227 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005228 break;
5229 case ui::Transform::ROT_180:
5230 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005231 displacementY = renderArea.getBounds().getWidth();
5232 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005233 break;
5234 case ui::Transform::ROT_270:
5235 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005236 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005237 break;
5238 default:
5239 break;
5240 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005241
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005242 // We need to transform the clipping window into the right spot.
5243 // First, rotate the clipping rectangle by the rotation hint to get the
5244 // right orientation
5245 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5246 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5247 const vec4 rotClipTL = rotMatrix * clipTL;
5248 const vec4 rotClipBR = rotMatrix * clipBR;
5249 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5250 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5251 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5252 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5253
5254 // Now reposition the clipping rectangle with the displacement vector
5255 // computed above.
5256 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005257 clientCompositionDisplay.clip =
5258 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5259 newClipRight + displacementX, newClipBottom + displacementY);
5260
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005261 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005262 clientCompositionDisplay.globalTransform =
5263 clipTransform * clientCompositionDisplay.globalTransform;
5264
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005265 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5266 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005267
chaviw50da5042018-04-09 13:49:37 -07005268 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005269
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005270 renderengine::LayerSettings fillLayer;
5271 fillLayer.source.buffer.buffer = nullptr;
5272 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5273 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5274 fillLayer.alpha = half(alpha);
5275 clientCompositionLayers.push_back(fillLayer);
5276
5277 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005278 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005279 const bool supportProtectedContent = false;
5280 Region clip(renderArea.getBounds());
5281 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5282 clip,
5283 useIdentityTransform,
5284 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5285 renderArea.isSecure(),
5286 supportProtectedContent,
5287 clearRegion,
5288 };
5289 auto result = layer->prepareClientComposition(targetSettings);
5290 if (result) {
5291 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005292 }
chaviwa76b2712017-09-20 12:02:26 -07005293 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005294
5295 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005296 // Use an empty fence for the buffer fence, since we just created the buffer so
5297 // there is no need for synchronization with the GPU.
5298 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005299 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005300 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005301 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005302 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005303
5304 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005305}
5306
chaviwa76b2712017-09-20 12:02:26 -07005307status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5308 TraverseLayersFunction traverseLayers,
5309 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005310 bool useIdentityTransform, bool forSystem,
5311 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005312 ATRACE_CALL();
5313
chaviwa76b2712017-09-20 12:02:26 -07005314 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005315 outCapturedSecureLayers =
5316 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005317 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005318
Robert Carr03480e22018-01-04 16:02:06 -08005319 // We allow the system server to take screenshots of secure layers for
5320 // use in situations like the Screen-rotation animation and place
5321 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005322 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005323 ALOGW("FB is protected: PERMISSION_DENIED");
5324 return PERMISSION_DENIED;
5325 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005326 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005327 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005328}
5329
chaviw95ef3c42019-02-14 10:55:09 -08005330void SurfaceFlinger::setInputWindowsFinished() {
5331 Mutex::Autolock _l(mStateLock);
5332
5333 mPendingSyncInputWindows = false;
5334 mTransactionCV.broadcast();
5335}
chaviw5f21a5e2019-02-14 10:00:34 -08005336
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005337// ---------------------------------------------------------------------------
5338
Dan Stoza412903f2017-04-27 13:42:17 -07005339void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5340 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005341}
5342
Dan Stoza412903f2017-04-27 13:42:17 -07005343void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5344 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005345}
5346
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005347void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005348 const LayerVector::Visitor& visitor) {
5349 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005350 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005351 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005352 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005353 continue;
5354 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005355 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005356 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005357 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005358 return;
5359 }
chaviwa76b2712017-09-20 12:02:26 -07005360 if (!layer->isVisible()) {
5361 return;
5362 }
5363 visitor(layer);
5364 });
5365 }
5366}
5367
Dominik Laskowski22488f62019-03-28 09:53:04 -07005368void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5369 const std::vector<int32_t>& allowedConfigs) {
5370 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08005371 return;
5372 }
5373
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005374 const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
5375 allowedConfigs.end());
5376 if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
5377 return;
5378 }
5379
Ady Abraham838de062019-02-04 10:24:03 -08005380 ALOGV("Updating allowed configs");
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005381 mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
5382
5383 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5384 // that listeners that care about a change in allowed configs can get the notification.
5385 // Giving current ActiveConfig so that most other listeners would just drop the event
5386 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5387 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08005388
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005389 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5390 const auto& type = mScheduler->getPreferredRefreshRateType();
5391 const auto& config = mRefreshRateConfigs->getRefreshRateFromType(type);
5392 if (isDisplayConfigAllowed(config.configId)) {
5393 ALOGV("switching to Scheduler preferred config %d", config.configId);
5394 setDesiredActiveConfig({type, config.configId, Scheduler::ConfigEvent::Changed});
5395 } else {
5396 // Set the highest allowed config by iterating backwards on available refresh rates
5397 const auto& refreshRates = mRefreshRateConfigs->getRefreshRateMap();
5398 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
5399 if (isDisplayConfigAllowed(iter->second.configId)) {
5400 ALOGV("switching to allowed config %d", iter->second.configId);
5401 setDesiredActiveConfig(
5402 {iter->first, iter->second.configId, Scheduler::ConfigEvent::Changed});
5403 break;
5404 }
5405 }
5406 }
5407 } else if (!allowedConfigs.empty()) {
5408 ALOGV("switching to config %d", allowedConfigs[0]);
5409 setDesiredActiveConfig(
5410 {RefreshRateType::DEFAULT, allowedConfigs[0], Scheduler::ConfigEvent::Changed});
5411 }
Ady Abraham838de062019-02-04 10:24:03 -08005412}
5413
Dominik Laskowski22488f62019-03-28 09:53:04 -07005414status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005415 const std::vector<int32_t>& allowedConfigs) {
5416 ATRACE_CALL();
5417
Dominik Laskowski22488f62019-03-28 09:53:04 -07005418 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005419 return BAD_VALUE;
5420 }
5421
Ady Abraham34392f72019-04-10 11:29:27 -07005422 if (mDebugDisplayConfigSetByBackdoor) {
5423 // ignore this request as config is overridden by backdoor
5424 return NO_ERROR;
5425 }
5426
Ady Abraham838de062019-02-04 10:24:03 -08005427 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005428 const auto display = getDisplayDeviceLocked(displayToken);
5429 if (!display) {
5430 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5431 displayToken.get());
5432 } else if (display->isVirtual()) {
5433 ALOGW("Attempt to set allowed display configs for virtual display");
5434 } else {
5435 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5436 }
Ady Abraham838de062019-02-04 10:24:03 -08005437 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005438
Ady Abraham838de062019-02-04 10:24:03 -08005439 return NO_ERROR;
5440}
5441
Dominik Laskowski22488f62019-03-28 09:53:04 -07005442status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005443 std::vector<int32_t>* outAllowedConfigs) {
5444 ATRACE_CALL();
5445
Dominik Laskowski22488f62019-03-28 09:53:04 -07005446 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005447 return BAD_VALUE;
5448 }
5449
Dominik Laskowski22488f62019-03-28 09:53:04 -07005450 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005451
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005452 const auto display = getDisplayDeviceLocked(displayToken);
5453 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005454 return NAME_NOT_FOUND;
5455 }
5456
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005457 if (display->isPrimary()) {
5458 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
5459 }
5460
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005461 return NO_ERROR;
5462}
5463
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005464void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005465 mFlinger->setInputWindowsFinished();
5466}
5467
Robert Carrc0df3122019-04-11 13:18:21 -07005468sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5469 BBinder *b = handle->localBinder();
5470 if (b == nullptr) {
5471 return nullptr;
5472 }
5473 auto it = mLayersByLocalBinderToken.find(b);
5474 if (it != mLayersByLocalBinderToken.end()) {
5475 return it->second.promote();
5476 }
5477 return nullptr;
5478}
5479
Alec Mouri4545a8a2019-08-08 20:05:32 -07005480void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5481 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5482}
5483
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005484} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005485
Mathias Agopian3f844832013-08-07 21:24:32 -07005486#if defined(__gl_h_)
5487#error "don't include gl/gl.h in this file"
5488#endif
5489
5490#if defined(__gl2_h_)
5491#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005492#endif