blob: 010b52efffa78476da67b38d34f115b67b7c126e [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
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700125using namespace std::string_literals;
126
Jaesoo Lee43518572017-01-23 19:03:16 +0900127using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900128using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900129using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800130
Ady Abraham8532d012019-05-08 14:50:56 -0700131using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800132using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700133using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700134using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800135using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700136using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700137using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900138
Steven Thomasb02664d2017-07-26 18:48:28 -0700139namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700140
141#pragma clang diagnostic push
142#pragma clang diagnostic error "-Wswitch-enum"
143
144bool isWideColorMode(const ColorMode colorMode) {
145 switch (colorMode) {
146 case ColorMode::DISPLAY_P3:
147 case ColorMode::ADOBE_RGB:
148 case ColorMode::DCI_P3:
149 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700150 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700151 case ColorMode::BT2100_PQ:
152 case ColorMode::BT2100_HLG:
153 return true;
154 case ColorMode::NATIVE:
155 case ColorMode::STANDARD_BT601_625:
156 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
157 case ColorMode::STANDARD_BT601_525:
158 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
159 case ColorMode::STANDARD_BT709:
160 case ColorMode::SRGB:
161 return false;
162 }
163 return false;
164}
165
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700166ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
167 switch (rotation) {
168 case ISurfaceComposer::eRotateNone:
169 return ui::Transform::ROT_0;
170 case ISurfaceComposer::eRotate90:
171 return ui::Transform::ROT_90;
172 case ISurfaceComposer::eRotate180:
173 return ui::Transform::ROT_180;
174 case ISurfaceComposer::eRotate270:
175 return ui::Transform::ROT_270;
176 }
177 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
178 return ui::Transform::ROT_0;
179}
180
Peiyong Linfca547f2018-07-09 13:03:33 -0700181#pragma clang diagnostic pop
182
Steven Thomasb02664d2017-07-26 18:48:28 -0700183class ConditionalLock {
184public:
185 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
186 if (lock) {
187 mMutex.lock();
188 }
189 }
190 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
191private:
192 Mutex& mMutex;
193 bool mLocked;
194};
Peiyong Linfca547f2018-07-09 13:03:33 -0700195
Peiyong Lin9d846a52018-11-05 13:18:20 -0800196// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
197bool validateCompositionDataspace(Dataspace dataspace) {
198 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
199}
200
Steven Thomasb02664d2017-07-26 18:48:28 -0700201} // namespace anonymous
202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203// ---------------------------------------------------------------------------
204
Mathias Agopian99b49842011-06-27 16:05:52 -0700205const String16 sHardwareTest("android.permission.HARDWARE_TEST");
206const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
207const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
208const String16 sDump("android.permission.DUMP");
209
210// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700211int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700212bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800213uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800214bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800215bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800216int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600217bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700218int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700219bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700220bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700221Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
222ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
223Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
224ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700225
Kalle Raitaa099a242017-01-11 11:17:29 -0800226std::string getHwcServiceName() {
227 char value[PROPERTY_VALUE_MAX] = {};
228 property_get("debug.sf.hwc_service_name", value, "default");
229 ALOGI("Using HWComposer service: '%s'", value);
230 return std::string(value);
231}
232
233bool useTrebleTestingOverride() {
234 char value[PROPERTY_VALUE_MAX] = {};
235 property_get("debug.sf.treble_testing_override", value, "false");
236 ALOGI("Treble testing override: '%s'", value);
237 return std::string(value) == "true";
238}
239
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800240std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
241 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800242 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700243 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800244 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800246 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700247 return std::string("Enhanced");
248 default:
249 return std::string("Unknown ") +
250 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252}
253
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700254SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800255
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700256SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
257 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700258 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700259 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700260 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700261 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700262 mCompositionEngine(mFactory.createCompositionEngine()),
Valerie Haud251afb2019-03-29 14:19:02 -0700263 mPhaseOffsets(mFactory.createPhaseOffsets()),
264 mPendingSyncInputWindows(false) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800265
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700266SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800267 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800268
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900269 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800270
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900271 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700272
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900273 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700274
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800276
Steven Thomas050b2c82017-03-06 11:45:16 -0800277 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800279
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 mDefaultCompositionDataspace =
287 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700288 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
289 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 defaultCompositionDataspace = mDefaultCompositionDataspace;
291 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
292 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
293 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
294 wideColorGamutCompositionPixelFormat =
295 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700296
Yichi Chenda901bf2019-06-28 14:58:27 +0800297 mColorSpaceAgnosticDataspace =
298 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
303 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
304 switch (tmpPrimaryDisplayOrientation) {
305 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700306 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800307 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700309 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800310 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700312 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800313 break;
314 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700315 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800316 break;
317 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700318 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800319
Sundong Ahn85131bd2019-02-18 15:51:53 +0900320 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800321
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800322 // debugging stuff...
323 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700324
Mathias Agopianb4b17302013-03-20 18:36:41 -0700325 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700326 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800328 property_get("debug.sf.showupdates", value, "0");
329 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700330
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700331 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000332
333 // DDMS debugging deprecated (b/120782499)
334 property_get("debug.sf.ddms", value, "0");
335 int debugDdms = atoi(value);
336 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700337
338 property_get("debug.sf.disable_backpressure", value, "0");
339 mPropagateBackpressure = !atoi(value);
340 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700341
Ady Abrahamadb9a992019-09-19 21:21:55 +0000342 property_get("debug.sf.enable_gl_backpressure", value, "0");
343 mPropagateBackpressureClientComposition = atoi(value);
344 ALOGI_IF(mPropagateBackpressureClientComposition,
345 "Enabling backpressure propagation for Client Composition");
346
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800347 property_get("debug.sf.enable_hwc_vds", value, "0");
348 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800349 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800350
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800351 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800352 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800353 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700354
Yiwei Zhang243b3782018-05-15 17:40:04 -0700355 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700356 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
357 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
358
Dan Stozaec460082018-12-17 15:35:09 -0800359 property_get("debug.sf.luma_sampling", value, "1");
360 mLumaSampling = atoi(value);
361
Romain Guy11d63f42017-07-20 12:47:14 -0700362 // We should be reading 'persist.sys.sf.color_saturation' here
363 // but since /data may be encrypted, we need to wait until after vold
364 // comes online to attempt to read the property. The property is
365 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800366
367 if (useTrebleTestingOverride()) {
368 // Without the override SurfaceFlinger cannot connect to HIDL
369 // services that are not listed in the manifests. Considered
370 // deriving the setting from the set service name, but it
371 // would be brittle if the name that's not 'default' is used
372 // for production purposes later on.
373 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
374 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800375}
376
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800377void SurfaceFlinger::onFirstRef()
378{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800379 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800380}
381
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700382SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800383
Dan Stozac7014012014-02-14 15:03:43 -0800384void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800385{
386 // the window manager died on us. prepare its eulogy.
387
Andy McFadden13a082e2012-08-24 10:16:42 -0700388 // restore initial conditions (default device unblank, etc)
389 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800390
391 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700392 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800393}
394
Robert Carr1db73f62016-12-21 12:58:51 -0800395static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700396 status_t err = client->initCheck();
397 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800398 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399 }
Robert Carr1db73f62016-12-21 12:58:51 -0800400 return nullptr;
401}
402
403sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
404 return initClient(new Client(this));
405}
406
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700407sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
408 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700409{
410 class DisplayToken : public BBinder {
411 sp<SurfaceFlinger> flinger;
412 virtual ~DisplayToken() {
413 // no more references, this display must be terminated
414 Mutex::Autolock _l(flinger->mStateLock);
415 flinger->mCurrentState.displays.removeItem(this);
416 flinger->setTransactionFlags(eDisplayTransactionNeeded);
417 }
418 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700419 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700420 : flinger(flinger) {
421 }
422 };
423
424 sp<BBinder> token = new DisplayToken(this);
425
426 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700427 // Display ID is assigned when virtual display is allocated by HWC.
428 DisplayDeviceState state;
429 state.isSecure = secure;
430 state.displayName = displayName;
431 mCurrentState.displays.add(token, state);
432 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700433 return token;
434}
435
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700436void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700437 Mutex::Autolock _l(mStateLock);
438
Dominik Laskowski075d3172018-05-24 15:50:06 -0700439 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
440 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700441 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700442 return;
443 }
444
Dominik Laskowski075d3172018-05-24 15:50:06 -0700445 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
446 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700447 ALOGE("destroyDisplay called for non-virtual display");
448 return;
449 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700450 mInterceptor->saveDisplayDeletion(state.sequenceId);
451 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700452 setTransactionFlags(eDisplayTransactionNeeded);
453}
454
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800455std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
456 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700457
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800458 const auto internalDisplayId = getInternalDisplayIdLocked();
459 if (!internalDisplayId) {
460 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700461 }
462
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800463 std::vector<PhysicalDisplayId> displayIds;
464 displayIds.reserve(mPhysicalDisplayTokens.size());
465 displayIds.push_back(internalDisplayId->value);
466
467 for (const auto& [id, token] : mPhysicalDisplayTokens) {
468 if (id != *internalDisplayId) {
469 displayIds.push_back(id.value);
470 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700471 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700472
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800473 return displayIds;
474}
475
476sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
477 Mutex::Autolock lock(mStateLock);
478 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700479}
480
Ady Abraham37965d42018-11-01 13:43:32 -0700481status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
482 if (!outGetColorManagement) {
483 return BAD_VALUE;
484 }
485 *outGetColorManagement = useColorManagement;
486 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700487}
488
Lloyd Pique441d5042018-10-18 16:49:51 -0700489HWComposer& SurfaceFlinger::getHwComposer() const {
490 return mCompositionEngine->getHwComposer();
491}
492
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700493renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
494 return mCompositionEngine->getRenderEngine();
495}
496
Lloyd Pique70d91362018-10-18 16:02:55 -0700497compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
498 return *mCompositionEngine.get();
499}
500
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800501void SurfaceFlinger::bootFinished()
502{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700503 if (mStartPropertySetThread->join() != NO_ERROR) {
504 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800505 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800506 const nsecs_t now = systemTime();
507 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000508 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700509
Mikael Pessa90092f42019-08-26 17:22:04 -0700510 mFrameTracer->initialize();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700511
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700512 // wait patiently for the window manager death
513 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700514 mWindowManager = defaultServiceManager()->getService(name);
515 if (mWindowManager != 0) {
516 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700517 }
Robert Carr720e5062018-07-30 17:45:14 -0700518 sp<IBinder> input(defaultServiceManager()->getService(
519 String16("inputflinger")));
520 if (input == nullptr) {
521 ALOGE("Failed to link to input service");
522 } else {
523 mInputFlinger = interface_cast<IInputFlinger>(input);
524 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700525
Steven Thomas050b2c82017-03-06 11:45:16 -0800526 if (mVrFlinger) {
527 mVrFlinger->OnBootFinished();
528 }
529
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700530 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700531 // formerly we would just kill the process, but we now ask it to exit so it
532 // can choose where to stop the animation.
533 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700534
535 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
536 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
537 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700538
Ana Krulecbd6654b2019-02-15 15:18:15 -0800539 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800540 readPersistentProperties();
541 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800542
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700543 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
544 // set the refresh rate according to the policy
545 const auto& performanceRefreshRate =
546 mRefreshRateConfigs->getRefreshRateFromType(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800547
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700548 if (isDisplayConfigAllowed(performanceRefreshRate.configId)) {
549 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
550 } else {
551 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
552 }
Ana Krulecbd6654b2019-02-15 15:18:15 -0800553 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800554 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800555}
556
Dan Stoza436ccf32018-06-21 12:10:12 -0700557uint32_t SurfaceFlinger::getNewTexture() {
558 {
559 std::lock_guard lock(mTexturePoolMutex);
560 if (!mTexturePool.empty()) {
561 uint32_t name = mTexturePool.back();
562 mTexturePool.pop_back();
563 ATRACE_INT("TexturePoolSize", mTexturePool.size());
564 return name;
565 }
566
567 // The pool was too small, so increase it for the future
568 ++mTexturePoolSize;
569 }
570
571 // The pool was empty, so we need to get a new texture name directly using a
572 // blocking call to the main thread
573 uint32_t name = 0;
574 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
575 return name;
576}
577
Mathias Agopian3f844832013-08-07 21:24:32 -0700578void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700579 std::lock_guard lock(mTexturePoolMutex);
580 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
581 // to actually delete this or not based on mTexturePoolSize
582 mTexturePool.push_back(texture);
583 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700584}
585
Wei Wangf9b05ee2017-07-19 20:59:39 -0700586// Do not call property_set on main thread which will be blocked by init
587// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700589 ALOGI( "SurfaceFlinger's main thread ready to run. "
590 "Initializing graphics H/W...");
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700591 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900592
Steven Thomasb02664d2017-07-26 18:48:28 -0700593 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800594
Steven Thomasb02664d2017-07-26 18:48:28 -0700595 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700596 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800597 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700598 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
599 renderengine::RenderEngineCreationArgs::Builder()
600 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
601 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
602 .setUseColorManagerment(useColorManagement)
603 .setEnableProtectedContext(enable_protected_contents(false))
604 .setPrecacheToneMapperShaderOnly(false)
605 .setContextPriority(useContextPriority
606 ? renderengine::RenderEngine::ContextPriority::HIGH
607 : renderengine::RenderEngine::ContextPriority::MEDIUM)
608 .build()));
Steven Thomasb02664d2017-07-26 18:48:28 -0700609
610 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
611 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700612 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
613 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800614 // Process any initial hotplug and resulting display changes.
615 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700616 const auto display = getDefaultDisplayDeviceLocked();
617 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700618 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700619 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800620
Steven Thomas050b2c82017-03-06 11:45:16 -0800621 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700622 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700623 // This callback is called from the vr flinger dispatch thread. We
624 // need to call signalTransaction(), which requires holding
625 // mStateLock when we're not on the main thread. Acquiring
626 // mStateLock from the vr flinger dispatch thread might trigger a
627 // deadlock in surface flinger (see b/66916578), so post a message
628 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700629 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700630 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
631 mVrFlingerRequestsDisplay = requestDisplay;
632 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700633 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800634 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700635 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
636 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700637 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700638 .value_or(0),
639 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800640 if (!mVrFlinger) {
641 ALOGE("Failed to start vrflinger");
642 }
643 }
644
Mathias Agopian92a979a2012-08-02 18:32:23 -0700645 // initialize our drawing state
646 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700647
Andy McFadden13a082e2012-08-24 10:16:42 -0700648 // set initial conditions (e.g. unblank default device)
649 initializeDisplays();
650
Steven Thomas137d4bc2019-07-25 16:55:14 -0700651 char primeShaderCache[PROPERTY_VALUE_MAX];
652 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
653 if (atoi(primeShaderCache)) {
654 getRenderEngine().primeCache();
655 }
Dan Stoza4e637772016-07-28 13:31:51 -0700656
Wei Wangf9b05ee2017-07-19 20:59:39 -0700657 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700658
659 const bool presentFenceReliable =
660 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
661 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700662
663 if (mStartPropertySetThread->Start() != NO_ERROR) {
664 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800665 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800666
Dan Stoza9e56aa02015-11-02 13:00:03 -0800667 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700668}
669
Romain Guy11d63f42017-07-20 12:47:14 -0700670void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700671 Mutex::Autolock _l(mStateLock);
672
Romain Guy11d63f42017-07-20 12:47:14 -0700673 char value[PROPERTY_VALUE_MAX];
674
675 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800676 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700677 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800678 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100679
680 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700681 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800682
683 property_get("persist.sys.sf.color_mode", value, "0");
684 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700685}
686
Mathias Agopiana67e4182012-06-19 17:26:12 -0700687void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800688 // Start boot animation service by setting a property mailbox
689 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700690 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800691 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700692 if (mStartPropertySetThread->join() != NO_ERROR) {
693 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800694 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700695}
696
Mathias Agopian875d8e12013-06-07 15:35:48 -0700697size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700698 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700699}
700
Mathias Agopian875d8e12013-06-07 15:35:48 -0700701size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700702 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700703}
704
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800705// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800706
Jamie Gennis582270d2011-08-17 18:19:00 -0700707bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800708 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800709 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800710 return authenticateSurfaceTextureLocked(bufferProducer);
711}
712
713bool SurfaceFlinger::authenticateSurfaceTextureLocked(
714 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800715 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800716 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800717}
718
Brian Anderson6b376712017-04-04 10:51:39 -0700719status_t SurfaceFlinger::getSupportedFrameTimestamps(
720 std::vector<FrameEvent>* outSupported) const {
721 *outSupported = {
722 FrameEvent::REQUESTED_PRESENT,
723 FrameEvent::ACQUIRE,
724 FrameEvent::LATCH,
725 FrameEvent::FIRST_REFRESH_START,
726 FrameEvent::LAST_REFRESH_START,
727 FrameEvent::GPU_COMPOSITION_DONE,
728 FrameEvent::DEQUEUE_READY,
729 FrameEvent::RELEASE,
730 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700731 ConditionalLock _l(mStateLock,
732 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700733 if (!getHwComposer().hasCapability(
734 HWC2::Capability::PresentFenceIsNotReliable)) {
735 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
736 }
737 return NO_ERROR;
738}
739
Dominik Laskowski22488f62019-03-28 09:53:04 -0700740status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
741 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700742 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700743 return BAD_VALUE;
744 }
745
Dominik Laskowski22488f62019-03-28 09:53:04 -0700746 Mutex::Autolock lock(mStateLock);
747
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800748 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700749 if (!displayId) {
750 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700751 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700752
Mathias Agopian8b736f12012-08-13 17:54:26 -0700753 // TODO: Not sure if display density should handled by SF any longer
754 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700755 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700756 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700757 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800758 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700759 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700760 }
761 return density;
762 }
763 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700764 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700765 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700766 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700767 return getDensityFromProperty("ro.sf.lcd_density"); }
768 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700769
Dan Stoza7f7da322014-05-02 15:26:25 -0700770 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700771
Dominik Laskowski075d3172018-05-24 15:50:06 -0700772 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700773 DisplayInfo info = DisplayInfo();
774
Dan Stoza9e56aa02015-11-02 13:00:03 -0800775 float xdpi = hwConfig->getDpiX();
776 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700777
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700778 info.w = hwConfig->getWidth();
779 info.h = hwConfig->getHeight();
780 // Default display viewport to display width and height
781 info.viewportW = info.w;
782 info.viewportH = info.h;
783
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800784 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700785 // The density of the device is provided by a build property
786 float density = Density::getBuildDensity() / 160.0f;
787 if (density == 0) {
788 // the build doesn't provide a density -- this is wrong!
789 // use xdpi instead
790 ALOGE("ro.sf.lcd_density must be defined as a build property");
791 density = xdpi / 160.0f;
792 }
793 if (Density::getEmuDensity()) {
794 // if "qemu.sf.lcd_density" is specified, it overrides everything
795 xdpi = ydpi = density = Density::getEmuDensity();
796 density /= 160.0f;
797 }
798 info.density = density;
799
800 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700801 const auto display = getDefaultDisplayDeviceLocked();
802 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700803
804 // This is for screenrecord
805 const Rect viewport = display->getViewport();
806 if (viewport.isValid()) {
807 info.viewportW = uint32_t(viewport.getWidth());
808 info.viewportH = uint32_t(viewport.getHeight());
809 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700810 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 } else {
812 // TODO: where should this value come from?
813 static const int TV_DENSITY = 213;
814 info.density = TV_DENSITY / 160.0f;
815 info.orientation = 0;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700816
817 const auto display = getDisplayDeviceLocked(displayToken);
818 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700819 }
820
Dan Stoza7f7da322014-05-02 15:26:25 -0700821 info.xdpi = xdpi;
822 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800823 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700824 const auto refreshRateType =
825 mRefreshRateConfigs->getRefreshRateTypeFromHwcConfigId(hwConfig->getId());
Ady Abraham796beb02019-04-11 15:23:07 -0700826 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
827 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800828
Andy McFadden91b2ca82014-06-13 14:04:23 -0700829 // This is how far in advance a buffer must be queued for
830 // presentation at a given time. If you want a buffer to appear
831 // on the screen at time N, you must submit the buffer before
832 // (N - presentationDeadline).
833 //
834 // Normally it's one full refresh period (to give SF a chance to
835 // latch the buffer), but this can be reduced by configuring a
836 // DispSync offset. Any additional delays introduced by the hardware
837 // composer or panel must be accounted for here.
838 //
839 // We add an additional 1ms to allow for processing time and
840 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700841 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700842
843 // All non-virtual displays are currently considered secure.
844 info.secure = true;
845
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800846 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700847 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800848 std::swap(info.w, info.h);
849 }
850
Michael Wright28f24d02016-07-12 13:30:53 -0700851 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700852 }
853
Dan Stoza7f7da322014-05-02 15:26:25 -0700854 return NO_ERROR;
855}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700856
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700857status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
858 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700859 return BAD_VALUE;
860 }
861
Ana Krulecc2870422019-01-29 19:00:58 -0800862 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700863 return NO_ERROR;
864}
865
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700866int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
867 const auto display = getDisplayDevice(displayToken);
868 if (!display) {
869 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800870 return BAD_VALUE;
871 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700872
Steven Thomasc9098452019-09-30 17:15:05 -0700873 if (display->isPrimary()) {
874 std::lock_guard<std::mutex> lock(mActiveConfigLock);
875 if (mDesiredActiveConfigChanged) {
876 return mDesiredActiveConfig.configId;
877 } else {
878 return display->getActiveConfig();
879 }
880 } else {
881 return display->getActiveConfig();
882 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700883}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700884
Ady Abraham03b02dd2019-03-21 15:40:11 -0700885void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800886 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800887
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800888 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800889 // config twice. However event generation config might have changed so we need to update it
890 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800891 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700892 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
893 mDesiredActiveConfig = info;
894 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800895
896 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800897 // This will trigger HWC refresh without resetting the idle timer.
898 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700899 // Start receiving vsync samples now, so that we can detect a period
900 // switch.
901 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700902 // As we called to set period, we will call to onRefreshRateChangeCompleted once
903 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700904 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700905 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700906 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800907 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800908 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700909
910 if (mRefreshRateOverlay) {
911 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
912 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800913}
914
915status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
916 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800917
918 std::vector<int32_t> allowedConfig;
919 allowedConfig.push_back(mode);
920
921 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800922}
923
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800924void SurfaceFlinger::setActiveConfigInternal() {
925 ATRACE_CALL();
926
Dominik Laskowski22488f62019-03-28 09:53:04 -0700927 const auto display = getDefaultDisplayDeviceLocked();
928 if (!display) {
929 return;
930 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800931
Dominik Laskowski22488f62019-03-28 09:53:04 -0700932 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700933 mRefreshRateConfigs->setCurrentConfig(mUpcomingActiveConfig.configId);
934 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700935
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800936 display->setActiveConfig(mUpcomingActiveConfig.configId);
937
Alec Mouri754c98a2019-03-18 18:53:42 -0700938 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700939 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800940 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700941
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800942 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800943 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
944 mUpcomingActiveConfig.configId);
945 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800946}
947
Ady Abraham53852a52019-05-28 18:07:44 -0700948void SurfaceFlinger::desiredActiveConfigChangeDone() {
949 std::lock_guard<std::mutex> lock(mActiveConfigLock);
950 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
951 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700952
953 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
954 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700955 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700956}
957
Dominik Laskowski22488f62019-03-28 09:53:04 -0700958bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800959 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800960 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700961 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800962 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700963 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800964 return true;
965 }
966
967 // We received the present fence from the HWC, so we assume it successfully updated
968 // the config, hence we update SF.
969 mCheckPendingFence = false;
970 setActiveConfigInternal();
971 }
972
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800973 // Store the local variable to release the lock.
974 ActiveConfigInfo desiredActiveConfig;
975 {
976 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800977 if (!mDesiredActiveConfigChanged) {
978 return false;
979 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800980 desiredActiveConfig = mDesiredActiveConfig;
981 }
982
Dominik Laskowski22488f62019-03-28 09:53:04 -0700983 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800984 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
985 // display is not valid or we are already in the requested mode
986 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -0700987 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800988 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800990
Ady Abraham838de062019-02-04 10:24:03 -0800991 // Desired active config was set, it is different than the config currently in use, however
992 // allowed configs might have change by the time we process the refresh.
993 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -0700994 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -0700995 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -0800996 return false;
997 }
Alec Mouri7f015182019-07-11 13:56:22 -0700998
Ady Abrahamb838aed2019-02-12 15:30:16 -0800999 mUpcomingActiveConfig = desiredActiveConfig;
1000 const auto displayId = display->getId();
1001 LOG_ALWAYS_FATAL_IF(!displayId);
1002
1003 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1004 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1005
1006 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001007 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001008 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001009 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001010}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001011
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001012status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1013 Vector<ColorMode>* outColorModes) {
1014 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001015 return BAD_VALUE;
1016 }
1017
Peiyong Lina52f0292018-03-14 17:26:31 -07001018 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001019 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001020 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001021 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1022
1023 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1024 if (!displayId) {
1025 return NAME_NOT_FOUND;
1026 }
1027
Dominik Laskowski075d3172018-05-24 15:50:06 -07001028 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001029 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001030 }
Michael Wright28f24d02016-07-12 13:30:53 -07001031 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001032
1033 // If it's built-in display and the configuration claims it's not wide color capable,
1034 // filter out all wide color modes. The typical reason why this happens is that the
1035 // hardware is not good enough to support GPU composition of wide color, and thus the
1036 // OEMs choose to disable this capability.
1037 if (isInternalDisplay && !hasWideColorDisplay) {
1038 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1039 isWideColorMode);
1040 } else {
1041 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1042 }
Michael Wright28f24d02016-07-12 13:30:53 -07001043
1044 return NO_ERROR;
1045}
1046
Daniel Solomon42d04562019-01-20 21:03:19 -08001047status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1048 ui::DisplayPrimaries &primaries) {
1049 if (!displayToken) {
1050 return BAD_VALUE;
1051 }
1052
1053 // Currently we only support this API for a single internal display.
1054 if (getInternalDisplayToken() != displayToken) {
1055 return BAD_VALUE;
1056 }
1057
1058 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1059 return NO_ERROR;
1060}
1061
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001062ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1063 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001064 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001065 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001066 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001067}
1068
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001069status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001070 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001071 Vector<ColorMode> modes;
1072 getDisplayColorModes(displayToken, &modes);
1073 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1074 if (mode < ColorMode::NATIVE || !exists) {
1075 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1076 decodeColorMode(mode).c_str(), mode, displayToken.get());
1077 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001078 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001079 const auto display = getDisplayDevice(displayToken);
1080 if (!display) {
1081 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1082 decodeColorMode(mode).c_str(), mode, displayToken.get());
1083 } else if (display->isVirtual()) {
1084 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1085 decodeColorMode(mode).c_str(), mode);
1086 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001087 display->getCompositionDisplay()->setColorProfile(
1088 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1089 RenderIntent::COLORIMETRIC,
1090 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001091 }
1092 }));
1093
Michael Wright28f24d02016-07-12 13:30:53 -07001094 return NO_ERROR;
1095}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001096
Svetoslavd85084b2014-03-20 10:28:31 -07001097status_t SurfaceFlinger::clearAnimationFrameStats() {
1098 Mutex::Autolock _l(mStateLock);
1099 mAnimFrameTracker.clearStats();
1100 return NO_ERROR;
1101}
1102
1103status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1104 Mutex::Autolock _l(mStateLock);
1105 mAnimFrameTracker.getStats(outStats);
1106 return NO_ERROR;
1107}
1108
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001109status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1110 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001111 Mutex::Autolock _l(mStateLock);
1112
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001113 const auto display = getDisplayDeviceLocked(displayToken);
1114 if (!display) {
1115 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001116 return BAD_VALUE;
1117 }
1118
Peiyong Linfb069302018-04-25 14:34:31 -07001119 // At this point the DisplayDeivce should already be set up,
1120 // meaning the luminance information is already queried from
1121 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001123 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1124 capabilities.getDesiredMaxLuminance(),
1125 capabilities.getDesiredMaxAverageLuminance(),
1126 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001127
1128 return NO_ERROR;
1129}
1130
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001131status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1132 ui::PixelFormat* outFormat,
1133 ui::Dataspace* outDataspace,
1134 uint8_t* outComponentMask) const {
1135 if (!outFormat || !outDataspace || !outComponentMask) {
1136 return BAD_VALUE;
1137 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001138 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001139 if (!display || !display->getId()) {
1140 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1141 return BAD_VALUE;
1142 }
1143 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1144 outDataspace, outComponentMask);
1145}
1146
Kevin DuBois74e53772018-11-19 10:52:38 -08001147status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1148 bool enable, uint8_t componentMask,
1149 uint64_t maxFrames) const {
1150 const auto display = getDisplayDevice(displayToken);
1151 if (!display || !display->getId()) {
1152 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1153 return BAD_VALUE;
1154 }
1155
1156 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1157 componentMask, maxFrames);
1158}
1159
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001160status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1161 uint64_t maxFrames, uint64_t timestamp,
1162 DisplayedFrameStats* outStats) const {
1163 const auto display = getDisplayDevice(displayToken);
1164 if (!display || !display->getId()) {
1165 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1166 return BAD_VALUE;
1167 }
1168
1169 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1170 outStats);
1171}
1172
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001173status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1174 if (!outSupported) {
1175 return BAD_VALUE;
1176 }
1177 *outSupported = getRenderEngine().supportsProtectedContent();
1178 return NO_ERROR;
1179}
1180
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001181status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1182 bool* outIsWideColorDisplay) const {
1183 if (!displayToken || !outIsWideColorDisplay) {
1184 return BAD_VALUE;
1185 }
1186 Mutex::Autolock _l(mStateLock);
1187 const auto display = getDisplayDeviceLocked(displayToken);
1188 if (!display) {
1189 return BAD_VALUE;
1190 }
Peiyong Linff84a152019-05-17 18:36:19 -07001191
1192 // Use hasWideColorDisplay to override built-in display.
1193 const auto displayId = display->getId();
1194 if (displayId && displayId == getInternalDisplayIdLocked()) {
1195 *outIsWideColorDisplay = hasWideColorDisplay;
1196 return NO_ERROR;
1197 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001198 *outIsWideColorDisplay = display->hasWideColorGamut();
1199 return NO_ERROR;
1200}
1201
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001202status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001203 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001204 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001205
Dominik Laskowski6505f792019-09-18 11:10:05 -07001206 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1207 mEventQueue->setEventConnection(
1208 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001209 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001210 }));
1211
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001212 return NO_ERROR;
1213}
1214
1215status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001216 Mutex::Autolock lock(mStateLock);
1217 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001218}
1219
Lloyd Pique755e3192018-01-31 16:46:15 -08001220status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1221 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001222 // Try to acquire a lock for 1s, fail gracefully
1223 const status_t err = mStateLock.timedLock(s2ns(1));
1224 const bool locked = (err == NO_ERROR);
1225 if (!locked) {
1226 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1227 return TIMED_OUT;
1228 }
1229
1230 outLayers->clear();
1231 mCurrentState.traverseInZOrder([&](Layer* layer) {
1232 outLayers->push_back(layer->getLayerDebugInfo());
1233 });
1234
1235 mStateLock.unlock();
1236 return NO_ERROR;
1237}
1238
Peiyong Linc6780972018-10-28 15:24:08 -07001239status_t SurfaceFlinger::getCompositionPreference(
1240 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1241 Dataspace* outWideColorGamutDataspace,
1242 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001243 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001244 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001245 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001246 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001247 return NO_ERROR;
1248}
1249
Dan Stozaec460082018-12-17 15:35:09 -08001250status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1251 const sp<IBinder>& stopLayerHandle,
1252 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001253 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001254 return BAD_VALUE;
1255 }
1256 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001257 return NO_ERROR;
1258}
1259
Dan Stozaec460082018-12-17 15:35:09 -08001260status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001261 if (!listener) {
1262 return BAD_VALUE;
1263 }
Dan Stozaec460082018-12-17 15:35:09 -08001264 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001265 return NO_ERROR;
1266}
Dan Gittik57e63c52019-01-18 16:37:54 +00001267
1268status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1269 bool* outSupport) const {
1270 if (!displayToken || !outSupport) {
1271 return BAD_VALUE;
1272 }
1273 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1274 if (!displayId) {
1275 return NAME_NOT_FOUND;
1276 }
1277 *outSupport =
1278 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1279 return NO_ERROR;
1280}
1281
1282status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1283 float brightness) const {
1284 if (!displayToken) {
1285 return BAD_VALUE;
1286 }
1287 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1288 if (!displayId) {
1289 return NAME_NOT_FOUND;
1290 }
1291 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1292}
1293
Ady Abraham8532d012019-05-08 14:50:56 -07001294status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1295 PowerHint powerHint = static_cast<PowerHint>(hintId);
1296
1297 if (powerHint == PowerHint::INTERACTION) {
1298 mScheduler->notifyTouchEvent();
1299 }
1300
1301 return NO_ERROR;
1302}
1303
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001304// ----------------------------------------------------------------------------
1305
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001306sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001307 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001308 const auto& handle =
1309 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001310
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001311 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001312}
1313
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001314// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001315
1316void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001317 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001318}
1319
1320void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001321 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001322 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001323}
1324
1325void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001326 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001327 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001328}
1329
1330void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001331 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001332 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001333}
1334
1335status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001336 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001337 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001338}
1339
1340status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001341 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001342 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001343 if (res == NO_ERROR) {
1344 msg->wait();
1345 }
1346 return res;
1347}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001348
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001349void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001350 do {
1351 waitForEvent();
1352 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001353}
1354
Dominik Laskowski83b88212018-12-11 13:34:06 -08001355nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001356 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001357 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1358 return 0;
1359 }
1360
1361 const auto config = getHwComposer().getActiveConfig(*displayId);
1362 return config ? config->getVsyncPeriod() : 0;
1363}
1364
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001365void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1366 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001367 ATRACE_NAME("SF onVsync");
1368
Steven Thomas3cfac282017-02-06 12:29:30 -08001369 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001370 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001371 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001372 return;
1373 }
1374
Dominik Laskowski075d3172018-05-24 15:50:06 -07001375 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001376 return;
1377 }
1378
Dominik Laskowski075d3172018-05-24 15:50:06 -07001379 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001380 // For now, we don't do anything with external display vsyncs.
1381 return;
1382 }
1383
Alec Mourif8e689c2019-05-20 18:32:22 -07001384 bool periodFlushed = false;
1385 mScheduler->addResyncSample(timestamp, &periodFlushed);
1386 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001387 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001388 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001389}
1390
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001391void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001392 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1393 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001394}
1395
Ady Abraham261614e2019-07-10 17:53:12 -07001396bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001397 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001398}
1399
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001400void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001401 const auto display = getDefaultDisplayDeviceLocked();
1402 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001403 return;
1404 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001405 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001406
Ana Krulec7d1d6832018-12-27 11:10:09 -08001407 // Don't do any updating if the current fps is the same as the new one.
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001408 const auto& refreshRateConfig = mRefreshRateConfigs->getRefreshRateFromType(refreshRate);
1409 const int desiredConfigId = refreshRateConfig.configId;
Alec Mouri0a1cc962019-03-14 12:33:02 -07001410
Dominik Laskowski22488f62019-03-28 09:53:04 -07001411 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001412 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1413 return;
1414 }
1415
Dominik Laskowski22488f62019-03-28 09:53:04 -07001416 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001417}
1418
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001419void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001420 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001421 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001422 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001423
Lloyd Piqueba04e622017-12-14 17:11:26 -08001424 // Ignore events that do not have the right sequenceId.
1425 if (sequenceId != getBE().mComposerSequenceId) {
1426 return;
1427 }
1428
Steven Thomasb02664d2017-07-26 18:48:28 -07001429 // Only lock if we're not on the main thread. This function is normally
1430 // called on a hwbinder thread, but for the primary display it's called on
1431 // the main thread with the state lock already held, so don't attempt to
1432 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001433 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001434
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001435 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001436
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001437 if (std::this_thread::get_id() == mMainThreadId) {
1438 // Process all pending hot plug events immediately if we are on the main thread.
1439 processDisplayHotplugEventsLocked();
1440 }
1441
Lloyd Piqueba04e622017-12-14 17:11:26 -08001442 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001443}
1444
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001445void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001446 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001447 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001448 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001449 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001450 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001451}
1452
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001453void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001454 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001455
1456 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1457 // display power state.
1458 postMessageAsync(new LambdaMessage(
1459 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1460}
1461
1462void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1463 ATRACE_CALL();
1464
Ady Abraham27c70212019-06-11 10:52:26 -07001465 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1466
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001467 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001468 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1469 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001470 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001471 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001472 }
Mathias Agopian86303202012-07-24 22:46:10 -07001473}
1474
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001475// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001476void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001477 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001478 // Clear the drawing state so that the logic inside of
1479 // handleTransactionLocked will fire. It will determine the delta between
1480 // mCurrentState and mDrawingState and re-apply all changes when we make the
1481 // transition.
1482 mDrawingState.displays.clear();
1483 mDisplays.clear();
1484}
1485
Steven Thomas050b2c82017-03-06 11:45:16 -08001486void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001487 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001488 if (!mVrFlinger)
1489 return;
1490 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001491 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001492 return;
1493 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001494
Lloyd Pique441d5042018-10-18 16:49:51 -07001495 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001496 ALOGE("Vr flinger is only supported for remote hardware composer"
1497 " service connections. Ignoring request to transition to vr"
1498 " flinger.");
1499 mVrFlingerRequestsDisplay = false;
1500 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001501 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001502
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001503 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001504
Steven Thomas0123ac62018-07-12 11:32:34 -07001505 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001506 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001507
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001508 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001509
1510 // Clear out all the output layers from the composition engine for all
1511 // displays before destroying the hardware composer interface. This ensures
1512 // any HWC layers are destroyed through that interface before it becomes
1513 // invalid.
1514 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001515 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001516 }
1517
Steven Thomas0123ac62018-07-12 11:32:34 -07001518 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1519 // called below. Clear the reference now so we don't accidentally use it
1520 // later.
1521 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001522
Steven Thomasb02664d2017-07-26 18:48:28 -07001523 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001524 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001525 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001526
Steven Thomasb02664d2017-07-26 18:48:28 -07001527 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001528 // Delete the current instance before creating the new one
1529 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1530 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1531 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1532 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001533
Lloyd Pique441d5042018-10-18 16:49:51 -07001534 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001535 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001536
1537 if (vrFlingerRequestsDisplay) {
1538 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001539 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001540
1541 mVisibleRegionsDirty = true;
1542 invalidateHwcGeometry();
1543
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001544 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001545 display = getDefaultDisplayDeviceLocked();
1546 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001547 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001548
Steven Thomasb02664d2017-07-26 18:48:28 -07001549 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001550 const nsecs_t vsyncPeriod = getVsyncPeriod();
1551 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001552
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001553 // The present fences returned from vr_hwc are not an accurate
1554 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001555 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001556
Steven Thomasb02664d2017-07-26 18:48:28 -07001557 // Use phase of 0 since phase is not known.
1558 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001559 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001560 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001561
Ana Krulecc2870422019-01-29 19:00:58 -08001562 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001563
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001564 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001565 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001566}
1567
Ady Abraham11579302019-09-19 12:35:58 -07001568bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1569 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001570 // We are storing the last 2 present fences. If sf's phase offset is to be
1571 // woken up before the actual vsync but targeting the next vsync, we need to check
1572 // fence N-2
1573 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001574 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001575 ? mPreviousPresentFences[0]
1576 : mPreviousPresentFences[1];
1577
Ady Abraham11579302019-09-19 12:35:58 -07001578 if (fence == Fence::NO_FENCE) {
1579 return false;
1580 }
1581
1582 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1583 fence->wait(graceTimeMs);
1584 }
1585
1586 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001587}
1588
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001589void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001590 DisplayStatInfo stats;
1591 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001592 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001593 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001594 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001595 mPhaseOffsets->getOffsetThresholdForNextVsync()
1596 ? presentTime
1597 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001598}
1599
Dominik Laskowski22488f62019-03-28 09:53:04 -07001600void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001601 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001602 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001603 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001604 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001605 // calculate the expected present time once and use the cached
1606 // value throughout this frame to make sure all layers are
1607 // seeing this same value.
1608 populateExpectedPresentTime();
1609
Ady Abraham11579302019-09-19 12:35:58 -07001610 // When Backpressure propagation is enabled we want to give a small grace period
1611 // for the present fence to fire instead of just giving up on this frame to handle cases
1612 // where present fence is just about to get signaled.
1613 const int graceTimeForPresentFenceMs =
1614 (mPropagateBackpressure &&
1615 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1616 ? 1
1617 : 0;
1618 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1619 previousFrameMissed(
1620 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001621 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1622 mHadDeviceComposition && frameMissed};
1623 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1624 mHadClientComposition && frameMissed};
1625
Alec Mouricc0fc602019-02-26 21:45:19 -08001626 if (frameMissed) {
1627 mFrameMissedCount++;
1628 mTimeStats->incrementMissedFrames();
1629 }
1630
Alec Mouri40189b02019-03-05 15:07:54 -08001631 if (hwcFrameMissed) {
1632 mHwcFrameMissedCount++;
1633 }
1634
1635 if (gpuFrameMissed) {
1636 mGpuFrameMissedCount++;
1637 }
1638
Dominik Laskowski49cea512019-11-12 14:13:23 -08001639 mScheduler->chooseRefreshRateForContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001640
Ady Abrahamb838aed2019-02-12 15:30:16 -08001641 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001642 break;
1643 }
1644
Ady Abrahamadb9a992019-09-19 21:21:55 +00001645 if (frameMissed && mPropagateBackpressure) {
1646 if ((hwcFrameMissed && !gpuFrameMissed) ||
1647 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001648 signalLayerUpdate();
1649 break;
1650 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001651 }
Dan Stoza50182882016-07-08 12:02:20 -07001652
Steven Thomas050b2c82017-03-06 11:45:16 -08001653 // Now that we're going to make it to the handleMessageTransaction()
1654 // call below it's safe to call updateVrFlinger(), which will
1655 // potentially trigger a display handoff.
1656 updateVrFlinger();
1657
Dan Stoza6b9454d2014-11-07 16:00:59 -08001658 bool refreshNeeded = handleMessageTransaction();
1659 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001660
1661 updateCursorAsync();
1662 updateInputFlinger();
1663
Dan Stoza58784442014-12-02 16:58:17 -08001664 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001665 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001666 // Signal a refresh if a transaction modified the window state,
1667 // a new buffer was latched, or if HWC has requested a full
1668 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001669 if (mFrameStartTime <= 0) {
1670 // We should only use the time of the first invalidate
1671 // message that signals a refresh as the beginning of the
1672 // frame. Otherwise the real frame time will be
1673 // underestimated.
1674 mFrameStartTime = frameStart;
1675 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001676 signalRefresh();
1677 }
1678 break;
1679 }
1680 case MessageQueue::REFRESH: {
1681 handleMessageRefresh();
1682 break;
1683 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001684 }
1685}
1686
Dan Stoza6b9454d2014-11-07 16:00:59 -08001687bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001688 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001689 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001690
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001691 bool flushedATransaction = flushTransactionQueues();
1692
1693 bool runHandleTransaction = transactionFlags &&
1694 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1695
1696 if (runHandleTransaction) {
1697 handleTransaction(eTransactionMask);
1698 } else {
1699 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001700 }
1701
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001702 if (transactionFlushNeeded()) {
1703 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001704 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001705
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001706 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001707}
1708
Mathias Agopian4fec8732012-06-29 14:12:52 -07001709void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001710 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001711
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001712 mRefreshPending = false;
1713
Lloyd Piqueab039b52019-02-13 14:22:42 -08001714 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001715 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001716 for (const auto& [_, display] : mDisplays) {
1717 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1718 }
1719 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1720 auto compositionLayer = layer->getCompositionLayer();
1721 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1722 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001723 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1724 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1725 auto compositionLayer = layer->getCompositionLayer();
Adithya Srinivasan871023e2019-11-05 13:54:13 -08001726 if (compositionLayer) {
1727 refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
1728 mFrameTracer->traceTimestamp(layer->getSequence(), layer->getCurrentBufferId(),
1729 layer->getCurrentFrameNumber(), systemTime(),
1730 FrameTracer::FrameEvent::HWC_COMPOSITION_QUEUED);
1731 }
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001732 }
1733
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001734 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001735 refreshArgs.outputColorSetting = useColorManagement
1736 ? mDisplayColorSetting
1737 : compositionengine::OutputColorSetting::kUnmanaged;
1738 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1739 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001740
1741 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1742 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001743
1744 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1745 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1746 mDrawingState.colorMatrixChanged = false;
1747 }
1748
1749 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1750
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001751 if (mDebugRegion != 0) {
1752 refreshArgs.devOptFlashDirtyRegionsDelay =
1753 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1754 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001755
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001756 mGeometryInvalid = false;
1757
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001758 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001759 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1760 // Reset the frame start time now that we've recorded this frame.
1761 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001762
David Sodmanfa9b2af2017-12-24 13:28:59 -08001763 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001764 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001765
Lloyd Pique66d68602019-02-13 14:23:31 -08001766 mHadClientComposition =
1767 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1768 auto& displayDevice = tokenDisplayPair.second;
1769 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1770 });
1771 mHadDeviceComposition =
1772 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1773 auto& displayDevice = tokenDisplayPair.second;
1774 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1775 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001776
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001777 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001778
David Sodman7e4ae112018-02-09 15:02:28 -08001779 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001780 if (mVisibleRegionsDirty) {
1781 mVisibleRegionsDirty = false;
1782 if (mTracingEnabled) {
1783 mTracing.notify("visibleRegionsDirty");
1784 }
1785 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001786
1787 if (mCompositionEngine->needsAnotherUpdate()) {
1788 signalLayerUpdate();
1789 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001790}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001791
David Sodmanfa9b2af2017-12-24 13:28:59 -08001792
1793bool SurfaceFlinger::handleMessageInvalidate() {
1794 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001795 bool refreshNeeded = handlePageFlip();
1796
Vishnu Nair4351ad52019-02-11 14:13:02 -08001797 if (mVisibleRegionsDirty) {
1798 computeLayerBounds();
1799 }
1800
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001801 for (auto& layer : mLayersPendingRefresh) {
1802 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001803 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001804 invalidateLayerStack(layer, visibleReg);
1805 }
1806 mLayersPendingRefresh.clear();
1807 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001808}
1809
Ana Krulece588e312018-09-18 12:32:24 -07001810void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1811 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001812 // Update queue of past composite+present times and determine the
1813 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001814 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001815 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001816 while (!getBE().mCompositePresentTimes.empty()) {
1817 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001818 // Cached values should have been updated before calling this method,
1819 // which helps avoid duplicate syscalls.
1820 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1821 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1822 break;
1823 }
1824 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001825 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001826 }
1827
1828 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001829 while (getBE().mCompositePresentTimes.size() > 16) {
1830 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001831 }
1832
Ana Krulece588e312018-09-18 12:32:24 -07001833 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001834}
1835
Ana Krulece588e312018-09-18 12:32:24 -07001836void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1837 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001838 // Integer division and modulo round toward 0 not -inf, so we need to
1839 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001840 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1841 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1842 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001843
Ana Krulec757f63a2019-01-25 10:46:18 -08001844 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001845 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001846 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001847 }
1848
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001849 // Snap the latency to a value that removes scheduling jitter from the
1850 // composition and present times, which often have >1ms of jitter.
1851 // Reducing jitter is important if an app attempts to extrapolate
1852 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001853 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001854 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001855 nsecs_t bias = stats.vsyncPeriod / 2;
1856 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1857 nsecs_t snappedCompositeToPresentLatency =
1858 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001859
David Sodman99974d22017-11-28 12:04:33 -08001860 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001861 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1862 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001863 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001864}
1865
David Sodman2b406362017-12-15 13:33:47 -08001866void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001867{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001868 ATRACE_CALL();
1869 ALOGV("postComposition");
1870
Brian Anderson3546a3f2016-07-14 11:51:14 -07001871 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001872 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001873 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001874 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001875 }
1876
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001877 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001878 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001879
David Sodman73beded2017-11-15 11:56:06 -08001880 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001881 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08001882 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001883 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001884 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1885 ->getRenderSurface()
1886 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001887 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001888 } else {
1889 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1890 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001891
David Sodman73beded2017-11-15 11:56:06 -08001892 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001893 mPreviousPresentFences[1] = mPreviousPresentFences[0];
1894 mPreviousPresentFences[0] = displayDevice
1895 ? getHwComposer().getPresentFence(*displayDevice->getId())
1896 : Fence::NO_FENCE;
1897 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08001898 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001899
Ana Krulece588e312018-09-18 12:32:24 -07001900 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08001901 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001902
Lloyd Piqueab039b52019-02-13 14:22:42 -08001903 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
1904 // be sampled a little later than when we started doing work for this frame,
1905 // but that should be okay since updateCompositorTiming has snapping logic.
1906 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
1907 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001908 CompositorTiming compositorTiming;
1909 {
David Sodman99974d22017-11-28 12:04:33 -08001910 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1911 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001912 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001913
Robert Carr2047fae2016-11-28 14:09:09 -08001914 mDrawingState.traverseInZOrder([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08001915 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
1916 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001917 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001918 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001919 }
Robert Carr2047fae2016-11-28 14:09:09 -08001920 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001921
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001922 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001923 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001924 }
1925
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001926 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001927 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1928 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001929 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001930 }
1931 }
1932
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001933 if (mAnimCompositionPending) {
1934 mAnimCompositionPending = false;
1935
Brian Anderson4e606e32017-03-16 15:34:57 -07001936 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001937 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001938 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07001939 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001940 // The HWC doesn't support present fences, so use the refresh
1941 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07001942 const nsecs_t presentTime =
1943 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001944 mAnimFrameTracker.setActualPresentTime(presentTime);
1945 }
1946 mAnimFrameTracker.advanceFrame();
1947 }
Dan Stozab90cf072015-03-05 11:05:59 -08001948
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001949 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001950 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001951 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001952 }
1953
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001954 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001955
Lloyd Pique32cbe282018-10-19 13:09:22 -07001956 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1957 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001958 return;
1959 }
1960
1961 nsecs_t currentTime = systemTime();
1962 if (mHasPoweredOff) {
1963 mHasPoweredOff = false;
1964 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001965 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001966 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001967 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1968 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001969 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001970 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001971 }
David Sodman4a36e932017-11-07 14:29:47 -08001972 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001973 }
David Sodman4a36e932017-11-07 14:29:47 -08001974 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001975
1976 {
1977 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07001978 if (mTexturePool.size() < mTexturePoolSize) {
1979 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07001980 const size_t offset = mTexturePool.size();
1981 mTexturePool.resize(mTexturePoolSize);
1982 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1983 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07001984 } else if (mTexturePool.size() > mTexturePoolSize) {
1985 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
1986 const size_t offset = mTexturePoolSize;
1987 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
1988 mTexturePool.resize(mTexturePoolSize);
1989 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07001990 }
1991 }
Marissa Walle2ffb422018-10-12 11:33:52 -07001992
Ady Abrahambe0f9482019-04-24 15:41:53 -07001993 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07001994 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08001995
Kevin DuBois413287f2019-02-25 08:46:47 -08001996 if (mLumaSampling && mRegionSamplingThread) {
1997 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08001998 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07001999
2000 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2001 // side-effect of getTotalSize(), so we check that again here
2002 if (ATRACE_ENABLED()) {
2003 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2004 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002005}
2006
Vishnu Nair4351ad52019-02-11 14:13:02 -08002007void SurfaceFlinger::computeLayerBounds() {
2008 for (const auto& pair : mDisplays) {
2009 const auto& displayDevice = pair.second;
2010 const auto display = displayDevice->getCompositionDisplay();
2011 for (const auto& layer : mDrawingState.layersSortedByZ) {
2012 // only consider the layers on the given layer stack
2013 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002014 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002015 }
2016
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002017 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2018 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002019 }
2020 }
2021}
2022
David Sodmanfa9b2af2017-12-24 13:28:59 -08002023void SurfaceFlinger::postFrame()
2024{
2025 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002026 const auto display = getDefaultDisplayDeviceLocked();
2027 if (display && getHwComposer().isConnected(*display->getId())) {
2028 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002029 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2030 logFrameStats();
2031 }
2032 }
2033}
2034
Mathias Agopian87baae12012-07-31 12:38:26 -07002035void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002036{
Mathias Agopian841cde52012-03-01 15:44:37 -08002037 ATRACE_CALL();
2038
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002039 // here we keep a copy of the drawing state (that is the state that's
2040 // going to be overwritten by handleTransactionLocked()) outside of
2041 // mStateLock so that the side-effects of the State assignment
2042 // don't happen with mStateLock held (which can cause deadlocks).
2043 State drawingState(mDrawingState);
2044
Mathias Agopianca4d3602011-05-19 15:38:14 -07002045 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002046 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002047
Mathias Agopianca4d3602011-05-19 15:38:14 -07002048 // Here we're guaranteed that some transaction flags are set
2049 // so we can call handleTransactionLocked() unconditionally.
2050 // We call getTransactionFlags(), which will also clear the flags,
2051 // with mStateLock held to guarantee that mCurrentState won't change
2052 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002053
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002054 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002055 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002056 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002057
Mathias Agopianca4d3602011-05-19 15:38:14 -07002058 mDebugInTransaction = 0;
2059 invalidateHwcGeometry();
2060 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002061}
2062
Lloyd Piqueba04e622017-12-14 17:11:26 -08002063void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2064 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002065 const std::optional<DisplayIdentificationInfo> info =
2066 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002067
Dominik Laskowski075d3172018-05-24 15:50:06 -07002068 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002069 continue;
2070 }
2071
Lloyd Piqueba04e622017-12-14 17:11:26 -08002072 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002073 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002074 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002075 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2076 initScheduler(info->id);
2077 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002078 mPhysicalDisplayTokens[info->id] = new BBinder();
2079 DisplayDeviceState state;
2080 state.displayId = info->id;
2081 state.isSecure = true; // All physical displays are currently considered secure.
2082 state.displayName = info->name;
2083 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2084 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002085 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002086 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002087 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002088
Dominik Laskowski075d3172018-05-24 15:50:06 -07002089 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2090 if (index >= 0) {
2091 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2092 mInterceptor->saveDisplayDeletion(state.sequenceId);
2093 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002094 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002095 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002096 }
2097
2098 processDisplayChangesLocked();
2099 }
2100
2101 mPendingHotplugEvents.clear();
2102}
2103
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002104void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002105 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2106 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002107}
2108
Lloyd Pique99d3da52018-01-22 17:48:03 -08002109sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002110 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002111 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002112 const sp<IGraphicBufferProducer>& producer) {
2113 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002114 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002115 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002116 creationArgs.isSecure = state.isSecure;
2117 creationArgs.displaySurface = dispSurface;
2118 creationArgs.hasWideColorGamut = false;
2119 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002120 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002121
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002122 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002123 creationArgs.isPrimary = isInternalDisplay;
2124
2125 if (useColorManagement && displayId) {
2126 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002127 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002128 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002129 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002130 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002131
Dominik Laskowski7e045462018-05-30 13:02:02 -07002132 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002133 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002134 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002135 }
tangrobin6753a022018-08-10 10:58:54 +08002136 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002137
Dominik Laskowski075d3172018-05-24 15:50:06 -07002138 if (displayId) {
2139 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002140 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002141 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002142 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002143
Lloyd Pique90c115d2018-09-18 21:39:42 -07002144 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002145 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002146 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002147
Lloyd Pique99d3da52018-01-22 17:48:03 -08002148 // Make sure that composition can never be stalled by a virtual display
2149 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002150 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002151 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002152 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2153 }
2154
Dominik Laskowski075d3172018-05-24 15:50:06 -07002155 creationArgs.displayInstallOrientation =
2156 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002157
Lloyd Pique99d3da52018-01-22 17:48:03 -08002158 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002159 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002160
Lloyd Pique90c115d2018-09-18 21:39:42 -07002161 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002162
2163 if (maxFrameBufferAcquiredBuffers >= 3) {
2164 nativeWindowSurface->preallocateBuffers();
2165 }
2166
2167 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002168 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002169 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002170 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002171 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002172 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002173 display->getCompositionDisplay()->setColorProfile(
2174 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2175 RenderIntent::COLORIMETRIC,
2176 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002177 if (!state.isVirtual()) {
2178 LOG_ALWAYS_FATAL_IF(!displayId);
2179 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002180 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002181
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002182 display->setLayerStack(state.layerStack);
2183 display->setProjection(state.orientation, state.viewport, state.frame);
2184 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002185
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002186 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002187}
2188
Lloyd Pique347200f2017-12-14 17:00:15 -08002189void SurfaceFlinger::processDisplayChangesLocked() {
2190 // here we take advantage of Vector's copy-on-write semantics to
2191 // improve performance by skipping the transaction entirely when
2192 // know that the lists are identical
2193 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2194 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2195 if (!curr.isIdenticalTo(draw)) {
2196 mVisibleRegionsDirty = true;
2197 const size_t cc = curr.size();
2198 size_t dc = draw.size();
2199
2200 // find the displays that were removed
2201 // (ie: in drawing state but not in current state)
2202 // also handle displays that changed
2203 // (ie: displays that are in both lists)
2204 for (size_t i = 0; i < dc;) {
2205 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2206 if (j < 0) {
2207 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002208 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002209 // Save display ID before disconnecting.
2210 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002211 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002212
2213 if (!display->isVirtual()) {
2214 LOG_ALWAYS_FATAL_IF(!displayId);
2215 dispatchDisplayHotplugEvent(displayId->value, false);
2216 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002217 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002218
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002219 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002220 } else {
2221 // this display is in both lists. see if something changed.
2222 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002223 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002224 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2225 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2226 if (state_binder != draw_binder) {
2227 // changing the surface is like destroying and
2228 // recreating the DisplayDevice, so we just remove it
2229 // from the drawing state, so that it get re-added
2230 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002231 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002232 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002233 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002234 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002235 mDrawingState.displays.removeItemsAt(i);
2236 dc--;
2237 // at this point we must loop to the next item
2238 continue;
2239 }
2240
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002241 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002242 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002243 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002244 }
2245 if ((state.orientation != draw[i].orientation) ||
2246 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002247 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002248 }
2249 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002250 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002251 }
2252 }
2253 }
2254 ++i;
2255 }
2256
2257 // find displays that were added
2258 // (ie: in current state but not in drawing state)
2259 for (size_t i = 0; i < cc; i++) {
2260 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2261 const DisplayDeviceState& state(curr[i]);
2262
Lloyd Pique542307f2018-10-19 13:24:08 -07002263 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002264 sp<IGraphicBufferProducer> producer;
2265 sp<IGraphicBufferProducer> bqProducer;
2266 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002267 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002268
Dominik Laskowski075d3172018-05-24 15:50:06 -07002269 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002270 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002271 // Virtual displays without a surface are dormant:
2272 // they have external state (layer stack, projection,
2273 // etc.) but no internal state (i.e. a DisplayDevice).
2274 if (state.surface != nullptr) {
2275 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002276 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002277 int width = 0;
2278 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2279 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2280 int height = 0;
2281 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2282 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2283 int intFormat = 0;
2284 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2285 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002286 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002287
Dominik Laskowski075d3172018-05-24 15:50:06 -07002288 displayId =
2289 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002290 }
2291
2292 // TODO: Plumb requested format back up to consumer
2293
2294 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002295 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002296 bqProducer, bqConsumer,
2297 state.displayName);
2298
2299 dispSurface = vds;
2300 producer = vds;
2301 }
2302 } else {
2303 ALOGE_IF(state.surface != nullptr,
2304 "adding a supported display, but rendering "
2305 "surface is provided (%p), ignoring it",
2306 state.surface.get());
2307
Dominik Laskowski075d3172018-05-24 15:50:06 -07002308 displayId = state.displayId;
2309 LOG_ALWAYS_FATAL_IF(!displayId);
2310 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002311 producer = bqProducer;
2312 }
2313
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002314 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002315 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002316 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002317 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002318 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002319 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002320 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002321 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002322 }
2323 }
2324 }
2325 }
2326 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002327
2328 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002329}
2330
Mathias Agopian87baae12012-07-31 12:38:26 -07002331void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002332{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002333 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2334
Dan Stoza7dde5992015-05-22 09:51:44 -07002335 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002336 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2337 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002338 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002339
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002340 /*
2341 * Traversal of the children
2342 * (perform the transaction for each of them if needed)
2343 */
2344
Marissa Wall06255332019-03-27 13:48:27 -07002345 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002346 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002347 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002348 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002349
2350 const uint32_t flags = layer->doTransaction(0);
2351 if (flags & Layer::eVisibleRegion)
2352 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002353
2354 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002355 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002356 }
Robert Carr2047fae2016-11-28 14:09:09 -08002357 });
Marissa Wall06255332019-03-27 13:48:27 -07002358 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002359 }
2360
2361 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002362 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002363 */
2364
Mathias Agopiane57f2922012-08-09 16:29:12 -07002365 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002366 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002367 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002368 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002369
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002370 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002371 // The transform hint might have changed for some layers
2372 // (either because a display has changed, or because a layer
2373 // as changed).
2374 //
2375 // Walk through all the layers in currentLayers,
2376 // and update their transform hint.
2377 //
2378 // If a layer is visible only on a single display, then that
2379 // display is used to calculate the hint, otherwise we use the
2380 // default display.
2381 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002382 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002383 // the hint is set before we acquire a buffer from the surface texture.
2384 //
2385 // NOTE: layer transactions have taken place already, so we use their
2386 // drawing state. However, SurfaceFlinger's own transaction has not
2387 // happened yet, so we must use the current state layer list
2388 // (soon to become the drawing state list).
2389 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002390 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002391 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002392 bool first = true;
2393 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002394 // NOTE: we rely on the fact that layers are sorted by
2395 // layerStack first (so we don't have to traverse the list
2396 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002397 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002398 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002399 currentlayerStack = layerStack;
2400 // figure out if this layerstack is mirrored
2401 // (more than one display) if so, pick the default display,
2402 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002403 hintDisplay = nullptr;
2404 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002405 if (display->getCompositionDisplay()
2406 ->belongsInOutput(layer->getLayerStack(),
2407 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002408 if (hintDisplay) {
2409 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002410 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002411 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002412 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002413 }
2414 }
2415 }
2416 }
Chet Haase91d25932013-04-11 15:24:55 -07002417
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002418 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002419 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2420 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002421
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002422 // could be null when this layer is using a layerStack
2423 // that is not visible on any display. Also can occur at
2424 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002425 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002426 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002427
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002428 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002429 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002430 if (hintDisplay) {
2431 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002432 }
Robert Carr2047fae2016-11-28 14:09:09 -08002433
2434 first = false;
2435 });
Mathias Agopian84300952012-11-21 16:02:13 -08002436 }
2437
2438
Mathias Agopian3559b072012-08-15 13:46:03 -07002439 /*
2440 * Perform our own transaction if needed
2441 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002442
2443 if (mLayersAdded) {
2444 mLayersAdded = false;
2445 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002446 mVisibleRegionsDirty = true;
2447 }
2448
2449 // some layers might have been removed, so
2450 // we need to update the regions they're exposing.
2451 if (mLayersRemoved) {
2452 mLayersRemoved = false;
2453 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002454 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002455 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002456 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002457 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002458 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002459 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002460 }
Robert Carr2047fae2016-11-28 14:09:09 -08002461 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002462 }
2463
Vishnu Nairec0ab382019-02-13 15:32:56 -08002464 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002466}
2467
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002468void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002469 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002470 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002471 return;
2472 }
2473
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002474 if (mVisibleRegionsDirty || mInputInfoChanged) {
2475 mInputInfoChanged = false;
2476 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002477 } else if (mInputWindowCommands.syncInputWindows) {
2478 // If the caller requested to sync input windows, but there are no
2479 // changes to input windows, notify immediately.
2480 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002481 }
2482
Arthur Hung6cbb9752019-09-05 16:38:18 +08002483 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002484}
2485
2486void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002487 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002488
2489 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2490 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002491 // When calculating the screen bounds we ignore the transparent region since it may
2492 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002493 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002494 }
2495 });
chaviw291d88a2019-02-14 10:33:58 -08002496
2497 mInputFlinger->setInputWindows(inputHandles,
2498 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2499 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002500}
2501
Vishnu Nairec0ab382019-02-13 15:32:56 -08002502void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002503 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002504 mPendingInputWindowCommands.clear();
2505}
2506
Riley Andrews03414a12014-07-01 14:22:59 -07002507void SurfaceFlinger::updateCursorAsync()
2508{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002509 compositionengine::CompositionRefreshArgs refreshArgs;
2510 for (const auto& [_, display] : mDisplays) {
2511 if (display->getId()) {
2512 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002513 }
2514 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002515
2516 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002517}
2518
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002519void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2520 if (mScheduler) {
2521 // In practice it's not allowed to hotplug in/out the primary display once it's been
2522 // connected during startup, but some tests do it, so just warn and return.
2523 ALOGW("Can't re-init scheduler");
2524 return;
2525 }
2526
2527 int currentConfig = getHwComposer().getActiveConfigIndex(primaryDisplayId);
2528 mRefreshRateConfigs =
2529 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2530 getHwComposer().getConfigs(
2531 primaryDisplayId),
2532 currentConfig);
2533 mRefreshRateStats =
2534 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2535 currentConfig, HWC_POWER_MODE_OFF);
2536 mRefreshRateStats->setConfigMode(currentConfig);
2537
2538 // start the EventThread
2539 mScheduler =
2540 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
2541 *mRefreshRateConfigs);
2542 mAppConnectionHandle =
2543 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
2544 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2545 impl::EventThread::InterceptVSyncsCallback());
2546 mSfConnectionHandle =
2547 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
2548 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2549 [this](nsecs_t timestamp) {
2550 mInterceptor->saveVSyncEvent(timestamp);
2551 });
2552
2553 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2554 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
2555 mPhaseOffsets->getCurrentOffsets());
2556
2557 mRegionSamplingThread =
2558 new RegionSamplingThread(*this, *mScheduler,
2559 RegionSamplingThread::EnvironmentTimingTunables());
2560
2561 mScheduler->setChangeRefreshRateCallback(
2562 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
2563 Mutex::Autolock lock(mStateLock);
2564 setRefreshRateTo(type, event);
2565 });
2566}
2567
Mathias Agopian4fec8732012-06-29 14:12:52 -07002568void SurfaceFlinger::commitTransaction()
2569{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002570 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002571
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002572 mTransactionPending = false;
2573 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002574 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002575}
2576
Lloyd Pique58e24a32019-08-01 15:50:14 -07002577void SurfaceFlinger::commitTransactionLocked() {
2578 if (!mLayersPendingRemoval.isEmpty()) {
2579 // Notify removed layers now that they can't be drawn from
2580 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002581 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002582
2583 // Ensure any buffers set to display on any children are released.
2584 if (l->isRemovedFromCurrentState()) {
2585 l->latchAndReleaseBuffer();
2586 }
2587
2588 // If the layer has been removed and has no parent, then it will not be reachable
2589 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2590 // ensure we can copy its current to drawing state.
2591 if (!l->getParent()) {
2592 mOffscreenLayers.emplace(l.get());
2593 }
2594 }
2595 mLayersPendingRemoval.clear();
2596 }
2597
2598 // If this transaction is part of a window animation then the next frame
2599 // we composite should be considered an animation as well.
2600 mAnimCompositionPending = mAnimTransactionPending;
2601
2602 mDrawingState = mCurrentState;
2603 // clear the "changed" flags in current state
2604 mCurrentState.colorMatrixChanged = false;
2605
2606 mDrawingState.traverseInZOrder([&](Layer* layer) {
2607 layer->commitChildList();
2608
2609 // If the layer can be reached when traversing mDrawingState, then the layer is no
2610 // longer offscreen. Remove the layer from the offscreenLayer set.
2611 if (mOffscreenLayers.count(layer)) {
2612 mOffscreenLayers.erase(layer);
2613 }
2614 });
2615
2616 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002617 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002618}
2619
Nataniel Borges2b796da2019-02-15 13:32:18 -08002620void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2621 if (mTracingEnabledChanged) {
2622 mTracingEnabled = mTracing.isEnabled();
2623 mTracingEnabledChanged = false;
2624 }
2625
2626 // Synchronize with Tracing thread
2627 std::unique_lock<std::mutex> lock;
2628 if (mTracingEnabled) {
2629 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2630 }
2631
2632 lockedOperation();
2633
2634 // Synchronize with Tracing thread
2635 if (mTracingEnabled) {
2636 lock.unlock();
2637 }
2638}
2639
chaviw74d90ad2019-04-26 14:45:26 -07002640void SurfaceFlinger::commitOffscreenLayers() {
2641 for (Layer* offscreenLayer : mOffscreenLayers) {
2642 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2643 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2644 if (!trFlags) return;
2645
2646 layer->doTransaction(0);
2647 layer->commitChildList();
2648 });
2649 }
2650}
2651
Chia-I Wuab0c3192017-08-01 11:29:00 -07002652void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002653 for (const auto& [token, displayDevice] : mDisplays) {
2654 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002655 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002656 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002657 }
2658 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002659}
2660
Dan Stoza6b9454d2014-11-07 16:00:59 -08002661bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002662{
Ady Abraham09bd3922019-04-08 10:44:56 -07002663 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002664 ALOGV("handlePageFlip");
2665
Brian Andersond6927fb2016-07-23 23:37:30 -07002666 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002667
Mathias Agopian4fec8732012-06-29 14:12:52 -07002668 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002669 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002670 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002671
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002672 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2673
Eric Penner51c59cd2014-07-28 19:51:58 -07002674 // Store the set of layers that need updates. This set must not change as
2675 // buffers are being latched, as this could result in a deadlock.
2676 // Example: Two producers share the same command stream and:
2677 // 1.) Layer 0 is latched
2678 // 2.) Layer 0 gets a new frame
2679 // 2.) Layer 1 gets a new frame
2680 // 3.) Layer 1 is latched.
2681 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2682 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002683 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002684 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002685 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002686 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002687 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002688 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002689 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002690 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002691 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002692 } else {
2693 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002694 }
Robert Carr2047fae2016-11-28 14:09:09 -08002695 });
2696
chaviw49a108c2019-08-12 11:23:06 -07002697 // The client can continue submitting buffers for offscreen layers, but they will not
2698 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2699 // layers to ensure dequeueBuffer doesn't block indefinitely.
2700 for (Layer* offscreenLayer : mOffscreenLayers) {
2701 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2702 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2703 }
2704
Lloyd Piquef2c79392018-12-20 16:23:33 -08002705 if (!mLayersWithQueuedFrames.empty()) {
2706 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2707 // writes to Layer current state. See also b/119481871
2708 Mutex::Autolock lock(mStateLock);
2709
2710 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002711 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002712 mLayersPendingRefresh.push_back(layer);
2713 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002714 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002715 if (layer->isBufferLatched()) {
2716 newDataLatched = true;
2717 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002718 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002719 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002720
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002721 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002722
2723 // If we will need to wake up at some time in the future to deal with a
2724 // queued frame that shouldn't be displayed during this vsync period, wake
2725 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002726 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002727 signalLayerUpdate();
2728 }
2729
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002730 // enter boot animation on first buffer latch
2731 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2732 ALOGI("Enter boot animation");
2733 mBootStage = BootStage::BOOTANIMATION;
2734 }
2735
chaviw74b03172019-08-19 11:09:03 -07002736 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2737
Dan Stoza6b9454d2014-11-07 16:00:59 -08002738 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002739 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002740}
2741
Mathias Agopianad456f92011-01-13 17:53:01 -08002742void SurfaceFlinger::invalidateHwcGeometry()
2743{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002744 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002745}
2746
Robert Carrc0df3122019-04-11 13:18:21 -07002747status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2748 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2749 const sp<IBinder>& parentHandle,
2750 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002751 // add this layer to the current state list
2752 {
2753 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002754 sp<Layer> parent;
2755 if (parentHandle != nullptr) {
2756 parent = fromHandle(parentHandle);
2757 if (parent == nullptr) {
2758 return NAME_NOT_FOUND;
2759 }
2760 } else {
2761 parent = parentLayer;
2762 }
2763
Robert Carr1f0a16a2016-10-24 16:27:39 -07002764 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002765 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002766 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002767 return NO_MEMORY;
2768 }
Robert Carrc0df3122019-04-11 13:18:21 -07002769
2770 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2771
Robert Carrb89ea9d2018-12-10 13:01:14 -08002772 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002773 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002774 } else if (parent == nullptr) {
2775 lbc->onRemovedFromCurrentState();
2776 } else if (parent->isRemovedFromCurrentState()) {
2777 parent->addChild(lbc);
2778 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002779 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002780 parent->addChild(lbc);
2781 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002782
Yiwei Zhang243b3782018-05-15 17:40:04 -07002783 if (gbc != nullptr) {
2784 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2785 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2786 mMaxGraphicBufferProducerListSize,
2787 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2788 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002789 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002790 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002791 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002792 }
2793
Mathias Agopian96f08192010-06-02 23:28:45 -07002794 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002795 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002796
Dan Stoza7d89d062015-04-30 13:29:25 -07002797 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002798}
2799
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002800uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002801 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002802}
2803
Mathias Agopian3f844832013-08-07 21:24:32 -07002804uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002805 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806}
2807
Mathias Agopian3f844832013-08-07 21:24:32 -07002808uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002809 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002810}
2811
2812uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002813 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002814 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002815 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002816 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002817 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002818 }
2819 return old;
2820}
2821
Marissa Wall713b63f2018-10-17 15:42:43 -07002822bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002823 // to prevent onHandleDestroyed from being called while the lock is held,
2824 // we must keep a copy of the transactions (specifically the composer
2825 // states) around outside the scope of the lock
2826 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002827 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002828 {
2829 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002830
Valerie Haufce31b82019-04-30 16:41:14 -07002831 auto it = mTransactionQueues.begin();
2832 while (it != mTransactionQueues.end()) {
2833 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002834
Valerie Haufce31b82019-04-30 16:41:14 -07002835 while (!transactionQueue.empty()) {
2836 const auto& transaction = transactionQueue.front();
2837 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002838 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002839 transaction.states)) {
2840 setTransactionFlags(eTransactionFlushNeeded);
2841 break;
2842 }
2843 transactions.push_back(transaction);
2844 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2845 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002846 transaction.buffer, transaction.postTime,
2847 transaction.privileged, transaction.hasListenerCallbacks,
2848 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002849 transactionQueue.pop();
2850 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002851 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002852
Valerie Haufce31b82019-04-30 16:41:14 -07002853 if (transactionQueue.empty()) {
2854 it = mTransactionQueues.erase(it);
2855 mTransactionCV.broadcast();
2856 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002857 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002858 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002859 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002860 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002861 return flushedATransaction;
2862}
2863
2864bool SurfaceFlinger::transactionFlushNeeded() {
2865 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07002866}
2867
chaviwca27f252018-02-06 16:46:39 -08002868
Marissa Wall17b4e452018-12-26 16:32:34 -08002869bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002870 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08002871 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002872 if (!useCachedExpectedPresentTime)
2873 populateExpectedPresentTime();
2874
2875 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08002876 // Do not present if the desiredPresentTime has not passed unless it is more than one second
2877 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
2878 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
2879 desiredPresentTime < expectedPresentTime + s2ns(1)) {
2880 return false;
2881 }
2882
Marissa Wall713b63f2018-10-17 15:42:43 -07002883 for (const ComposerState& state : states) {
2884 const layer_state_t& s = state.state;
2885 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
2886 continue;
2887 }
2888 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08002889 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07002890 }
2891 }
Marissa Wall17b4e452018-12-26 16:32:34 -08002892 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002893}
2894
Valerie Hau9dab9732019-08-20 09:29:25 -07002895void SurfaceFlinger::setTransactionState(
2896 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2897 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
2898 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
2899 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002900 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08002901
Valerie Haubc6ddb12019-03-08 11:10:15 -08002902 const int64_t postTime = systemTime();
2903
Robert Carr14167e02019-02-13 13:50:55 -08002904 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
2905
Mathias Agopian698c0872011-06-28 19:09:31 -07002906 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07002907
Marissa Wall713b63f2018-10-17 15:42:43 -07002908 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07002909 auto itr = mTransactionQueues.find(applyToken);
2910 // if this is an animation frame, wait until prior animation frame has
2911 // been applied by SF
2912 if (flags & eAnimation) {
2913 while (itr != mTransactionQueues.end()) {
2914 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2915 if (CC_UNLIKELY(err != NO_ERROR)) {
2916 ALOGW_IF(err == TIMED_OUT,
2917 "setTransactionState timed out "
2918 "waiting for animation frame to apply");
2919 break;
2920 }
2921 itr = mTransactionQueues.find(applyToken);
2922 }
2923 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002924
2925 // Expected present time is computed and cached on invalidate, so it may be stale.
2926 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
2927 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08002928 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002929 uncacheBuffer, postTime, privileged,
2930 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002931 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002932 return;
2933 }
2934
Valerie Haubc6ddb12019-03-08 11:10:15 -08002935 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002936 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
2937 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07002938}
2939
Valerie Hau9dab9732019-08-20 09:29:25 -07002940void SurfaceFlinger::applyTransactionState(
2941 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2942 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
2943 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
2944 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
2945 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07002946 uint32_t transactionFlags = 0;
2947
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002948 if (flags & eAnimation) {
2949 // For window updates that are part of an animation we must wait for
2950 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07002951 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002952 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002953 if (CC_UNLIKELY(err != NO_ERROR)) {
2954 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002955 // caller after a few seconds.
2956 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2957 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002958 mAnimTransactionPending = false;
2959 break;
2960 }
2961 }
2962 }
2963
chaviwca27f252018-02-06 16:46:39 -08002964 for (const DisplayState& display : displays) {
2965 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002966 }
2967
Valerie Hau9dab9732019-08-20 09:29:25 -07002968 // start and end registration for listeners w/ no surface so they can get their callback. Note
2969 // that listeners with SurfaceControls will start registration during setClientStateLocked
2970 // below.
2971 for (const auto& listener : listenerCallbacks) {
2972 mTransactionCompletedThread.startRegistration(listener);
2973 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07002974 }
2975
Valerie Hau9dab9732019-08-20 09:29:25 -07002976 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07002977 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08002978 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07002979 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
2980 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07002981 }
2982
Valerie Hau9dab9732019-08-20 09:29:25 -07002983 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07002984 mTransactionCompletedThread.endRegistration(listenerCallback);
2985 }
2986
Marissa Walle2ffb422018-10-12 11:33:52 -07002987 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07002988 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07002989 mTransactionCompletedThread.sendCallbacks();
2990 }
2991 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08002992
chaviw273171b2018-12-26 11:46:30 -08002993 transactionFlags |= addInputWindowCommands(inputWindowCommands);
2994
Marissa Wall947d34e2019-03-29 14:03:53 -07002995 if (uncacheBuffer.isValid()) {
2996 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07002997 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07002998 }
2999
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003000 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3001 // anyway. This can be used as a flush mechanism for previous async transactions.
3002 // Empty animation transaction can be used to simulate back-pressure, so also force a
3003 // transaction for empty animation transactions.
3004 if (transactionFlags == 0 &&
3005 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003006 transactionFlags = eTransactionNeeded;
3007 }
3008
Marissa Wall06255332019-03-27 13:48:27 -07003009 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3010 // so we don't have to wake up again next frame to preform an uneeded traversal.
3011 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3012 transactionFlags = transactionFlags & (~eTraversalNeeded);
3013 mTraversalNeededMainThread = true;
3014 }
3015
Mathias Agopian386aa982011-11-07 21:58:03 -08003016 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003017 if (mInterceptor->isEnabled()) {
3018 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003019 }
Irvel468051e2016-06-13 16:44:44 -07003020
Mathias Agopian386aa982011-11-07 21:58:03 -08003021 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003022 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3023 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003024 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003025
3026 // if this is a synchronous transaction, wait for it to take effect
3027 // before returning.
3028 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003029 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003030 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003031 if (flags & eAnimation) {
3032 mAnimTransactionPending = true;
3033 }
chaviw4fe36852019-04-15 16:25:49 -07003034 if (mPendingInputWindowCommands.syncInputWindows) {
3035 mPendingSyncInputWindows = true;
3036 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003037
3038 // applyTransactionState can be called by either the main SF thread or by
3039 // another process through setTransactionState. While a given process may wish
3040 // to wait on synchronous transactions, the main SF thread should never
3041 // be blocked. Therefore, we only wait if isMainThread is false.
3042 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003043 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3044 if (CC_UNLIKELY(err != NO_ERROR)) {
3045 // just in case something goes wrong in SF, return to the
3046 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003047 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3048 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003049 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003050 break;
3051 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003052 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003053 }
3054}
3055
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003056uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3057 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3058 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003059
Mathias Agopiane57f2922012-08-09 16:29:12 -07003060 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003061 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3062
3063 const uint32_t what = s.what;
3064 if (what & DisplayState::eSurfaceChanged) {
3065 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3066 state.surface = s.surface;
3067 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003068 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003069 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003070 if (what & DisplayState::eLayerStackChanged) {
3071 if (state.layerStack != s.layerStack) {
3072 state.layerStack = s.layerStack;
3073 flags |= eDisplayTransactionNeeded;
3074 }
3075 }
3076 if (what & DisplayState::eDisplayProjectionChanged) {
3077 if (state.orientation != s.orientation) {
3078 state.orientation = s.orientation;
3079 flags |= eDisplayTransactionNeeded;
3080 }
3081 if (state.frame != s.frame) {
3082 state.frame = s.frame;
3083 flags |= eDisplayTransactionNeeded;
3084 }
3085 if (state.viewport != s.viewport) {
3086 state.viewport = s.viewport;
3087 flags |= eDisplayTransactionNeeded;
3088 }
3089 }
3090 if (what & DisplayState::eDisplaySizeChanged) {
3091 if (state.width != s.width) {
3092 state.width = s.width;
3093 flags |= eDisplayTransactionNeeded;
3094 }
3095 if (state.height != s.height) {
3096 state.height = s.height;
3097 flags |= eDisplayTransactionNeeded;
3098 }
3099 }
3100
Mathias Agopiane57f2922012-08-09 16:29:12 -07003101 return flags;
3102}
3103
Robert Carr14167e02019-02-13 13:50:55 -08003104bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003105 IPCThreadState* ipc = IPCThreadState::self();
3106 const int pid = ipc->getCallingPid();
3107 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003108 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003109 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003110 return false;
3111 }
3112 return true;
3113}
3114
Marissa Wall3dad52d2019-03-22 14:03:19 -07003115uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003116 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3117 bool privileged,
3118 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003119 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003120
Valerie Hau9dab9732019-08-20 09:29:25 -07003121 for (auto& listener : s.listeners) {
3122 // note that startRegistration will not re-register if the listener has
3123 // already be registered for a prior surface control
3124 mTransactionCompletedThread.startRegistration(listener);
3125 listenerCallbacks.insert(listener);
3126 }
3127
Vishnu Nairf03652d2019-07-16 17:56:56 -07003128 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003129 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003130 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003131 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003132 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003133 }
chaviw8b3871a2017-11-01 17:41:01 -07003134 return 0;
3135 }
3136
chaviw8b3871a2017-11-01 17:41:01 -07003137 uint32_t flags = 0;
3138
Garfield Tan8a3083e2018-12-03 13:21:07 -08003139 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003140
3141 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3142 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003143 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003144 layer->pushPendingState();
3145 }
3146
chaviw8b3871a2017-11-01 17:41:01 -07003147 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003148 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003149 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003150 }
chaviw8b3871a2017-11-01 17:41:01 -07003151 }
3152 if (what & layer_state_t::eLayerChanged) {
3153 // NOTE: index needs to be calculated before we update the state
3154 const auto& p = layer->getParent();
3155 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003156 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003157 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003158 mCurrentState.layersSortedByZ.removeAt(idx);
3159 mCurrentState.layersSortedByZ.add(layer);
3160 // we need traversal (state changed)
3161 // AND transaction (list changed)
3162 flags |= eTransactionNeeded|eTraversalNeeded;
3163 }
chaviw8b3871a2017-11-01 17:41:01 -07003164 } else {
3165 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003166 flags |= eTransactionNeeded|eTraversalNeeded;
3167 }
3168 }
chaviw8b3871a2017-11-01 17:41:01 -07003169 }
3170 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003171 // NOTE: index needs to be calculated before we update the state
3172 const auto& p = layer->getParent();
3173 if (p == nullptr) {
3174 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3175 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3176 mCurrentState.layersSortedByZ.removeAt(idx);
3177 mCurrentState.layersSortedByZ.add(layer);
3178 // we need traversal (state changed)
3179 // AND transaction (list changed)
3180 flags |= eTransactionNeeded|eTraversalNeeded;
3181 }
3182 } else {
3183 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3184 flags |= eTransactionNeeded|eTraversalNeeded;
3185 }
chaviw8b3871a2017-11-01 17:41:01 -07003186 }
3187 }
3188 if (what & layer_state_t::eSizeChanged) {
3189 if (layer->setSize(s.w, s.h)) {
3190 flags |= eTraversalNeeded;
3191 }
3192 }
3193 if (what & layer_state_t::eAlphaChanged) {
3194 if (layer->setAlpha(s.alpha))
3195 flags |= eTraversalNeeded;
3196 }
3197 if (what & layer_state_t::eColorChanged) {
3198 if (layer->setColor(s.color))
3199 flags |= eTraversalNeeded;
3200 }
Peiyong Lind3788632018-09-18 16:01:31 -07003201 if (what & layer_state_t::eColorTransformChanged) {
3202 if (layer->setColorTransform(s.colorTransform)) {
3203 flags |= eTraversalNeeded;
3204 }
3205 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003206 if (what & layer_state_t::eBackgroundColorChanged) {
3207 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3208 flags |= eTraversalNeeded;
3209 }
3210 }
chaviw8b3871a2017-11-01 17:41:01 -07003211 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003212 // TODO: b/109894387
3213 //
3214 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3215 // rotation. To see the problem observe that if we have a square parent, and a child
3216 // of the same size, then we rotate the child 45 degrees around it's center, the child
3217 // must now be cropped to a non rectangular 8 sided region.
3218 //
3219 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3220 // private API, and the WindowManager only uses rotation in one case, which is on a top
3221 // level layer in which cropping is not an issue.
3222 //
3223 // However given that abuse of rotation matrices could lead to surfaces extending outside
3224 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3225 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3226 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003227 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003228 flags |= eTraversalNeeded;
3229 }
3230 if (what & layer_state_t::eTransparentRegionChanged) {
3231 if (layer->setTransparentRegionHint(s.transparentRegion))
3232 flags |= eTraversalNeeded;
3233 }
3234 if (what & layer_state_t::eFlagsChanged) {
3235 if (layer->setFlags(s.flags, s.mask))
3236 flags |= eTraversalNeeded;
3237 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003238 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003239 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003240 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003241 if (what & layer_state_t::eCornerRadiusChanged) {
3242 if (layer->setCornerRadius(s.cornerRadius))
3243 flags |= eTraversalNeeded;
3244 }
chaviw8b3871a2017-11-01 17:41:01 -07003245 if (what & layer_state_t::eLayerStackChanged) {
3246 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3247 // We only allow setting layer stacks for top level layers,
3248 // everything else inherits layer stack from its parent.
3249 if (layer->hasParent()) {
3250 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003251 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003252 } else if (idx < 0) {
3253 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003254 "that also does not appear in the top level layer list. Something"
3255 " has gone wrong.",
3256 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003257 } else if (layer->setLayerStack(s.layerStack)) {
3258 mCurrentState.layersSortedByZ.removeAt(idx);
3259 mCurrentState.layersSortedByZ.add(layer);
3260 // we need traversal (state changed)
3261 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003262 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003263 }
3264 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003265 if (what & layer_state_t::eDeferTransaction_legacy) {
3266 if (s.barrierHandle_legacy != nullptr) {
3267 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3268 } else if (s.barrierGbp_legacy != nullptr) {
3269 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003270 if (authenticateSurfaceTextureLocked(gbp)) {
3271 const auto& otherLayer =
3272 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003273 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003274 } else {
3275 ALOGE("Attempt to defer transaction to to an"
3276 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003277 }
3278 }
chaviw8b3871a2017-11-01 17:41:01 -07003279 // We don't trigger a traversal here because if no other state is
3280 // changed, we don't want this to cause any more work
3281 }
chaviw8b3871a2017-11-01 17:41:01 -07003282 if (what & layer_state_t::eReparentChildren) {
3283 if (layer->reparentChildren(s.reparentHandle)) {
3284 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003285 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003286 }
chaviw8b3871a2017-11-01 17:41:01 -07003287 if (what & layer_state_t::eDetachChildren) {
3288 layer->detachChildren();
3289 }
3290 if (what & layer_state_t::eOverrideScalingModeChanged) {
3291 layer->setOverrideScalingMode(s.overrideScalingMode);
3292 // We don't trigger a traversal here because if no other state is
3293 // changed, we don't want this to cause any more work
3294 }
Marissa Wall61c58622018-07-18 10:12:20 -07003295 if (what & layer_state_t::eTransformChanged) {
3296 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3297 }
3298 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3299 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3300 flags |= eTraversalNeeded;
3301 }
3302 if (what & layer_state_t::eCropChanged) {
3303 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3304 }
Marissa Wall861616d2018-10-22 12:52:23 -07003305 if (what & layer_state_t::eFrameChanged) {
3306 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3307 }
Marissa Wall61c58622018-07-18 10:12:20 -07003308 if (what & layer_state_t::eAcquireFenceChanged) {
3309 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3310 }
3311 if (what & layer_state_t::eDataspaceChanged) {
3312 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3313 }
3314 if (what & layer_state_t::eHdrMetadataChanged) {
3315 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3316 }
3317 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3318 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3319 }
3320 if (what & layer_state_t::eApiChanged) {
3321 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3322 }
3323 if (what & layer_state_t::eSidebandStreamChanged) {
3324 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3325 }
Robert Carr720e5062018-07-30 17:45:14 -07003326 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003327 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003328 layer->setInputInfo(s.inputInfo);
3329 flags |= eTraversalNeeded;
3330 } else {
3331 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3332 }
Robert Carr720e5062018-07-30 17:45:14 -07003333 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003334 if (what & layer_state_t::eMetadataChanged) {
3335 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3336 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003337 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3338 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3339 flags |= eTraversalNeeded;
3340 }
3341 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003342 if (what & layer_state_t::eShadowRadiusChanged) {
3343 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3344 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003345 // This has to happen after we reparent children because when we reparent to null we remove
3346 // child layers from current state and remove its relative z. If the children are reparented in
3347 // the same transaction, then we have to make sure we reparent the children first so we do not
3348 // lose its relative z order.
3349 if (what & layer_state_t::eReparent) {
3350 bool hadParent = layer->hasParent();
3351 if (layer->reparent(s.parentHandleForChild)) {
3352 if (!hadParent) {
3353 mCurrentState.layersSortedByZ.remove(layer);
3354 }
3355 flags |= eTransactionNeeded | eTraversalNeeded;
3356 }
3357 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003358 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003359 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3360 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003361 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3362 }
3363 }
Marissa Wall78b72202019-03-15 14:58:34 -07003364 bool bufferChanged = what & layer_state_t::eBufferChanged;
3365 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3366 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003367 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003368 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003369 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3370 if (success) {
3371 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3372 success = ClientCache::getInstance()
3373 .registerErasedRecipient(s.cachedBuffer,
3374 wp<ClientCache::ErasedRecipient>(this));
3375 if (!success) {
3376 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3377 }
3378 }
Marissa Wall78b72202019-03-15 14:58:34 -07003379 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003380 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003381 } else if (bufferChanged) {
3382 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003383 }
Marissa Wall78b72202019-03-15 14:58:34 -07003384 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003385 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003386 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003387 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003388 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003389 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3390 // Do not put anything that updates layer state or modifies flags after
3391 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003392 return flags;
3393}
3394
chaviw273171b2018-12-26 11:46:30 -08003395uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3396 uint32_t flags = 0;
3397 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3398 flags |= eTraversalNeeded;
3399 }
3400
chaviwa911b102019-02-14 10:18:33 -08003401 if (inputWindowCommands.syncInputWindows) {
3402 flags |= eTraversalNeeded;
3403 }
3404
Vishnu Nairec0ab382019-02-13 15:32:56 -08003405 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003406 return flags;
3407}
3408
chaviwfe94a222019-08-21 13:52:59 -07003409status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3410 sp<IBinder>* outHandle) {
3411 if (!mirrorFromHandle) {
3412 return NAME_NOT_FOUND;
3413 }
3414
3415 sp<Layer> mirrorLayer;
3416 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003417 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003418
3419 {
3420 Mutex::Autolock _l(mStateLock);
3421 mirrorFrom = fromHandle(mirrorFromHandle);
3422 if (!mirrorFrom) {
3423 return NAME_NOT_FOUND;
3424 }
3425
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003426 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3427 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003428 if (result != NO_ERROR) {
3429 return result;
3430 }
3431
3432 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3433 }
3434
3435 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3436}
3437
Marissa Wall2d814fb2019-04-09 18:52:57 +00003438status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3439 uint32_t h, PixelFormat format, uint32_t flags,
3440 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003441 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003442 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3443 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003444 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003445 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003446 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003447 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003448 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003449
Robert Carrc0df3122019-04-11 13:18:21 -07003450 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3451 "Expected only one of parentLayer or parentHandle to be non-null. "
3452 "Programmer error?");
3453
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003454 status_t result = NO_ERROR;
3455
3456 sp<Layer> layer;
3457
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003458 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003459
Evan Roskya1f1e152019-01-24 16:17:46 -08003460 bool primaryDisplayOnly = false;
3461
3462 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3463 // TODO b/64227542
3464 if (metadata.has(METADATA_WINDOW_TYPE)) {
3465 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3466 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003467 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003468 primaryDisplayOnly = true;
3469 }
3470 }
3471
Mathias Agopian3165cc22012-08-08 19:42:09 -07003472 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003473 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003474 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3475 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003476
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003477 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003478 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003479 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003480 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003481 break;
chaviw13fdc492017-06-27 12:40:18 -07003482 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003483 // check if buffer size is set for color layer.
3484 if (w > 0 || h > 0) {
3485 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3486 int(w), int(h));
3487 return BAD_VALUE;
3488 }
3489
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003490 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3491 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003492 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003493 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003494 // check if buffer size is set for container layer.
3495 if (w > 0 || h > 0) {
3496 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3497 int(w), int(h));
3498 return BAD_VALUE;
3499 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003500 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3501 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003502 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003503 default:
3504 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003505 break;
3506 }
3507
Dan Stoza7d89d062015-04-30 13:29:25 -07003508 if (result != NO_ERROR) {
3509 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003510 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003511
Evan Roskya1f1e152019-01-24 16:17:46 -08003512 if (primaryDisplayOnly) {
3513 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003514 }
3515
Robert Carrb89ea9d2018-12-10 13:01:14 -08003516 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003517 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3518 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003519 if (result != NO_ERROR) {
3520 return result;
3521 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003522 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003523
3524 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003525 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003526}
3527
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003528std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3529 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003530
3531 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003532 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003533
Dan Stoza436ccf32018-06-21 12:10:12 -07003534 // Grab the state lock since we're accessing mCurrentState
3535 Mutex::Autolock lock(mStateLock);
3536
Cody Northropbc755282017-03-31 12:00:08 -06003537 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003538 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003539 while (matchFound) {
3540 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003541 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003542 if (layer->getName() == uniqueName) {
3543 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003544 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003545 }
3546 });
3547 }
3548
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003549 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003550 return uniqueName;
3551}
3552
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003553status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003554 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003555 LayerMetadata metadata, PixelFormat& format,
3556 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003557 sp<IGraphicBufferProducer>* gbp,
3558 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003559 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003560 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003561 case PIXEL_FORMAT_TRANSPARENT:
3562 case PIXEL_FORMAT_TRANSLUCENT:
3563 format = PIXEL_FORMAT_RGBA_8888;
3564 break;
3565 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003566 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003567 break;
3568 }
3569
chaviwb4c6e582019-08-16 14:35:07 -07003570 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003571 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003572 args.textureName = getNewTexture();
3573 {
3574 // Grab the SF state lock during this since it's the only safe way to access
3575 // RenderEngine when creating a BufferLayerConsumer
3576 // TODO: Check if this lock is still needed here
3577 Mutex::Autolock lock(mStateLock);
3578 layer = getFactory().createBufferQueueLayer(args);
3579 }
3580
Marissa Wallfd668622018-05-10 10:21:13 -07003581 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003582 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003583 *handle = layer->getHandle();
3584 *gbp = layer->getProducer();
3585 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003586 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003587
Marissa Wallfd668622018-05-10 10:21:13 -07003588 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003589 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003590}
3591
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003592status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003593 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003594 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003595 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003596 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003597 args.displayDevice = getDefaultDisplayDevice();
3598 args.textureName = getNewTexture();
3599 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003600 if (outTransformHint) {
3601 *outTransformHint = layer->getTransformHint();
3602 }
Marissa Wall61c58622018-07-18 10:12:20 -07003603 *handle = layer->getHandle();
3604 *outLayer = layer;
3605
3606 return NO_ERROR;
3607}
3608
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003609status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003610 uint32_t h, uint32_t flags, LayerMetadata metadata,
3611 sp<IBinder>* handle, sp<Layer>* outLayer) {
3612 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003613 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003614 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003615 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003616}
3617
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003618status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003619 uint32_t w, uint32_t h, uint32_t flags,
3620 LayerMetadata metadata, sp<IBinder>* handle,
3621 sp<Layer>* outLayer) {
3622 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003623 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003624 *handle = (*outLayer)->getHandle();
3625 return NO_ERROR;
3626}
3627
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003628void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003629 mLayersPendingRemoval.add(layer);
3630 mLayersRemoved = true;
3631 setTransactionFlags(eTransactionNeeded);
3632}
3633
Robert Carr695d5282018-12-18 15:27:58 -08003634void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003635{
Robert Carr2e102c92018-10-23 12:11:15 -07003636 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003637 // If a layer has a parent, we allow it to out-live it's handle
3638 // with the idea that the parent holds a reference and will eventually
3639 // be cleaned up. However no one cleans up the top-level so we do so
3640 // here.
3641 if (layer->getParent() == nullptr) {
3642 mCurrentState.layersSortedByZ.remove(layer);
3643 }
3644 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003645
3646 auto it = mLayersByLocalBinderToken.begin();
3647 while (it != mLayersByLocalBinderToken.end()) {
3648 if (it->second == layer) {
3649 it = mLayersByLocalBinderToken.erase(it);
3650 } else {
3651 it++;
3652 }
3653 }
3654
Robert Carr695d5282018-12-18 15:27:58 -08003655 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003656}
3657
Mathias Agopianb60314a2012-04-10 22:09:54 -07003658// ---------------------------------------------------------------------------
3659
Andy McFadden13a082e2012-08-24 10:16:42 -07003660void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003661 const auto display = getDefaultDisplayDeviceLocked();
3662 if (!display) return;
3663
3664 const sp<IBinder> token = display->getDisplayToken().promote();
3665 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003666
Jesse Hall01e29052013-02-19 16:13:35 -08003667 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003668 Vector<ComposerState> state;
3669 Vector<DisplayState> displays;
3670 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003671 d.what = DisplayState::eDisplayProjectionChanged |
3672 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003673 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003674 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003675 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003676 d.frame.makeInvalid();
3677 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003678 d.width = 0;
3679 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003680 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003681 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3682 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003683
Dominik Laskowskie9774092018-12-11 10:04:24 -08003684 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003685
Dominik Laskowski83b88212018-12-11 13:34:06 -08003686 const nsecs_t vsyncPeriod = getVsyncPeriod();
3687 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003688
Brian Andersond0010582017-03-07 13:20:31 -08003689 // Use phase of 0 since phase is not known.
3690 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003691 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003692 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003693}
3694
3695void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003696 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003697 postMessageAsync(
3698 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003699}
3700
Ady Abraham27c70212019-06-11 10:52:26 -07003701void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3702 if (mHWCVsyncState != enabled) {
3703 getHwComposer().setVsyncEnabled(displayId, enabled);
3704 mHWCVsyncState = enabled;
3705 }
3706}
3707
Dominik Laskowskie9774092018-12-11 10:04:24 -08003708void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003709 if (display->isVirtual()) {
3710 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003711 return;
3712 }
3713
Dominik Laskowski075d3172018-05-24 15:50:06 -07003714 const auto displayId = display->getId();
3715 LOG_ALWAYS_FATAL_IF(!displayId);
3716
Dominik Laskowski34157762018-10-31 13:07:19 -07003717 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003718
3719 int currentMode = display->getPowerMode();
3720 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003721 return;
3722 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003723
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003724 display->setPowerMode(mode);
3725
Lloyd Pique4dccc412018-01-22 17:21:36 -08003726 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003727 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003728 }
3729
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003730 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003731 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003732 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003733 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003734 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003735 mScheduler->onScreenAcquired(mAppConnectionHandle);
3736 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003737 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003738
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003739 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003740 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003741 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003742
3743 struct sched_param param = {0};
3744 param.sched_priority = 1;
3745 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3746 ALOGW("Couldn't set SCHED_FIFO on display on");
3747 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003748 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003749 // Turn off the display
3750 struct sched_param param = {0};
3751 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3752 ALOGW("Couldn't set SCHED_OTHER on display off");
3753 }
3754
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003755 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003756 mScheduler->disableHardwareVsync(true);
3757 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003758 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003759
Ady Abraham27c70212019-06-11 10:52:26 -07003760 // Make sure HWVsync is disabled before turning off the display
3761 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3762
Dominik Laskowski075d3172018-05-24 15:50:06 -07003763 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003764 mVisibleRegionsDirty = true;
3765 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003766 } else if (mode == HWC_POWER_MODE_DOZE ||
3767 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003768 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003769 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003770 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003771 mScheduler->onScreenAcquired(mAppConnectionHandle);
3772 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003773 }
3774 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3775 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003776 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003777 mScheduler->disableHardwareVsync(true);
3778 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003779 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003780 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003781 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003782 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003783 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003784 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003785
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003786 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003787 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003788 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003789 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003790 }
3791
Dominik Laskowski34157762018-10-31 13:07:19 -07003792 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003793}
3794
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003795void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003796 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003797 const auto display = getDisplayDevice(displayToken);
3798 if (!display) {
3799 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3800 displayToken.get());
3801 } else if (display->isVirtual()) {
3802 ALOGW("Attempt to set power mode %d for virtual display", mode);
3803 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003804 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003805 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003806 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003807}
3808
3809// ---------------------------------------------------------------------------
3810
Dominik Laskowskic2867142019-01-21 11:33:38 -08003811status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3812 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003813 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003814
Mathias Agopianbd115332013-04-18 16:41:04 -07003815 IPCThreadState* ipc = IPCThreadState::self();
3816 const int pid = ipc->getCallingPid();
3817 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003818
Mathias Agopianbd115332013-04-18 16:41:04 -07003819 if ((uid != AID_SHELL) &&
3820 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003821 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3822 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003823 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003824 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003825 // (this would indicate SF is stuck, but we want to be able to
3826 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003827 status_t err = mStateLock.timedLock(s2ns(1));
3828 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003829 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003830 StringAppendF(&result,
3831 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3832 "(no locks held)\n",
3833 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003834 }
3835
Dominik Laskowskic2867142019-01-21 11:33:38 -08003836 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003837 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003838 {"--dispsync"s,
3839 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003840 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003841 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3842 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3843 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3844 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3845 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3846 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003847 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003848 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3849 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003850
Dominik Laskowskic2867142019-01-21 11:33:38 -08003851 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003852
Dominik Laskowski46470112019-08-02 13:13:11 -07003853 const auto it = dumpers.find(flag);
3854 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003855 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07003856 } else if (!asProto) {
3857 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003858 }
3859
Mathias Agopian9795c422009-08-26 16:36:26 -07003860 if (locked) {
3861 mStateLock.unlock();
3862 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003863
Dominik Laskowski46470112019-08-02 13:13:11 -07003864 if (it == dumpers.end()) {
3865 const LayersProto layersProto = dumpProtoFromMainThread();
3866 if (asProto) {
3867 result.append(layersProto.SerializeAsString());
3868 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07003869 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07003870 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3871 result.append(LayerProtoParser::layerTreeToString(layerTree));
3872 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07003873 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07003874 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003875 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003876 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08003877 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003878 return NO_ERROR;
3879}
3880
Nataniel Borges8e7dc722019-02-28 15:10:28 -08003881status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
3882 if (asProto && mTracing.isEnabled()) {
3883 mTracing.writeToFileAsync();
3884 }
3885
3886 return doDump(fd, DumpArgs(), asProto);
3887}
3888
Dominik Laskowskic2867142019-01-21 11:33:38 -08003889void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003890 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003891 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003892}
3893
Dominik Laskowskic2867142019-01-21 11:33:38 -08003894void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003895 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003896
Dominik Laskowskic2867142019-01-21 11:33:38 -08003897 if (args.size() > 1) {
3898 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08003899 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003900 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003901 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003902 }
Robert Carr2047fae2016-11-28 14:09:09 -08003903 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08003904 } else {
3905 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003906 }
3907}
3908
Dominik Laskowskic2867142019-01-21 11:33:38 -08003909void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003910 const bool clearAll = args.size() < 2;
3911 const auto name = clearAll ? String8() : String8(args[1]);
3912
Robert Carr2047fae2016-11-28 14:09:09 -08003913 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003914 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003915 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003916 }
Robert Carr2047fae2016-11-28 14:09:09 -08003917 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003918
Svetoslavd85084b2014-03-20 10:28:31 -07003919 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003920}
3921
Dominik Laskowskic2867142019-01-21 11:33:38 -08003922void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
3923 mTimeStats->parseArgs(asProto, args, result);
3924}
3925
Jamie Gennis6547ff42013-07-16 20:12:42 -07003926// This should only be called from the main thread. Otherwise it would need
3927// the lock and should use mCurrentState rather than mDrawingState.
3928void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003929 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003930 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003931 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003932
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003933 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07003934}
3935
Yiwei Zhang5434a782018-12-05 18:06:32 -08003936void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003937 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003938
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003939 if (isLayerTripleBufferingDisabled())
3940 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003941
Yiwei Zhang5434a782018-12-05 18:06:32 -08003942 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
3943 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
3944 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
3945 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
3946 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3947 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003948 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003949}
3950
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003951void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07003952 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07003953
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003954 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07003955 result.append("\n");
3956
Ana Krulec757f63a2019-01-25 10:46:18 -08003957 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003958 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07003959 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08003960 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003961
Ady Abraham42b3beb2019-07-09 18:09:52 -07003962 StringAppendF(&result, "Allowed Display Configs: ");
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003963 for (int32_t configId : mAllowedDisplayConfigs) {
3964 StringAppendF(&result, "%" PRIu32 " Hz, ",
3965 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07003966 }
3967 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
3968 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07003969
Ana Krulecc2870422019-01-29 19:00:58 -08003970 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003971}
3972
Yiwei Zhang5434a782018-12-05 18:06:32 -08003973void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
3974 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003975 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3976 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003977 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003978 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003979 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003980 }
David Sodman4a36e932017-11-07 14:29:47 -08003981 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003982 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003983 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003984 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
3985 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003986}
3987
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003988void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
3989 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003990 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3991 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003992 for (const auto& segment : history) {
3993 if (!segment.usedThirdBuffer) {
3994 stats.twoBufferTime += segment.totalTime;
3995 }
3996 if (segment.occupancyAverage < 1.0f) {
3997 stats.doubleBufferedTime += segment.totalTime;
3998 } else if (segment.occupancyAverage < 2.0f) {
3999 stats.tripleBufferedTime += segment.totalTime;
4000 }
4001 ++stats.numSegments;
4002 stats.totalTime += segment.totalTime;
4003 }
4004}
4005
Yiwei Zhang5434a782018-12-05 18:06:32 -08004006void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4007 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004008
4009 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4010 const size_t count = currentLayers.size();
4011 for (size_t i=0 ; i<count ; i++) {
4012 currentLayers[i]->dumpFrameEvents(result);
4013 }
4014}
4015
Yiwei Zhang5434a782018-12-05 18:06:32 -08004016void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004017 result.append("Buffering stats:\n");
4018 result.append(" [Layer name] <Active time> <Two buffer> "
4019 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004020 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004021 typedef std::tuple<std::string, float, float, float> BufferTuple;
4022 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004023 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004024 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004025 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004026 if (stats.numSegments == 0) {
4027 continue;
4028 }
4029 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4030 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4031 stats.totalTime;
4032 float doubleBufferRatio = static_cast<float>(
4033 stats.doubleBufferedTime) / stats.totalTime;
4034 float tripleBufferRatio = static_cast<float>(
4035 stats.tripleBufferedTime) / stats.totalTime;
4036 sorted.insert({activeTime, {name, twoBufferRatio,
4037 doubleBufferRatio, tripleBufferRatio}});
4038 }
4039 for (const auto& sortedPair : sorted) {
4040 float activeTime = sortedPair.first;
4041 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004042 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4043 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004044 }
4045 result.append("\n");
4046}
4047
Yiwei Zhang5434a782018-12-05 18:06:32 -08004048void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004049 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004050 const auto displayId = display->getId();
4051 if (!displayId) {
4052 continue;
4053 }
4054 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004055 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004056 continue;
4057 }
4058
Yiwei Zhang5434a782018-12-05 18:06:32 -08004059 StringAppendF(&result,
4060 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4061 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004062 uint8_t port;
4063 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004064 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004065 result.append("no identification data\n");
4066 continue;
4067 }
4068
4069 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004070 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004071 continue;
4072 }
4073
4074 const auto edid = parseEdid(data);
4075 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004076 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004077 continue;
4078 }
4079
Yiwei Zhang5434a782018-12-05 18:06:32 -08004080 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004081 result.append(edid->displayName.data(), edid->displayName.length());
4082 result.append("\"\n");
4083 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004084}
4085
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004086void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4087 std::string& result) const {
4088 hwc2_display_t hwcDisplayId;
4089 uint8_t port;
4090 DisplayIdentificationData data;
4091
4092 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4093 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4094 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4095 }
4096}
4097
Yiwei Zhang5434a782018-12-05 18:06:32 -08004098void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004099 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004100 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4101 StringAppendF(&result, "DisplayColorSetting: %s\n",
4102 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004103
4104 // TODO: print out if wide-color mode is active or not
4105
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004106 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004107 const auto displayId = display->getId();
4108 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004109 continue;
4110 }
4111
Yiwei Zhang5434a782018-12-05 18:06:32 -08004112 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004113 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004114 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004115 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004116 }
4117
Lloyd Pique32cbe282018-10-19 13:09:22 -07004118 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004119 StringAppendF(&result, " Current color mode: %s (%d)\n",
4120 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004121 }
4122 result.append("\n");
4123}
4124
Vishnu Nair8406fd72019-07-30 11:29:31 -07004125LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004126 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004127 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004128 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004129 layer->writeToProtoDrawingState(layerProto, traceFlags);
4130 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004131 });
4132
4133 return layersProto;
4134}
4135
Vishnu Nair0f085c62019-08-30 08:49:12 -07004136void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4137 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4138 // it.
4139 LayerProto* rootProto = layersProto.add_layers();
4140 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4141 rootProto->set_id(offscreenRootLayerId);
4142 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004143 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004144
4145 for (Layer* offscreenLayer : mOffscreenLayers) {
4146 // Add layer as child of the fake root
4147 rootProto->add_children(offscreenLayer->sequence);
4148
4149 // Add layer
4150 LayerProto* layerProto = layersProto.add_layers();
4151 offscreenLayer->writeToProtoDrawingState(layerProto, traceFlags);
4152 offscreenLayer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing,
4153 traceFlags);
4154 layerProto->set_parent(offscreenRootLayerId);
4155
4156 // Add children
4157 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4158 if (layer == offscreenLayer) {
4159 return;
4160 }
4161 LayerProto* childProto = layersProto.add_layers();
4162 layer->writeToProtoDrawingState(childProto, traceFlags);
4163 layer->writeToProtoCommonState(childProto, LayerVector::StateSet::Drawing, traceFlags);
4164 });
4165 }
4166}
4167
Vishnu Nair8406fd72019-07-30 11:29:31 -07004168LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4169 LayersProto layersProto;
4170 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4171 return layersProto;
4172}
4173
Vishnu Nair0f085c62019-08-30 08:49:12 -07004174void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4175 result.append("Offscreen Layers:\n");
4176 postMessageSync(new LambdaMessage([&]() {
4177 for (Layer* offscreenLayer : mOffscreenLayers) {
4178 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4179 layer->dumpCallingUidPid(result);
4180 });
4181 }
4182 }));
4183}
4184
Dominik Laskowskic2867142019-01-21 11:33:38 -08004185void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4186 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004187 Colorizer colorizer(colorize);
4188
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004189 // figure out if we're stuck somewhere
4190 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004191 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004192 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4193
4194 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004195 * Dump library configuration.
4196 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004197
4198 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004199 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004200 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004201 appendSfConfigString(result);
4202 appendUiConfigString(result);
4203 appendGuiConfigString(result);
4204 result.append("\n");
4205
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004206 result.append("\nDisplay identification data:\n");
4207 dumpDisplayIdentificationData(result);
4208
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004209 result.append("\nWide-Color information:\n");
4210 dumpWideColorInfo(result);
4211
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004212 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004213 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004214 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004215 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004216 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004217
Andy McFadden41d67d72014-04-25 16:58:34 -07004218 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004219 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004220 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004221 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004222 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004223
Dan Stozab90cf072015-03-05 11:05:59 -08004224 dumpStaticScreenStats(result);
4225 result.append("\n");
4226
Alec Mouri40189b02019-03-05 15:07:54 -08004227 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4228 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4229 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004230
Dan Stozae77c7662016-05-13 11:37:28 -07004231 dumpBufferingStats(result);
4232
Andy McFadden4803b742012-09-24 19:07:20 -07004233 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004234 * Dump the visible layer list
4235 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004236 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004237 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004238 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4239 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004240 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004241
Chia-I Wu2f884132018-09-13 15:17:58 -07004242 {
Lloyd Pique207def92019-02-28 16:09:52 -08004243 StringAppendF(&result, "Composition layers\n");
4244 mDrawingState.traverseInZOrder([&](Layer* layer) {
4245 auto compositionLayer = layer->getCompositionLayer();
4246 if (compositionLayer) compositionLayer->dump(result);
4247 });
4248 }
4249
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004250 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004251 * Dump Display state
4252 */
4253
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004254 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004255 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004256 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004257 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004258 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004259 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004260 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004261
4262 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004263 * Dump CompositionEngine state
4264 */
4265
4266 mCompositionEngine->dump(result);
4267
4268 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004269 * Dump SurfaceFlinger global state
4270 */
4271
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004272 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004273 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004274 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004275
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004276 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004277
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004278 DebugEGLImageTracker::getInstance()->dump(result);
4279
Dominik Laskowski075d3172018-05-24 15:50:06 -07004280 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004281 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4282 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004283 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4284 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004285 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004286 StringAppendF(&result,
4287 " transaction-flags : %08x\n"
4288 " gpu_to_cpu_unsupported : %d\n",
4289 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004290
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004291 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004292 displayId && getHwComposer().isConnected(*displayId)) {
4293 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004294 StringAppendF(&result,
4295 " refresh-rate : %f fps\n"
4296 " x-dpi : %f\n"
4297 " y-dpi : %f\n",
4298 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4299 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004300 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004301
Yiwei Zhang5434a782018-12-05 18:06:32 -08004302 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004303
Dan Stozae22aec72016-08-01 13:20:59 -07004304 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004305 * Tracing state
4306 */
4307 mTracing.dump(result);
4308 result.append("\n");
4309
4310 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004311 * HWC layer minidump
4312 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004313 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004314 const auto displayId = display->getId();
4315 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004316 continue;
4317 }
4318
Yiwei Zhang5434a782018-12-05 18:06:32 -08004319 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004320 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004321 const sp<DisplayDevice> displayDevice = display;
4322 mCurrentState.traverseInZOrder(
4323 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004324 result.append("\n");
4325 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004326
4327 /*
4328 * Dump HWComposer state
4329 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004330 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004331 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004332 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004333 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004334 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004335 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004336
4337 /*
4338 * Dump gralloc state
4339 */
4340 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4341 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004342
4343 /*
4344 * Dump VrFlinger state if in use.
4345 */
4346 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4347 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004348 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004349 result.append("\n");
4350 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004351
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004352 result.append(mTimeStats->miniDump());
4353 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004354}
4355
Chia-I Wu28f320b2018-05-03 11:02:56 -07004356void SurfaceFlinger::updateColorMatrixLocked() {
4357 mat4 colorMatrix;
4358 if (mGlobalSaturationFactor != 1.0f) {
4359 // Rec.709 luma coefficients
4360 float3 luminance{0.213f, 0.715f, 0.072f};
4361 luminance *= 1.0f - mGlobalSaturationFactor;
4362 mat4 saturationMatrix = mat4(
4363 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4364 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4365 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4366 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4367 );
4368 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4369 } else {
4370 colorMatrix = mClientColorMatrix * mDaltonizer();
4371 }
4372
4373 if (mCurrentState.colorMatrix != colorMatrix) {
4374 mCurrentState.colorMatrix = colorMatrix;
4375 mCurrentState.colorMatrixChanged = true;
4376 setTransactionFlags(eTransactionNeeded);
4377 }
4378}
4379
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004380status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004381#pragma clang diagnostic push
4382#pragma clang diagnostic error "-Wswitch-enum"
4383 switch (static_cast<ISurfaceComposerTag>(code)) {
4384 // These methods should at minimum make sure that the client requested
4385 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004386 case BOOT_FINISHED:
4387 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004388 case CREATE_DISPLAY:
4389 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004390 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004391 case GET_ANIMATION_FRAME_STATS:
4392 case GET_HDR_CAPABILITIES:
4393 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004394 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004395 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004396 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004397 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004398 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004399 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004400 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004401 case GET_DISPLAYED_CONTENT_SAMPLE:
4402 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004403 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4404 IPCThreadState* ipc = IPCThreadState::self();
4405 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4406 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004407 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004408 }
Robert Carr1db73f62016-12-21 12:58:51 -08004409 return OK;
4410 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004411 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004412 IPCThreadState* ipc = IPCThreadState::self();
4413 const int pid = ipc->getCallingPid();
4414 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004415 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4416 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004417 return PERMISSION_DENIED;
4418 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004419 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004420 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004421 // Used by apps to hook Choreographer to SurfaceFlinger.
4422 case CREATE_DISPLAY_EVENT_CONNECTION:
4423 // The following calls are currently used by clients that do not
4424 // request necessary permissions. However, they do not expose any secret
4425 // information, so it is OK to pass them.
4426 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004427 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004428 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004429 case GET_PHYSICAL_DISPLAY_IDS:
4430 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004431 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004432 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004433 case GET_DISPLAY_CONFIGS:
4434 case GET_DISPLAY_STATS:
4435 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4436 // Calling setTransactionState is safe, because you need to have been
4437 // granted a reference to Client* and Handle* to do anything with it.
4438 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004439 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004440 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004441 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004442 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004443 case IS_WIDE_COLOR_DISPLAY:
4444 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4445 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004446 return OK;
4447 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004448 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004449 case CAPTURE_SCREEN:
4450 case ADD_REGION_SAMPLING_LISTENER:
4451 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004452 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004453 IPCThreadState* ipc = IPCThreadState::self();
4454 const int pid = ipc->getCallingPid();
4455 const int uid = ipc->getCallingUid();
4456 if ((uid != AID_GRAPHICS) &&
4457 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4458 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4459 return PERMISSION_DENIED;
4460 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004461 return OK;
4462 }
4463 // The following codes are deprecated and should never be allowed to access SF.
4464 case CONNECT_DISPLAY_UNUSED:
4465 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4466 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4467 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004468 }
chaviw93df2ea2019-04-30 16:45:12 -07004469 case CAPTURE_SCREEN_BY_ID: {
4470 IPCThreadState* ipc = IPCThreadState::self();
4471 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004472 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004473 return OK;
4474 }
4475 return PERMISSION_DENIED;
4476 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004477 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004478
4479 // These codes are used for the IBinder protocol to either interrogate the recipient
4480 // side of the transaction for its canonical interface descriptor or to dump its state.
4481 // We let them pass by default.
4482 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4483 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4484 code == IBinder::SYSPROPS_TRANSACTION) {
4485 return OK;
4486 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004487 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004488 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004489 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004490 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4491 return OK;
4492 }
4493 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4494 return PERMISSION_DENIED;
4495#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004496}
4497
Ana Krulec13be8ad2018-08-21 02:43:56 +00004498status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4499 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004500 status_t credentialCheck = CheckTransactCodeCredentials(code);
4501 if (credentialCheck != OK) {
4502 return credentialCheck;
4503 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004504
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004505 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4506 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004507 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004508 IPCThreadState* ipc = IPCThreadState::self();
4509 const int uid = ipc->getCallingUid();
4510 if (CC_UNLIKELY(uid != AID_SYSTEM
4511 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004512 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004513 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004514 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004515 return PERMISSION_DENIED;
4516 }
4517 int n;
4518 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004519 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004520 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004521 return NO_ERROR;
4522 case 1002: // SHOW_UPDATES
4523 n = data.readInt32();
4524 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004525 invalidateHwcGeometry();
4526 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004527 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004528 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004529 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004530 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004531 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004532 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004533 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004534 setTransactionFlags(
4535 eTransactionNeeded|
4536 eDisplayTransactionNeeded|
4537 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004538 return NO_ERROR;
4539 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004540 case 1006:{ // send empty update
4541 signalRefresh();
4542 return NO_ERROR;
4543 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004544 case 1008: // toggle use of hw composer
4545 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004546 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004547 invalidateHwcGeometry();
4548 repaintEverything();
4549 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004550 case 1009: // toggle use of transform hint
4551 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004552 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004553 invalidateHwcGeometry();
4554 repaintEverything();
4555 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004556 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004557 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004558 reply->writeInt32(0);
4559 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004560 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004561 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004562 return NO_ERROR;
4563 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004564 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004565 if (!display) {
4566 return NAME_NOT_FOUND;
4567 }
4568
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004569 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004570 return NO_ERROR;
4571 }
4572 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004573 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004574 // daltonize
4575 n = data.readInt32();
4576 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004577 case 1:
4578 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4579 break;
4580 case 2:
4581 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4582 break;
4583 case 3:
4584 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4585 break;
4586 default:
4587 mDaltonizer.setType(ColorBlindnessType::None);
4588 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004589 }
4590 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004591 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004592 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004593 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004594 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004595
4596 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004597 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004598 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004599 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004600 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004601 // apply a color matrix
4602 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004603 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004604 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004605 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004606 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004607 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004608 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004609 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004610 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004611 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004612 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004613
4614 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4615 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004616 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004617 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4618 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4619 }
4620
Chia-I Wu28f320b2018-05-03 11:02:56 -07004621 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004622 return NO_ERROR;
4623 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004624 case 1016: { // Unused.
4625 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004626 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004627 case 1017: {
4628 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004629 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004630 return NO_ERROR;
4631 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004632 case 1018: { // Modify Choreographer's phase offset
4633 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004634 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004635 return NO_ERROR;
4636 }
4637 case 1019: { // Modify SurfaceFlinger's phase offset
4638 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004639 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004640 return NO_ERROR;
4641 }
Irvel468051e2016-06-13 16:44:44 -07004642 case 1020: { // Layer updates interceptor
4643 n = data.readInt32();
4644 if (n) {
4645 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004646 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004647 }
4648 else{
4649 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004650 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004651 }
4652 return NO_ERROR;
4653 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004654 case 1021: { // Disable HWC virtual displays
4655 n = data.readInt32();
4656 mUseHwcVirtualDisplays = !n;
4657 return NO_ERROR;
4658 }
Romain Guy0147a172017-06-01 13:53:56 -07004659 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004660 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004661 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004662
Chia-I Wu28f320b2018-05-03 11:02:56 -07004663 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004664 return NO_ERROR;
4665 }
Romain Guy54f154a2017-10-24 21:40:32 +01004666 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004667 int32_t colorMode;
4668
Chia-I Wu0d711262018-05-21 15:19:35 -07004669 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004670 if (data.readInt32(&colorMode) == NO_ERROR) {
4671 mForceColorMode = static_cast<ColorMode>(colorMode);
4672 }
Romain Guy54f154a2017-10-24 21:40:32 +01004673 invalidateHwcGeometry();
4674 repaintEverything();
4675 return NO_ERROR;
4676 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004677 // Deprecate, use 1030 to check whether the device is color managed.
4678 case 1024: {
4679 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004680 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004681 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004682 n = data.readInt32();
4683 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004684 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004685 Mutex::Autolock lock(mStateLock);
4686 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004687 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004688 reply->writeInt32(NO_ERROR);
4689 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004690 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004691 bool writeFile = false;
4692 {
4693 Mutex::Autolock lock(mStateLock);
4694 mTracingEnabledChanged = true;
4695 writeFile = mTracing.disable();
4696 }
4697
4698 if (writeFile) {
4699 reply->writeInt32(mTracing.writeToFile());
4700 } else {
4701 reply->writeInt32(NO_ERROR);
4702 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004703 }
4704 return NO_ERROR;
4705 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004706 case 1026: { // Get layer tracing status
4707 reply->writeBool(mTracing.isEnabled());
4708 return NO_ERROR;
4709 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004710 // Is a DisplayColorSetting supported?
4711 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004712 const auto display = getDefaultDisplayDevice();
4713 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004714 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004715 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004716
4717 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4718 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004719 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004720 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004721 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004722 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004723 reply->writeBool(true);
4724 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004725 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004726 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004727 break;
4728 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004729 reply->writeBool(
4730 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004731 break;
4732 }
4733 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004734 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004735 // Is VrFlinger active?
4736 case 1028: {
4737 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004738 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004739 return NO_ERROR;
4740 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004741 // Set buffer size for SF tracing (value in KB)
4742 case 1029: {
4743 n = data.readInt32();
4744 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4745 ALOGW("Invalid buffer size: %d KB", n);
4746 reply->writeInt32(BAD_VALUE);
4747 return BAD_VALUE;
4748 }
4749
4750 ALOGD("Updating trace buffer to %d KB", n);
4751 mTracing.setBufferSize(n * 1024);
4752 reply->writeInt32(NO_ERROR);
4753 return NO_ERROR;
4754 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004755 // Is device color managed?
4756 case 1030: {
4757 reply->writeBool(useColorManagement);
4758 return NO_ERROR;
4759 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004760 // Override default composition data space
4761 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4762 // && adb shell stop zygote && adb shell start zygote
4763 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4764 // adb shell stop zygote && adb shell start zygote
4765 case 1031: {
4766 Mutex::Autolock _l(mStateLock);
4767 n = data.readInt32();
4768 if (n) {
4769 n = data.readInt32();
4770 if (n) {
4771 Dataspace dataspace = static_cast<Dataspace>(n);
4772 if (!validateCompositionDataspace(dataspace)) {
4773 return BAD_VALUE;
4774 }
4775 mDefaultCompositionDataspace = dataspace;
4776 }
4777 n = data.readInt32();
4778 if (n) {
4779 Dataspace dataspace = static_cast<Dataspace>(n);
4780 if (!validateCompositionDataspace(dataspace)) {
4781 return BAD_VALUE;
4782 }
4783 mWideColorGamutCompositionDataspace = dataspace;
4784 }
4785 } else {
4786 // restore composition data space.
4787 mDefaultCompositionDataspace = defaultCompositionDataspace;
4788 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4789 }
4790 return NO_ERROR;
4791 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004792 // Set trace flags
4793 case 1033: {
4794 n = data.readUint32();
4795 ALOGD("Updating trace flags to 0x%x", n);
4796 mTracing.setTraceFlags(n);
4797 reply->writeInt32(NO_ERROR);
4798 return NO_ERROR;
4799 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004800 case 1034: {
4801 // TODO(b/129297325): expose this via developer menu option
4802 n = data.readInt32();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004803 if (n && !mRefreshRateOverlay &&
4804 mRefreshRateConfigs->refreshRateSwitchingSupported()) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07004805 RefreshRateType type;
4806 {
4807 std::lock_guard<std::mutex> lock(mActiveConfigLock);
4808 type = mDesiredActiveConfig.type;
4809 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004810 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07004811 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004812 } else if (!n) {
4813 mRefreshRateOverlay.reset();
4814 }
4815 return NO_ERROR;
4816 }
Ady Abraham34392f72019-04-10 11:29:27 -07004817 case 1035: {
4818 n = data.readInt32();
4819 mDebugDisplayConfigSetByBackdoor = false;
4820 if (n >= 0) {
4821 const auto displayToken = getInternalDisplayToken();
4822 status_t result = setAllowedDisplayConfigs(displayToken, {n});
4823 if (result != NO_ERROR) {
4824 return result;
4825 }
4826 mDebugDisplayConfigSetByBackdoor = true;
4827 }
4828 return NO_ERROR;
4829 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004830 }
4831 }
4832 return err;
4833}
4834
Steven Thomas6d8110b2017-08-31 18:24:21 -07004835void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004836 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004837 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004838}
4839
Ana Krulec7d1d6832018-12-27 11:10:09 -08004840void SurfaceFlinger::repaintEverythingForHWC() {
4841 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004842 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004843}
4844
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004845// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4846class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004847public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004848 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4849 ~WindowDisconnector() {
4850 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004851 }
4852
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004853private:
4854 ANativeWindow* mWindow;
4855 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004856};
4857
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004858status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07004859 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
4860 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004861 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07004862 uint32_t reqWidth, uint32_t reqHeight,
4863 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08004864 ISurfaceComposer::Rotation rotation,
4865 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004866 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004867
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004868 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004869
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07004870 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
4871
Chia-I Wu20261cb2018-08-23 12:55:44 -07004872 sp<DisplayDevice> display;
4873 {
4874 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004875
Chia-I Wu20261cb2018-08-23 12:55:44 -07004876 display = getDisplayDeviceLocked(displayToken);
4877 if (!display) return BAD_VALUE;
4878
Chia-I Wucb023152018-08-28 12:57:23 -07004879 // set the requested width/height to the logical display viewport size
4880 // by default
4881 if (reqWidth == 0 || reqHeight == 0) {
4882 reqWidth = uint32_t(display->getViewport().width());
4883 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07004884 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004885 }
4886
Peiyong Lin0e003c92018-09-17 11:09:51 -07004887 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08004888 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004889
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08004890 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4891 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07004892 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07004893 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004894}
4895
chaviw93df2ea2019-04-30 16:45:12 -07004896static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
4897 switch (colorMode) {
4898 case ColorMode::DISPLAY_P3:
4899 case ColorMode::BT2100_PQ:
4900 case ColorMode::BT2100_HLG:
4901 case ColorMode::DISPLAY_BT2020:
4902 return Dataspace::DISPLAY_P3;
4903 default:
4904 return Dataspace::V0_SRGB;
4905 }
4906}
4907
4908const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
4909 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
4910 if (displayToken) {
4911 return getDisplayDeviceLocked(displayToken);
4912 }
4913 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
4914 // may not have a displayId.
4915 for (const auto& [token, display] : mDisplays) {
4916 if (display->getLayerStack() == displayOrLayerStack) {
4917 return display;
4918 }
4919 }
4920 return nullptr;
4921}
4922
4923status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
4924 sp<GraphicBuffer>* outBuffer) {
4925 sp<DisplayDevice> display;
4926 uint32_t width;
4927 uint32_t height;
4928 ui::Transform::orientation_flags captureOrientation;
4929 {
4930 Mutex::Autolock _l(mStateLock);
4931 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
4932 if (!display) {
4933 return BAD_VALUE;
4934 }
4935
4936 width = uint32_t(display->getViewport().width());
4937 height = uint32_t(display->getViewport().height());
4938
4939 captureOrientation = fromSurfaceComposerRotation(
4940 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07004941 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
4942 captureOrientation = ui::Transform::orientation_flags::ROT_270;
4943 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
4944 captureOrientation = ui::Transform::orientation_flags::ROT_90;
4945 }
chaviw93df2ea2019-04-30 16:45:12 -07004946 *outDataspace =
4947 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
4948 }
4949
4950 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
4951 false /* captureSecureLayers */);
4952
4953 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4954 std::placeholders::_1);
4955 bool ignored = false;
4956 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
4957 false /* useIdentityTransform */,
4958 ignored /* outCapturedSecureLayers */);
4959}
4960
Robert Carr866455f2019-04-02 16:28:26 -07004961status_t SurfaceFlinger::captureLayers(
4962 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
4963 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
4964 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
4965 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004966 ATRACE_CALL();
4967
4968 class LayerRenderArea : public RenderArea {
4969 public:
Robert Carr578038f2018-03-09 12:25:24 -08004970 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004971 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
4972 bool childrenOnly)
4973 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08004974 mLayer(layer),
4975 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004976 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08004977 mFlinger(flinger),
4978 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004979 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004980 Rect getBounds() const override {
4981 const Layer::State& layerState(mLayer->getDrawingState());
4982 return mLayer->getBufferSize(layerState);
4983 }
Marissa Wall61c58622018-07-18 10:12:20 -07004984 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004985 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07004986 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08004987 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004988 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08004989 }
chaviwa76b2712017-09-20 12:02:26 -07004990 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004991 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004992 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004993 Rect getSourceCrop() const override {
4994 if (mCrop.isEmpty()) {
4995 return getBounds();
4996 } else {
4997 return mCrop;
4998 }
4999 }
Robert Carr578038f2018-03-09 12:25:24 -08005000 class ReparentForDrawing {
5001 public:
5002 const sp<Layer>& oldParent;
5003 const sp<Layer>& newParent;
5004
Vishnu Nair4351ad52019-02-11 14:13:02 -08005005 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5006 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005007 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005008 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005009 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5010 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005011 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005012 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005013 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005014 };
5015
5016 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005017 const Rect sourceCrop = getSourceCrop();
5018 // no need to check rotation because there is none
5019 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5020 sourceCrop.height() != getReqHeight();
5021
Robert Carr578038f2018-03-09 12:25:24 -08005022 if (!mChildrenOnly) {
5023 mTransform = mLayer->getTransform().inverse();
5024 drawLayers();
5025 } else {
5026 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005027 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5028 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005029 // In the "childrenOnly" case we reparent the children to a screenshot
5030 // layer which has no properties set and which does not draw.
5031 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005032 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5033 "Screenshot Parent"s, w, h, 0,
5034 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005035
Vishnu Nair4351ad52019-02-11 14:13:02 -08005036 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005037 drawLayers();
5038 }
5039 }
chaviwa76b2712017-09-20 12:02:26 -07005040
chaviwa76b2712017-09-20 12:02:26 -07005041 private:
chaviw7206d492017-11-10 16:16:12 -08005042 const sp<Layer> mLayer;
5043 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005044
Peiyong Linefefaac2018-08-17 12:27:51 -07005045 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005046 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005047
5048 SurfaceFlinger* mFlinger;
5049 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005050 };
5051
Robert Carrc0df3122019-04-11 13:18:21 -07005052 int reqWidth = 0;
5053 int reqHeight = 0;
5054 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005055 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005056 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005057
Robert Carrc0df3122019-04-11 13:18:21 -07005058 {
5059 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005060
Robert Carrc0df3122019-04-11 13:18:21 -07005061 parent = fromHandle(layerHandleBinder);
5062 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5063 ALOGE("captureLayers called with an invalid or removed parent");
5064 return NAME_NOT_FOUND;
5065 }
5066
5067 const int uid = IPCThreadState::self()->getCallingUid();
5068 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5069 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5070 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5071 return PERMISSION_DENIED;
5072 }
5073
5074 if (sourceCrop.width() <= 0) {
5075 crop.left = 0;
5076 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5077 }
5078
5079 if (sourceCrop.height() <= 0) {
5080 crop.top = 0;
5081 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5082 }
5083 reqWidth = crop.width() * frameScale;
5084 reqHeight = crop.height() * frameScale;
5085
5086 for (const auto& handle : excludeHandles) {
5087 sp<Layer> excludeLayer = fromHandle(handle);
5088 if (excludeLayer != nullptr) {
5089 excludeLayers.emplace(excludeLayer);
5090 } else {
5091 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5092 return NAME_NOT_FOUND;
5093 }
5094 }
5095 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005096
Chia-I Wu20261cb2018-08-23 12:55:44 -07005097 // really small crop or frameScale
5098 if (reqWidth <= 0) {
5099 reqWidth = 1;
5100 }
5101 if (reqHeight <= 0) {
5102 reqHeight = 1;
5103 }
5104
Robert Carr866455f2019-04-02 16:28:26 -07005105 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5106 auto traverseLayers = [parent, childrenOnly,
5107 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005108 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5109 if (!layer->isVisible()) {
5110 return;
Robert Carr578038f2018-03-09 12:25:24 -08005111 } else if (childrenOnly && layer == parent.get()) {
5112 return;
chaviwa76b2712017-09-20 12:02:26 -07005113 }
Robert Carr866455f2019-04-02 16:28:26 -07005114
5115 sp<Layer> p = layer;
5116 while (p != nullptr) {
5117 if (excludeLayers.count(p) != 0) {
5118 return;
5119 }
5120 p = p->getParent();
5121 }
5122
chaviwa76b2712017-09-20 12:02:26 -07005123 visitor(layer);
5124 });
5125 };
Robert Carr108b2c72019-04-02 16:32:58 -07005126
5127 bool outCapturedSecureLayers = false;
5128 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5129 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005130}
5131
5132status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5133 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005134 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005135 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005136 bool useIdentityTransform,
5137 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005138 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005139
Peiyong Lin0e003c92018-09-17 11:09:51 -07005140 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005141 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5142 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005143 *outBuffer =
5144 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5145 static_cast<android_pixel_format>(reqPixelFormat), 1,
5146 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005147
Robert Carr108b2c72019-04-02 16:32:58 -07005148 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5149 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005150}
5151
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005152status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5153 TraverseLayersFunction traverseLayers,
5154 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005155 bool useIdentityTransform,
5156 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005157 // This mutex protects syncFd and captureResult for communication of the return values from the
5158 // main thread back to this Binder thread
5159 std::mutex captureMutex;
5160 std::condition_variable captureCondition;
5161 std::unique_lock<std::mutex> captureLock(captureMutex);
5162 int syncFd = -1;
5163 std::optional<status_t> captureResult;
5164
Robert Carr03480e22018-01-04 16:02:06 -08005165 const int uid = IPCThreadState::self()->getCallingUid();
5166 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5167
Dominik Laskowski8c001672018-05-30 16:52:06 -07005168 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005169 // If there is a refresh pending, bug out early and tell the binder thread to try again
5170 // after the refresh.
5171 if (mRefreshPending) {
5172 ATRACE_NAME("Skipping screenshot for now");
5173 std::unique_lock<std::mutex> captureLock(captureMutex);
5174 captureResult = std::make_optional<status_t>(EAGAIN);
5175 captureCondition.notify_one();
5176 return;
5177 }
5178
5179 status_t result = NO_ERROR;
5180 int fd = -1;
5181 {
5182 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005183 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005184 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005185 useIdentityTransform, forSystem, &fd,
5186 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005187 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005188 }
5189
5190 {
5191 std::unique_lock<std::mutex> captureLock(captureMutex);
5192 syncFd = fd;
5193 captureResult = std::make_optional<status_t>(result);
5194 captureCondition.notify_one();
5195 }
5196 });
5197
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005198 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005199 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005200 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005201 while (*captureResult == EAGAIN) {
5202 captureResult.reset();
5203 result = postMessageAsync(message);
5204 if (result != NO_ERROR) {
5205 return result;
5206 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005207 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005208 }
5209 result = *captureResult;
5210 }
5211
5212 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005213 sync_wait(syncFd, -1);
5214 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005215 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005216
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005217 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005218}
5219
chaviwa76b2712017-09-20 12:02:26 -07005220void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005221 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005222 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5223 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005224 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005225
chaviwa76b2712017-09-20 12:02:26 -07005226 const auto reqWidth = renderArea.getReqWidth();
5227 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005228 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005229 const auto transform = renderArea.getTransform();
5230 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005231
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005232 renderengine::DisplaySettings clientCompositionDisplay;
5233 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005234
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005235 // assume that bounds are never offset, and that they are the same as the
5236 // buffer bounds.
5237 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005238 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005239 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005240
5241 // Now take into account the rotation flag. We append a transform that
5242 // rotates the layer stack about the origin, then translate by buffer
5243 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005244 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005245 int displacementX = 0;
5246 int displacementY = 0;
5247 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5248 switch (rotation) {
5249 case ui::Transform::ROT_90:
5250 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005251 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005252 break;
5253 case ui::Transform::ROT_180:
5254 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005255 displacementY = renderArea.getBounds().getWidth();
5256 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005257 break;
5258 case ui::Transform::ROT_270:
5259 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005260 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005261 break;
5262 default:
5263 break;
5264 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005265
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005266 // We need to transform the clipping window into the right spot.
5267 // First, rotate the clipping rectangle by the rotation hint to get the
5268 // right orientation
5269 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5270 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5271 const vec4 rotClipTL = rotMatrix * clipTL;
5272 const vec4 rotClipBR = rotMatrix * clipBR;
5273 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5274 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5275 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5276 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5277
5278 // Now reposition the clipping rectangle with the displacement vector
5279 // computed above.
5280 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005281 clientCompositionDisplay.clip =
5282 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5283 newClipRight + displacementX, newClipBottom + displacementY);
5284
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005285 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005286 clientCompositionDisplay.globalTransform =
5287 clipTransform * clientCompositionDisplay.globalTransform;
5288
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005289 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5290 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005291
chaviw50da5042018-04-09 13:49:37 -07005292 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005293
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005294 renderengine::LayerSettings fillLayer;
5295 fillLayer.source.buffer.buffer = nullptr;
5296 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5297 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5298 fillLayer.alpha = half(alpha);
5299 clientCompositionLayers.push_back(fillLayer);
5300
5301 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005302 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005303 const bool supportProtectedContent = false;
5304 Region clip(renderArea.getBounds());
5305 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5306 clip,
5307 useIdentityTransform,
5308 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5309 renderArea.isSecure(),
5310 supportProtectedContent,
5311 clearRegion,
5312 };
5313 auto result = layer->prepareClientComposition(targetSettings);
5314 if (result) {
5315 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005316 }
chaviwa76b2712017-09-20 12:02:26 -07005317 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005318
5319 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005320 // Use an empty fence for the buffer fence, since we just created the buffer so
5321 // there is no need for synchronization with the GPU.
5322 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005323 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005324 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005325 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005326 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005327
5328 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005329}
5330
chaviwa76b2712017-09-20 12:02:26 -07005331status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5332 TraverseLayersFunction traverseLayers,
5333 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005334 bool useIdentityTransform, bool forSystem,
5335 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005336 ATRACE_CALL();
5337
chaviwa76b2712017-09-20 12:02:26 -07005338 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005339 outCapturedSecureLayers =
5340 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005341 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005342
Robert Carr03480e22018-01-04 16:02:06 -08005343 // We allow the system server to take screenshots of secure layers for
5344 // use in situations like the Screen-rotation animation and place
5345 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005346 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005347 ALOGW("FB is protected: PERMISSION_DENIED");
5348 return PERMISSION_DENIED;
5349 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005350 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005351 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005352}
5353
chaviw95ef3c42019-02-14 10:55:09 -08005354void SurfaceFlinger::setInputWindowsFinished() {
5355 Mutex::Autolock _l(mStateLock);
5356
5357 mPendingSyncInputWindows = false;
5358 mTransactionCV.broadcast();
5359}
chaviw5f21a5e2019-02-14 10:00:34 -08005360
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005361// ---------------------------------------------------------------------------
5362
Dan Stoza412903f2017-04-27 13:42:17 -07005363void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5364 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005365}
5366
Dan Stoza412903f2017-04-27 13:42:17 -07005367void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5368 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005369}
5370
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005371void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005372 const LayerVector::Visitor& visitor) {
5373 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005374 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005375 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005376 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005377 continue;
5378 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005379 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005380 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005381 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005382 return;
5383 }
chaviwa76b2712017-09-20 12:02:26 -07005384 if (!layer->isVisible()) {
5385 return;
5386 }
5387 visitor(layer);
5388 });
5389 }
5390}
5391
Dominik Laskowski22488f62019-03-28 09:53:04 -07005392void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5393 const std::vector<int32_t>& allowedConfigs) {
5394 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08005395 return;
5396 }
5397
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005398 const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
5399 allowedConfigs.end());
5400 if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
5401 return;
5402 }
5403
Ady Abraham838de062019-02-04 10:24:03 -08005404 ALOGV("Updating allowed configs");
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005405 mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
5406
5407 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5408 // that listeners that care about a change in allowed configs can get the notification.
5409 // Giving current ActiveConfig so that most other listeners would just drop the event
5410 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5411 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08005412
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005413 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5414 const auto& type = mScheduler->getPreferredRefreshRateType();
5415 const auto& config = mRefreshRateConfigs->getRefreshRateFromType(type);
5416 if (isDisplayConfigAllowed(config.configId)) {
5417 ALOGV("switching to Scheduler preferred config %d", config.configId);
5418 setDesiredActiveConfig({type, config.configId, Scheduler::ConfigEvent::Changed});
5419 } else {
5420 // Set the highest allowed config by iterating backwards on available refresh rates
5421 const auto& refreshRates = mRefreshRateConfigs->getRefreshRateMap();
5422 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
5423 if (isDisplayConfigAllowed(iter->second.configId)) {
5424 ALOGV("switching to allowed config %d", iter->second.configId);
5425 setDesiredActiveConfig(
5426 {iter->first, iter->second.configId, Scheduler::ConfigEvent::Changed});
5427 break;
5428 }
5429 }
5430 }
5431 } else if (!allowedConfigs.empty()) {
5432 ALOGV("switching to config %d", allowedConfigs[0]);
5433 setDesiredActiveConfig(
5434 {RefreshRateType::DEFAULT, allowedConfigs[0], Scheduler::ConfigEvent::Changed});
5435 }
Ady Abraham838de062019-02-04 10:24:03 -08005436}
5437
Dominik Laskowski22488f62019-03-28 09:53:04 -07005438status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005439 const std::vector<int32_t>& allowedConfigs) {
5440 ATRACE_CALL();
5441
Dominik Laskowski22488f62019-03-28 09:53:04 -07005442 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005443 return BAD_VALUE;
5444 }
5445
Ady Abraham34392f72019-04-10 11:29:27 -07005446 if (mDebugDisplayConfigSetByBackdoor) {
5447 // ignore this request as config is overridden by backdoor
5448 return NO_ERROR;
5449 }
5450
Ady Abrahama3129fb2019-10-18 14:17:23 -07005451 postMessageSync(new LambdaMessage([&]() {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005452 const auto display = getDisplayDeviceLocked(displayToken);
5453 if (!display) {
5454 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5455 displayToken.get());
5456 } else if (display->isVirtual()) {
5457 ALOGW("Attempt to set allowed display configs for virtual display");
5458 } else {
Ady Abrahama3129fb2019-10-18 14:17:23 -07005459 Mutex::Autolock lock(mStateLock);
Dominik Laskowski22488f62019-03-28 09:53:04 -07005460 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5461 }
Ady Abraham838de062019-02-04 10:24:03 -08005462 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005463
Ady Abraham838de062019-02-04 10:24:03 -08005464 return NO_ERROR;
5465}
5466
Dominik Laskowski22488f62019-03-28 09:53:04 -07005467status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005468 std::vector<int32_t>* outAllowedConfigs) {
5469 ATRACE_CALL();
5470
Dominik Laskowski22488f62019-03-28 09:53:04 -07005471 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005472 return BAD_VALUE;
5473 }
5474
Dominik Laskowski22488f62019-03-28 09:53:04 -07005475 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005476
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005477 const auto display = getDisplayDeviceLocked(displayToken);
5478 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005479 return NAME_NOT_FOUND;
5480 }
5481
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005482 if (display->isPrimary()) {
5483 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
5484 }
5485
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005486 return NO_ERROR;
5487}
5488
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005489void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005490 mFlinger->setInputWindowsFinished();
5491}
5492
Robert Carrc0df3122019-04-11 13:18:21 -07005493sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5494 BBinder *b = handle->localBinder();
5495 if (b == nullptr) {
5496 return nullptr;
5497 }
5498 auto it = mLayersByLocalBinderToken.find(b);
5499 if (it != mLayersByLocalBinderToken.end()) {
5500 return it->second.promote();
5501 }
5502 return nullptr;
5503}
5504
Dominik Laskowski75848362019-11-11 17:57:20 -08005505void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005506 mNumLayers++;
5507 mScheduler->registerLayer(layer);
5508}
5509
5510void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5511 mNumLayers--;
5512 mOffscreenLayers.erase(layer);
5513}
5514
Alec Mouri4545a8a2019-08-08 20:05:32 -07005515void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5516 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5517}
5518
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005519} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005520
Mathias Agopian3f844832013-08-07 21:24:32 -07005521#if defined(__gl_h_)
5522#error "don't include gl/gl.h in this file"
5523#endif
5524
5525#if defined(__gl2_h_)
5526#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005527#endif