blob: 0e33f10ab6f120e2578eaaa6a49e76aa174eb29b [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
Ana Krulece5a06e02019-03-06 17:09:03 -0800359 mUseSmart90ForVideo = use_smart_90_for_video(false);
Ana Krulecba13ab32019-02-20 14:14:12 -0800360 property_get("debug.sf.use_smart_90_for_video", value, "0");
Ana Krulece5a06e02019-03-06 17:09:03 -0800361
362 int int_value = atoi(value);
363 if (int_value) {
364 mUseSmart90ForVideo = true;
365 }
Ana Krulecba13ab32019-02-20 14:14:12 -0800366
Dan Stozaec460082018-12-17 15:35:09 -0800367 property_get("debug.sf.luma_sampling", value, "1");
368 mLumaSampling = atoi(value);
369
Romain Guy11d63f42017-07-20 12:47:14 -0700370 // We should be reading 'persist.sys.sf.color_saturation' here
371 // but since /data may be encrypted, we need to wait until after vold
372 // comes online to attempt to read the property. The property is
373 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800374
375 if (useTrebleTestingOverride()) {
376 // Without the override SurfaceFlinger cannot connect to HIDL
377 // services that are not listed in the manifests. Considered
378 // deriving the setting from the set service name, but it
379 // would be brittle if the name that's not 'default' is used
380 // for production purposes later on.
381 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
382 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800383}
384
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800385void SurfaceFlinger::onFirstRef()
386{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800387 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800388}
389
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700390SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800391
Dan Stozac7014012014-02-14 15:03:43 -0800392void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800393{
394 // the window manager died on us. prepare its eulogy.
395
Andy McFadden13a082e2012-08-24 10:16:42 -0700396 // restore initial conditions (default device unblank, etc)
397 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800398
399 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700400 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800401}
402
Robert Carr1db73f62016-12-21 12:58:51 -0800403static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700404 status_t err = client->initCheck();
405 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800406 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800407 }
Robert Carr1db73f62016-12-21 12:58:51 -0800408 return nullptr;
409}
410
411sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
412 return initClient(new Client(this));
413}
414
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700415sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
416 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700417{
418 class DisplayToken : public BBinder {
419 sp<SurfaceFlinger> flinger;
420 virtual ~DisplayToken() {
421 // no more references, this display must be terminated
422 Mutex::Autolock _l(flinger->mStateLock);
423 flinger->mCurrentState.displays.removeItem(this);
424 flinger->setTransactionFlags(eDisplayTransactionNeeded);
425 }
426 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700427 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700428 : flinger(flinger) {
429 }
430 };
431
432 sp<BBinder> token = new DisplayToken(this);
433
434 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700435 // Display ID is assigned when virtual display is allocated by HWC.
436 DisplayDeviceState state;
437 state.isSecure = secure;
438 state.displayName = displayName;
439 mCurrentState.displays.add(token, state);
440 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700441 return token;
442}
443
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700444void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700445 Mutex::Autolock _l(mStateLock);
446
Dominik Laskowski075d3172018-05-24 15:50:06 -0700447 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
448 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700449 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700450 return;
451 }
452
Dominik Laskowski075d3172018-05-24 15:50:06 -0700453 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
454 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700455 ALOGE("destroyDisplay called for non-virtual display");
456 return;
457 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700458 mInterceptor->saveDisplayDeletion(state.sequenceId);
459 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700460 setTransactionFlags(eDisplayTransactionNeeded);
461}
462
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800463std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
464 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700465
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800466 const auto internalDisplayId = getInternalDisplayIdLocked();
467 if (!internalDisplayId) {
468 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700469 }
470
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800471 std::vector<PhysicalDisplayId> displayIds;
472 displayIds.reserve(mPhysicalDisplayTokens.size());
473 displayIds.push_back(internalDisplayId->value);
474
475 for (const auto& [id, token] : mPhysicalDisplayTokens) {
476 if (id != *internalDisplayId) {
477 displayIds.push_back(id.value);
478 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700479 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700480
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800481 return displayIds;
482}
483
484sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
485 Mutex::Autolock lock(mStateLock);
486 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700487}
488
Ady Abraham37965d42018-11-01 13:43:32 -0700489status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
490 if (!outGetColorManagement) {
491 return BAD_VALUE;
492 }
493 *outGetColorManagement = useColorManagement;
494 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700495}
496
Lloyd Pique441d5042018-10-18 16:49:51 -0700497HWComposer& SurfaceFlinger::getHwComposer() const {
498 return mCompositionEngine->getHwComposer();
499}
500
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700501renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
502 return mCompositionEngine->getRenderEngine();
503}
504
Lloyd Pique70d91362018-10-18 16:02:55 -0700505compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
506 return *mCompositionEngine.get();
507}
508
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800509void SurfaceFlinger::bootFinished()
510{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700511 if (mStartPropertySetThread->join() != NO_ERROR) {
512 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800513 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800514 const nsecs_t now = systemTime();
515 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000516 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700517
Mikael Pessa90092f42019-08-26 17:22:04 -0700518 mFrameTracer->initialize();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700519
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700520 // wait patiently for the window manager death
521 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700522 mWindowManager = defaultServiceManager()->getService(name);
523 if (mWindowManager != 0) {
524 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700525 }
Robert Carr720e5062018-07-30 17:45:14 -0700526 sp<IBinder> input(defaultServiceManager()->getService(
527 String16("inputflinger")));
528 if (input == nullptr) {
529 ALOGE("Failed to link to input service");
530 } else {
531 mInputFlinger = interface_cast<IInputFlinger>(input);
532 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700533
Steven Thomas050b2c82017-03-06 11:45:16 -0800534 if (mVrFlinger) {
535 mVrFlinger->OnBootFinished();
536 }
537
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700538 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700539 // formerly we would just kill the process, but we now ask it to exit so it
540 // can choose where to stop the animation.
541 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700542
543 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
544 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
545 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700546
Ana Krulecbd6654b2019-02-15 15:18:15 -0800547 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800548 readPersistentProperties();
549 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800550
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700551 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
552 // set the refresh rate according to the policy
553 const auto& performanceRefreshRate =
554 mRefreshRateConfigs->getRefreshRateFromType(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800555
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700556 if (isDisplayConfigAllowed(performanceRefreshRate.configId)) {
557 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
558 } else {
559 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
560 }
Ana Krulecbd6654b2019-02-15 15:18:15 -0800561 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800562 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800563}
564
Dan Stoza436ccf32018-06-21 12:10:12 -0700565uint32_t SurfaceFlinger::getNewTexture() {
566 {
567 std::lock_guard lock(mTexturePoolMutex);
568 if (!mTexturePool.empty()) {
569 uint32_t name = mTexturePool.back();
570 mTexturePool.pop_back();
571 ATRACE_INT("TexturePoolSize", mTexturePool.size());
572 return name;
573 }
574
575 // The pool was too small, so increase it for the future
576 ++mTexturePoolSize;
577 }
578
579 // The pool was empty, so we need to get a new texture name directly using a
580 // blocking call to the main thread
581 uint32_t name = 0;
582 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
583 return name;
584}
585
Mathias Agopian3f844832013-08-07 21:24:32 -0700586void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700587 std::lock_guard lock(mTexturePoolMutex);
588 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
589 // to actually delete this or not based on mTexturePoolSize
590 mTexturePool.push_back(texture);
591 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700592}
593
Wei Wangf9b05ee2017-07-19 20:59:39 -0700594// Do not call property_set on main thread which will be blocked by init
595// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700596void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700597 ALOGI( "SurfaceFlinger's main thread ready to run. "
598 "Initializing graphics H/W...");
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700599 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900600
Steven Thomasb02664d2017-07-26 18:48:28 -0700601 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800602
Steven Thomasb02664d2017-07-26 18:48:28 -0700603 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin13effd12018-07-24 17:01:47 -0700604 int32_t renderEngineFeature = 0;
Peiyong Lin833074a2018-08-28 11:53:54 -0700605 renderEngineFeature |= (useColorManagement ?
606 renderengine::RenderEngine::USE_COLOR_MANAGEMENT : 0);
Peiyong Linb3839ad2018-09-05 15:37:19 -0700607 renderEngineFeature |= (useContextPriority ?
608 renderengine::RenderEngine::USE_HIGH_PRIORITY_CONTEXT : 0);
Peiyong Lin6a043d52019-04-01 17:18:21 -0700609 renderEngineFeature |=
610 (enable_protected_contents(false) ? renderengine::RenderEngine::ENABLE_PROTECTED_CONTEXT
611 : 0);
Peiyong Lin0256f722018-08-31 15:45:10 -0700612
613 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800614 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700615 mCompositionEngine->setRenderEngine(
Peiyong Linc6780972018-10-28 15:24:08 -0700616 renderengine::RenderEngine::create(static_cast<int32_t>(defaultCompositionPixelFormat),
Alec Mourida4cf3b2019-02-12 15:33:01 -0800617 renderEngineFeature, maxFrameBufferAcquiredBuffers));
Steven Thomasb02664d2017-07-26 18:48:28 -0700618
619 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
620 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700621 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
622 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800623 // Process any initial hotplug and resulting display changes.
624 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700625 const auto display = getDefaultDisplayDeviceLocked();
626 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700627 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700628 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800629
Steven Thomas050b2c82017-03-06 11:45:16 -0800630 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700631 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700632 // This callback is called from the vr flinger dispatch thread. We
633 // need to call signalTransaction(), which requires holding
634 // mStateLock when we're not on the main thread. Acquiring
635 // mStateLock from the vr flinger dispatch thread might trigger a
636 // deadlock in surface flinger (see b/66916578), so post a message
637 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700638 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700639 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
640 mVrFlingerRequestsDisplay = requestDisplay;
641 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700642 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800643 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700644 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
645 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700646 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700647 .value_or(0),
648 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800649 if (!mVrFlinger) {
650 ALOGE("Failed to start vrflinger");
651 }
652 }
653
Mathias Agopian92a979a2012-08-02 18:32:23 -0700654 // initialize our drawing state
655 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700656
Andy McFadden13a082e2012-08-24 10:16:42 -0700657 // set initial conditions (e.g. unblank default device)
658 initializeDisplays();
659
Steven Thomas137d4bc2019-07-25 16:55:14 -0700660 char primeShaderCache[PROPERTY_VALUE_MAX];
661 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
662 if (atoi(primeShaderCache)) {
663 getRenderEngine().primeCache();
664 }
Dan Stoza4e637772016-07-28 13:31:51 -0700665
Wei Wangf9b05ee2017-07-19 20:59:39 -0700666 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700667
668 const bool presentFenceReliable =
669 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
670 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700671
672 if (mStartPropertySetThread->Start() != NO_ERROR) {
673 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800674 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800675
Dan Stoza9e56aa02015-11-02 13:00:03 -0800676 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700677}
678
Romain Guy11d63f42017-07-20 12:47:14 -0700679void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700680 Mutex::Autolock _l(mStateLock);
681
Romain Guy11d63f42017-07-20 12:47:14 -0700682 char value[PROPERTY_VALUE_MAX];
683
684 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800685 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700686 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800687 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100688
689 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700690 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800691
692 property_get("persist.sys.sf.color_mode", value, "0");
693 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700694}
695
Mathias Agopiana67e4182012-06-19 17:26:12 -0700696void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800697 // Start boot animation service by setting a property mailbox
698 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700699 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800700 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700701 if (mStartPropertySetThread->join() != NO_ERROR) {
702 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800703 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700704}
705
Mathias Agopian875d8e12013-06-07 15:35:48 -0700706size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700707 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700708}
709
Mathias Agopian875d8e12013-06-07 15:35:48 -0700710size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700711 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700712}
713
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800714// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800715
Jamie Gennis582270d2011-08-17 18:19:00 -0700716bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800717 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800718 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800719 return authenticateSurfaceTextureLocked(bufferProducer);
720}
721
722bool SurfaceFlinger::authenticateSurfaceTextureLocked(
723 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800724 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800725 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800726}
727
Brian Anderson6b376712017-04-04 10:51:39 -0700728status_t SurfaceFlinger::getSupportedFrameTimestamps(
729 std::vector<FrameEvent>* outSupported) const {
730 *outSupported = {
731 FrameEvent::REQUESTED_PRESENT,
732 FrameEvent::ACQUIRE,
733 FrameEvent::LATCH,
734 FrameEvent::FIRST_REFRESH_START,
735 FrameEvent::LAST_REFRESH_START,
736 FrameEvent::GPU_COMPOSITION_DONE,
737 FrameEvent::DEQUEUE_READY,
738 FrameEvent::RELEASE,
739 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700740 ConditionalLock _l(mStateLock,
741 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700742 if (!getHwComposer().hasCapability(
743 HWC2::Capability::PresentFenceIsNotReliable)) {
744 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
745 }
746 return NO_ERROR;
747}
748
Dominik Laskowski22488f62019-03-28 09:53:04 -0700749status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
750 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700751 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700752 return BAD_VALUE;
753 }
754
Dominik Laskowski22488f62019-03-28 09:53:04 -0700755 Mutex::Autolock lock(mStateLock);
756
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800757 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700758 if (!displayId) {
759 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700760 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700761
Mathias Agopian8b736f12012-08-13 17:54:26 -0700762 // TODO: Not sure if display density should handled by SF any longer
763 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700764 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700765 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700766 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800767 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700768 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700769 }
770 return density;
771 }
772 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700773 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700774 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700775 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700776 return getDensityFromProperty("ro.sf.lcd_density"); }
777 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700778
Dan Stoza7f7da322014-05-02 15:26:25 -0700779 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700780
Dominik Laskowski075d3172018-05-24 15:50:06 -0700781 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700782 DisplayInfo info = DisplayInfo();
783
Dan Stoza9e56aa02015-11-02 13:00:03 -0800784 float xdpi = hwConfig->getDpiX();
785 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700786
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700787 info.w = hwConfig->getWidth();
788 info.h = hwConfig->getHeight();
789 // Default display viewport to display width and height
790 info.viewportW = info.w;
791 info.viewportH = info.h;
792
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800793 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700794 // The density of the device is provided by a build property
795 float density = Density::getBuildDensity() / 160.0f;
796 if (density == 0) {
797 // the build doesn't provide a density -- this is wrong!
798 // use xdpi instead
799 ALOGE("ro.sf.lcd_density must be defined as a build property");
800 density = xdpi / 160.0f;
801 }
802 if (Density::getEmuDensity()) {
803 // if "qemu.sf.lcd_density" is specified, it overrides everything
804 xdpi = ydpi = density = Density::getEmuDensity();
805 density /= 160.0f;
806 }
807 info.density = density;
808
809 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700810 const auto display = getDefaultDisplayDeviceLocked();
811 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700812
813 // This is for screenrecord
814 const Rect viewport = display->getViewport();
815 if (viewport.isValid()) {
816 info.viewportW = uint32_t(viewport.getWidth());
817 info.viewportH = uint32_t(viewport.getHeight());
818 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700819 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700820 } else {
821 // TODO: where should this value come from?
822 static const int TV_DENSITY = 213;
823 info.density = TV_DENSITY / 160.0f;
824 info.orientation = 0;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700825
826 const auto display = getDisplayDeviceLocked(displayToken);
827 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700828 }
829
Dan Stoza7f7da322014-05-02 15:26:25 -0700830 info.xdpi = xdpi;
831 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800832 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700833 const auto refreshRateType =
834 mRefreshRateConfigs->getRefreshRateTypeFromHwcConfigId(hwConfig->getId());
Ady Abraham796beb02019-04-11 15:23:07 -0700835 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
836 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800837
Andy McFadden91b2ca82014-06-13 14:04:23 -0700838 // This is how far in advance a buffer must be queued for
839 // presentation at a given time. If you want a buffer to appear
840 // on the screen at time N, you must submit the buffer before
841 // (N - presentationDeadline).
842 //
843 // Normally it's one full refresh period (to give SF a chance to
844 // latch the buffer), but this can be reduced by configuring a
845 // DispSync offset. Any additional delays introduced by the hardware
846 // composer or panel must be accounted for here.
847 //
848 // We add an additional 1ms to allow for processing time and
849 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700850 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700851
852 // All non-virtual displays are currently considered secure.
853 info.secure = true;
854
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800855 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700856 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800857 std::swap(info.w, info.h);
858 }
859
Michael Wright28f24d02016-07-12 13:30:53 -0700860 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700861 }
862
Dan Stoza7f7da322014-05-02 15:26:25 -0700863 return NO_ERROR;
864}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700865
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700866status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
867 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700868 return BAD_VALUE;
869 }
870
Ana Krulecc2870422019-01-29 19:00:58 -0800871 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700872 return NO_ERROR;
873}
874
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700875int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
876 const auto display = getDisplayDevice(displayToken);
877 if (!display) {
878 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800879 return BAD_VALUE;
880 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700881
Steven Thomasc9098452019-09-30 17:15:05 -0700882 if (display->isPrimary()) {
883 std::lock_guard<std::mutex> lock(mActiveConfigLock);
884 if (mDesiredActiveConfigChanged) {
885 return mDesiredActiveConfig.configId;
886 } else {
887 return display->getActiveConfig();
888 }
889 } else {
890 return display->getActiveConfig();
891 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700892}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700893
Ady Abraham03b02dd2019-03-21 15:40:11 -0700894void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800895 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800896
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800897 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800898 // config twice. However event generation config might have changed so we need to update it
899 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800900 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700901 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
902 mDesiredActiveConfig = info;
903 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800904
905 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800906 // This will trigger HWC refresh without resetting the idle timer.
907 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700908 // Start receiving vsync samples now, so that we can detect a period
909 // switch.
910 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700911 // As we called to set period, we will call to onRefreshRateChangeCompleted once
912 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700913 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700914 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700915 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800916 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800917 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700918
919 if (mRefreshRateOverlay) {
920 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
921 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800922}
923
924status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
925 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800926
927 std::vector<int32_t> allowedConfig;
928 allowedConfig.push_back(mode);
929
930 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800931}
932
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800933void SurfaceFlinger::setActiveConfigInternal() {
934 ATRACE_CALL();
935
Dominik Laskowski22488f62019-03-28 09:53:04 -0700936 const auto display = getDefaultDisplayDeviceLocked();
937 if (!display) {
938 return;
939 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800940
Dominik Laskowski22488f62019-03-28 09:53:04 -0700941 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700942 mRefreshRateConfigs->setCurrentConfig(mUpcomingActiveConfig.configId);
943 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700944
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800945 display->setActiveConfig(mUpcomingActiveConfig.configId);
946
Alec Mouri754c98a2019-03-18 18:53:42 -0700947 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700948 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800949 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700950
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800951 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800952 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
953 mUpcomingActiveConfig.configId);
954 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800955}
956
Ady Abraham53852a52019-05-28 18:07:44 -0700957void SurfaceFlinger::desiredActiveConfigChangeDone() {
958 std::lock_guard<std::mutex> lock(mActiveConfigLock);
959 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
960 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700961
962 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
963 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700964 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700965}
966
Dominik Laskowski22488f62019-03-28 09:53:04 -0700967bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800968 ATRACE_CALL();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800969 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700970 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800971 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700972 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800973 return true;
974 }
975
976 // We received the present fence from the HWC, so we assume it successfully updated
977 // the config, hence we update SF.
978 mCheckPendingFence = false;
979 setActiveConfigInternal();
980 }
981
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800982 // Store the local variable to release the lock.
983 ActiveConfigInfo desiredActiveConfig;
984 {
985 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800986 if (!mDesiredActiveConfigChanged) {
987 return false;
988 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800989 desiredActiveConfig = mDesiredActiveConfig;
990 }
991
Dominik Laskowski22488f62019-03-28 09:53:04 -0700992 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800993 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
994 // display is not valid or we are already in the requested mode
995 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -0700996 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800997 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800998 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800999
Ady Abraham838de062019-02-04 10:24:03 -08001000 // Desired active config was set, it is different than the config currently in use, however
1001 // allowed configs might have change by the time we process the refresh.
1002 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001003 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001004 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001005 return false;
1006 }
Alec Mouri7f015182019-07-11 13:56:22 -07001007
Ady Abrahamb838aed2019-02-12 15:30:16 -08001008 mUpcomingActiveConfig = desiredActiveConfig;
1009 const auto displayId = display->getId();
1010 LOG_ALWAYS_FATAL_IF(!displayId);
1011
1012 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1013 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1014
1015 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001016 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001017 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001018 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001019}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001020
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001021status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1022 Vector<ColorMode>* outColorModes) {
1023 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001024 return BAD_VALUE;
1025 }
1026
Peiyong Lina52f0292018-03-14 17:26:31 -07001027 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001028 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001029 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001030 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1031
1032 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1033 if (!displayId) {
1034 return NAME_NOT_FOUND;
1035 }
1036
Dominik Laskowski075d3172018-05-24 15:50:06 -07001037 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001038 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001039 }
Michael Wright28f24d02016-07-12 13:30:53 -07001040 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001041
1042 // If it's built-in display and the configuration claims it's not wide color capable,
1043 // filter out all wide color modes. The typical reason why this happens is that the
1044 // hardware is not good enough to support GPU composition of wide color, and thus the
1045 // OEMs choose to disable this capability.
1046 if (isInternalDisplay && !hasWideColorDisplay) {
1047 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1048 isWideColorMode);
1049 } else {
1050 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1051 }
Michael Wright28f24d02016-07-12 13:30:53 -07001052
1053 return NO_ERROR;
1054}
1055
Daniel Solomon42d04562019-01-20 21:03:19 -08001056status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1057 ui::DisplayPrimaries &primaries) {
1058 if (!displayToken) {
1059 return BAD_VALUE;
1060 }
1061
1062 // Currently we only support this API for a single internal display.
1063 if (getInternalDisplayToken() != displayToken) {
1064 return BAD_VALUE;
1065 }
1066
1067 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1068 return NO_ERROR;
1069}
1070
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001071ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1072 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001073 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001074 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001075 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001076}
1077
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001078status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001079 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080 Vector<ColorMode> modes;
1081 getDisplayColorModes(displayToken, &modes);
1082 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1083 if (mode < ColorMode::NATIVE || !exists) {
1084 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1085 decodeColorMode(mode).c_str(), mode, displayToken.get());
1086 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001087 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001088 const auto display = getDisplayDevice(displayToken);
1089 if (!display) {
1090 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1091 decodeColorMode(mode).c_str(), mode, displayToken.get());
1092 } else if (display->isVirtual()) {
1093 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1094 decodeColorMode(mode).c_str(), mode);
1095 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001096 display->getCompositionDisplay()->setColorProfile(
1097 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1098 RenderIntent::COLORIMETRIC,
1099 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001100 }
1101 }));
1102
Michael Wright28f24d02016-07-12 13:30:53 -07001103 return NO_ERROR;
1104}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001105
Svetoslavd85084b2014-03-20 10:28:31 -07001106status_t SurfaceFlinger::clearAnimationFrameStats() {
1107 Mutex::Autolock _l(mStateLock);
1108 mAnimFrameTracker.clearStats();
1109 return NO_ERROR;
1110}
1111
1112status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1113 Mutex::Autolock _l(mStateLock);
1114 mAnimFrameTracker.getStats(outStats);
1115 return NO_ERROR;
1116}
1117
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001118status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1119 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001120 Mutex::Autolock _l(mStateLock);
1121
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001122 const auto display = getDisplayDeviceLocked(displayToken);
1123 if (!display) {
1124 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001125 return BAD_VALUE;
1126 }
1127
Peiyong Linfb069302018-04-25 14:34:31 -07001128 // At this point the DisplayDeivce should already be set up,
1129 // meaning the luminance information is already queried from
1130 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001131 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001132 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1133 capabilities.getDesiredMaxLuminance(),
1134 capabilities.getDesiredMaxAverageLuminance(),
1135 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001136
1137 return NO_ERROR;
1138}
1139
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001140status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1141 ui::PixelFormat* outFormat,
1142 ui::Dataspace* outDataspace,
1143 uint8_t* outComponentMask) const {
1144 if (!outFormat || !outDataspace || !outComponentMask) {
1145 return BAD_VALUE;
1146 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001147 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001148 if (!display || !display->getId()) {
1149 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1150 return BAD_VALUE;
1151 }
1152 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1153 outDataspace, outComponentMask);
1154}
1155
Kevin DuBois74e53772018-11-19 10:52:38 -08001156status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1157 bool enable, uint8_t componentMask,
1158 uint64_t maxFrames) const {
1159 const auto display = getDisplayDevice(displayToken);
1160 if (!display || !display->getId()) {
1161 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1162 return BAD_VALUE;
1163 }
1164
1165 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1166 componentMask, maxFrames);
1167}
1168
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001169status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1170 uint64_t maxFrames, uint64_t timestamp,
1171 DisplayedFrameStats* outStats) const {
1172 const auto display = getDisplayDevice(displayToken);
1173 if (!display || !display->getId()) {
1174 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1175 return BAD_VALUE;
1176 }
1177
1178 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1179 outStats);
1180}
1181
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001182status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1183 if (!outSupported) {
1184 return BAD_VALUE;
1185 }
1186 *outSupported = getRenderEngine().supportsProtectedContent();
1187 return NO_ERROR;
1188}
1189
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001190status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1191 bool* outIsWideColorDisplay) const {
1192 if (!displayToken || !outIsWideColorDisplay) {
1193 return BAD_VALUE;
1194 }
1195 Mutex::Autolock _l(mStateLock);
1196 const auto display = getDisplayDeviceLocked(displayToken);
1197 if (!display) {
1198 return BAD_VALUE;
1199 }
Peiyong Linff84a152019-05-17 18:36:19 -07001200
1201 // Use hasWideColorDisplay to override built-in display.
1202 const auto displayId = display->getId();
1203 if (displayId && displayId == getInternalDisplayIdLocked()) {
1204 *outIsWideColorDisplay = hasWideColorDisplay;
1205 return NO_ERROR;
1206 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001207 *outIsWideColorDisplay = display->hasWideColorGamut();
1208 return NO_ERROR;
1209}
1210
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001211status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001212 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001213 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001214
Dominik Laskowski6505f792019-09-18 11:10:05 -07001215 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1216 mEventQueue->setEventConnection(
1217 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001218 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001219 }));
1220
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001221 return NO_ERROR;
1222}
1223
1224status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001225 Mutex::Autolock lock(mStateLock);
1226 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001227}
1228
Lloyd Pique755e3192018-01-31 16:46:15 -08001229status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1230 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001231 // Try to acquire a lock for 1s, fail gracefully
1232 const status_t err = mStateLock.timedLock(s2ns(1));
1233 const bool locked = (err == NO_ERROR);
1234 if (!locked) {
1235 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1236 return TIMED_OUT;
1237 }
1238
1239 outLayers->clear();
1240 mCurrentState.traverseInZOrder([&](Layer* layer) {
1241 outLayers->push_back(layer->getLayerDebugInfo());
1242 });
1243
1244 mStateLock.unlock();
1245 return NO_ERROR;
1246}
1247
Peiyong Linc6780972018-10-28 15:24:08 -07001248status_t SurfaceFlinger::getCompositionPreference(
1249 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1250 Dataspace* outWideColorGamutDataspace,
1251 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001252 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001253 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001254 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001255 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001256 return NO_ERROR;
1257}
1258
Dan Stozaec460082018-12-17 15:35:09 -08001259status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1260 const sp<IBinder>& stopLayerHandle,
1261 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001262 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001263 return BAD_VALUE;
1264 }
1265 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001266 return NO_ERROR;
1267}
1268
Dan Stozaec460082018-12-17 15:35:09 -08001269status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001270 if (!listener) {
1271 return BAD_VALUE;
1272 }
Dan Stozaec460082018-12-17 15:35:09 -08001273 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001274 return NO_ERROR;
1275}
Dan Gittik57e63c52019-01-18 16:37:54 +00001276
1277status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1278 bool* outSupport) const {
1279 if (!displayToken || !outSupport) {
1280 return BAD_VALUE;
1281 }
1282 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1283 if (!displayId) {
1284 return NAME_NOT_FOUND;
1285 }
1286 *outSupport =
1287 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1288 return NO_ERROR;
1289}
1290
1291status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1292 float brightness) const {
1293 if (!displayToken) {
1294 return BAD_VALUE;
1295 }
1296 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1297 if (!displayId) {
1298 return NAME_NOT_FOUND;
1299 }
1300 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1301}
1302
Ady Abraham8532d012019-05-08 14:50:56 -07001303status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1304 PowerHint powerHint = static_cast<PowerHint>(hintId);
1305
1306 if (powerHint == PowerHint::INTERACTION) {
1307 mScheduler->notifyTouchEvent();
1308 }
1309
1310 return NO_ERROR;
1311}
1312
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001313// ----------------------------------------------------------------------------
1314
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001315sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001316 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001317 const auto& handle =
1318 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001319
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001320 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001321}
1322
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001323// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001324
1325void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001326 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001327}
1328
1329void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001330 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001331 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001332}
1333
1334void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001335 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001336 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001337}
1338
1339void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001340 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001341 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001342}
1343
1344status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001345 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001346 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001347}
1348
1349status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001350 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001351 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001352 if (res == NO_ERROR) {
1353 msg->wait();
1354 }
1355 return res;
1356}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001357
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001358void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001359 do {
1360 waitForEvent();
1361 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001362}
1363
Dominik Laskowski83b88212018-12-11 13:34:06 -08001364nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001365 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001366 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1367 return 0;
1368 }
1369
1370 const auto config = getHwComposer().getActiveConfig(*displayId);
1371 return config ? config->getVsyncPeriod() : 0;
1372}
1373
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001374void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1375 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001376 ATRACE_NAME("SF onVsync");
1377
Steven Thomas3cfac282017-02-06 12:29:30 -08001378 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001379 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001380 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001381 return;
1382 }
1383
Dominik Laskowski075d3172018-05-24 15:50:06 -07001384 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001385 return;
1386 }
1387
Dominik Laskowski075d3172018-05-24 15:50:06 -07001388 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001389 // For now, we don't do anything with external display vsyncs.
1390 return;
1391 }
1392
Alec Mourif8e689c2019-05-20 18:32:22 -07001393 bool periodFlushed = false;
1394 mScheduler->addResyncSample(timestamp, &periodFlushed);
1395 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001396 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001397 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001398}
1399
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001400void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001401 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1402 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001403}
1404
Ady Abraham261614e2019-07-10 17:53:12 -07001405bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001406 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001407}
1408
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001409void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001410 const auto display = getDefaultDisplayDeviceLocked();
1411 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001412 return;
1413 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001414 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001415
Ana Krulec7d1d6832018-12-27 11:10:09 -08001416 // Don't do any updating if the current fps is the same as the new one.
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001417 const auto& refreshRateConfig = mRefreshRateConfigs->getRefreshRateFromType(refreshRate);
1418 const int desiredConfigId = refreshRateConfig.configId;
Alec Mouri0a1cc962019-03-14 12:33:02 -07001419
Dominik Laskowski22488f62019-03-28 09:53:04 -07001420 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001421 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1422 return;
1423 }
1424
Dominik Laskowski22488f62019-03-28 09:53:04 -07001425 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001426}
1427
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001428void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001429 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001430 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001431 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001432
Lloyd Piqueba04e622017-12-14 17:11:26 -08001433 // Ignore events that do not have the right sequenceId.
1434 if (sequenceId != getBE().mComposerSequenceId) {
1435 return;
1436 }
1437
Steven Thomasb02664d2017-07-26 18:48:28 -07001438 // Only lock if we're not on the main thread. This function is normally
1439 // called on a hwbinder thread, but for the primary display it's called on
1440 // the main thread with the state lock already held, so don't attempt to
1441 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001442 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001443
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001444 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001445
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001446 if (std::this_thread::get_id() == mMainThreadId) {
1447 // Process all pending hot plug events immediately if we are on the main thread.
1448 processDisplayHotplugEventsLocked();
1449 }
1450
Lloyd Piqueba04e622017-12-14 17:11:26 -08001451 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001452}
1453
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001454void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001455 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001456 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001457 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001458 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001459 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001460}
1461
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001462void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001463 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001464
1465 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1466 // display power state.
1467 postMessageAsync(new LambdaMessage(
1468 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1469}
1470
1471void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1472 ATRACE_CALL();
1473
Ady Abraham27c70212019-06-11 10:52:26 -07001474 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1475
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001476 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001477 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1478 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001479 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001480 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001481 }
Mathias Agopian86303202012-07-24 22:46:10 -07001482}
1483
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001484// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001485void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001486 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001487 // Clear the drawing state so that the logic inside of
1488 // handleTransactionLocked will fire. It will determine the delta between
1489 // mCurrentState and mDrawingState and re-apply all changes when we make the
1490 // transition.
1491 mDrawingState.displays.clear();
1492 mDisplays.clear();
1493}
1494
Steven Thomas050b2c82017-03-06 11:45:16 -08001495void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001496 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001497 if (!mVrFlinger)
1498 return;
1499 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001500 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001501 return;
1502 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001503
Lloyd Pique441d5042018-10-18 16:49:51 -07001504 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001505 ALOGE("Vr flinger is only supported for remote hardware composer"
1506 " service connections. Ignoring request to transition to vr"
1507 " flinger.");
1508 mVrFlingerRequestsDisplay = false;
1509 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001510 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001511
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001512 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001513
Steven Thomas0123ac62018-07-12 11:32:34 -07001514 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001515 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001516
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001517 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001518
1519 // Clear out all the output layers from the composition engine for all
1520 // displays before destroying the hardware composer interface. This ensures
1521 // any HWC layers are destroyed through that interface before it becomes
1522 // invalid.
1523 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001524 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001525 }
1526
Steven Thomas0123ac62018-07-12 11:32:34 -07001527 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1528 // called below. Clear the reference now so we don't accidentally use it
1529 // later.
1530 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001531
Steven Thomasb02664d2017-07-26 18:48:28 -07001532 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001533 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001534 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001535
Steven Thomasb02664d2017-07-26 18:48:28 -07001536 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001537 // Delete the current instance before creating the new one
1538 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1539 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1540 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1541 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001542
Lloyd Pique441d5042018-10-18 16:49:51 -07001543 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001544 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001545
1546 if (vrFlingerRequestsDisplay) {
1547 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001548 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001549
1550 mVisibleRegionsDirty = true;
1551 invalidateHwcGeometry();
1552
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001553 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001554 display = getDefaultDisplayDeviceLocked();
1555 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001556 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001557
Steven Thomasb02664d2017-07-26 18:48:28 -07001558 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001559 const nsecs_t vsyncPeriod = getVsyncPeriod();
1560 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001561
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001562 // The present fences returned from vr_hwc are not an accurate
1563 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001564 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001565
Steven Thomasb02664d2017-07-26 18:48:28 -07001566 // Use phase of 0 since phase is not known.
1567 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001568 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001569 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001570
Ana Krulecc2870422019-01-29 19:00:58 -08001571 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001572
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001573 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001574 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001575}
1576
Ady Abraham11579302019-09-19 12:35:58 -07001577bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1578 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001579 // We are storing the last 2 present fences. If sf's phase offset is to be
1580 // woken up before the actual vsync but targeting the next vsync, we need to check
1581 // fence N-2
1582 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001583 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001584 ? mPreviousPresentFences[0]
1585 : mPreviousPresentFences[1];
1586
Ady Abraham11579302019-09-19 12:35:58 -07001587 if (fence == Fence::NO_FENCE) {
1588 return false;
1589 }
1590
1591 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1592 fence->wait(graceTimeMs);
1593 }
1594
1595 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001596}
1597
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001598void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001599 DisplayStatInfo stats;
1600 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001601 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001602 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001603 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001604 mPhaseOffsets->getOffsetThresholdForNextVsync()
1605 ? presentTime
1606 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001607}
1608
Dominik Laskowski22488f62019-03-28 09:53:04 -07001609void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001610 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001611 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001612 case MessageQueue::INVALIDATE: {
Ady Abraham7c03ce62019-07-19 10:59:45 -07001613 // calculate the expected present time once and use the cached
1614 // value throughout this frame to make sure all layers are
1615 // seeing this same value.
1616 populateExpectedPresentTime();
1617
Ady Abraham11579302019-09-19 12:35:58 -07001618 // When Backpressure propagation is enabled we want to give a small grace period
1619 // for the present fence to fire instead of just giving up on this frame to handle cases
1620 // where present fence is just about to get signaled.
1621 const int graceTimeForPresentFenceMs =
1622 (mPropagateBackpressure &&
1623 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1624 ? 1
1625 : 0;
1626 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1627 previousFrameMissed(
1628 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001629 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1630 mHadDeviceComposition && frameMissed};
1631 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1632 mHadClientComposition && frameMissed};
1633
Alec Mouricc0fc602019-02-26 21:45:19 -08001634 if (frameMissed) {
1635 mFrameMissedCount++;
1636 mTimeStats->incrementMissedFrames();
1637 }
1638
Alec Mouri40189b02019-03-05 15:07:54 -08001639 if (hwcFrameMissed) {
1640 mHwcFrameMissedCount++;
1641 }
1642
1643 if (gpuFrameMissed) {
1644 mGpuFrameMissedCount++;
1645 }
1646
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001647 if (mUseSmart90ForVideo) {
1648 // This call is made each time SF wakes up and creates a new frame. It is part
1649 // of video detection feature.
Ady Abraham09bd3922019-04-08 10:44:56 -07001650 mScheduler->updateFpsBasedOnContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001651 }
1652
Ady Abrahamb838aed2019-02-12 15:30:16 -08001653 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001654 break;
1655 }
1656
Ady Abrahamadb9a992019-09-19 21:21:55 +00001657 if (frameMissed && mPropagateBackpressure) {
1658 if ((hwcFrameMissed && !gpuFrameMissed) ||
1659 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001660 signalLayerUpdate();
1661 break;
1662 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001663 }
Dan Stoza50182882016-07-08 12:02:20 -07001664
Steven Thomas050b2c82017-03-06 11:45:16 -08001665 // Now that we're going to make it to the handleMessageTransaction()
1666 // call below it's safe to call updateVrFlinger(), which will
1667 // potentially trigger a display handoff.
1668 updateVrFlinger();
1669
Dan Stoza6b9454d2014-11-07 16:00:59 -08001670 bool refreshNeeded = handleMessageTransaction();
1671 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001672
1673 updateCursorAsync();
1674 updateInputFlinger();
1675
Dan Stoza58784442014-12-02 16:58:17 -08001676 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001677 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001678 // Signal a refresh if a transaction modified the window state,
1679 // a new buffer was latched, or if HWC has requested a full
1680 // repaint
Dan Stoza6b9454d2014-11-07 16:00:59 -08001681 signalRefresh();
1682 }
1683 break;
1684 }
1685 case MessageQueue::REFRESH: {
1686 handleMessageRefresh();
1687 break;
1688 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001689 }
1690}
1691
Dan Stoza6b9454d2014-11-07 16:00:59 -08001692bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001693 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001694 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001695
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001696 bool flushedATransaction = flushTransactionQueues();
1697
1698 bool runHandleTransaction = transactionFlags &&
1699 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1700
1701 if (runHandleTransaction) {
1702 handleTransaction(eTransactionMask);
1703 } else {
1704 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001705 }
1706
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001707 if (transactionFlushNeeded()) {
1708 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001709 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001710
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001711 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001712}
1713
Mathias Agopian4fec8732012-06-29 14:12:52 -07001714void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001715 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001716
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001717 mRefreshPending = false;
1718
Lloyd Piqueab039b52019-02-13 14:22:42 -08001719 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001720 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001721 for (const auto& [_, display] : mDisplays) {
1722 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1723 }
1724 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1725 auto compositionLayer = layer->getCompositionLayer();
1726 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1727 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001728 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1729 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1730 auto compositionLayer = layer->getCompositionLayer();
1731 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
1732 }
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);
1759
David Sodmanfa9b2af2017-12-24 13:28:59 -08001760 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001761 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001762
Lloyd Pique66d68602019-02-13 14:23:31 -08001763 mHadClientComposition =
1764 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1765 auto& displayDevice = tokenDisplayPair.second;
1766 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1767 });
1768 mHadDeviceComposition =
1769 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1770 auto& displayDevice = tokenDisplayPair.second;
1771 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1772 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001773
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001774 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001775
David Sodman7e4ae112018-02-09 15:02:28 -08001776 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001777 if (mVisibleRegionsDirty) {
1778 mVisibleRegionsDirty = false;
1779 if (mTracingEnabled) {
1780 mTracing.notify("visibleRegionsDirty");
1781 }
1782 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001783
1784 if (mCompositionEngine->needsAnotherUpdate()) {
1785 signalLayerUpdate();
1786 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001787}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001788
David Sodmanfa9b2af2017-12-24 13:28:59 -08001789
1790bool SurfaceFlinger::handleMessageInvalidate() {
1791 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001792 bool refreshNeeded = handlePageFlip();
1793
Vishnu Nair4351ad52019-02-11 14:13:02 -08001794 if (mVisibleRegionsDirty) {
1795 computeLayerBounds();
1796 }
1797
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001798 for (auto& layer : mLayersPendingRefresh) {
1799 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001800 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001801 invalidateLayerStack(layer, visibleReg);
1802 }
1803 mLayersPendingRefresh.clear();
1804 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001805}
1806
Ana Krulece588e312018-09-18 12:32:24 -07001807void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1808 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001809 // Update queue of past composite+present times and determine the
1810 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001811 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001812 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001813 while (!getBE().mCompositePresentTimes.empty()) {
1814 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001815 // Cached values should have been updated before calling this method,
1816 // which helps avoid duplicate syscalls.
1817 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1818 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1819 break;
1820 }
1821 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001822 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001823 }
1824
1825 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001826 while (getBE().mCompositePresentTimes.size() > 16) {
1827 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001828 }
1829
Ana Krulece588e312018-09-18 12:32:24 -07001830 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001831}
1832
Ana Krulece588e312018-09-18 12:32:24 -07001833void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1834 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001835 // Integer division and modulo round toward 0 not -inf, so we need to
1836 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001837 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1838 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1839 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001840
Ana Krulec757f63a2019-01-25 10:46:18 -08001841 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001842 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001843 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001844 }
1845
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001846 // Snap the latency to a value that removes scheduling jitter from the
1847 // composition and present times, which often have >1ms of jitter.
1848 // Reducing jitter is important if an app attempts to extrapolate
1849 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001850 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001851 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001852 nsecs_t bias = stats.vsyncPeriod / 2;
1853 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1854 nsecs_t snappedCompositeToPresentLatency =
1855 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001856
David Sodman99974d22017-11-28 12:04:33 -08001857 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001858 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1859 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001860 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001861}
1862
David Sodman2b406362017-12-15 13:33:47 -08001863void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001864{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001865 ATRACE_CALL();
1866 ALOGV("postComposition");
1867
Brian Anderson3546a3f2016-07-14 11:51:14 -07001868 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001869 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001870 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001871 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001872 }
1873
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001874 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001875 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001876
David Sodman73beded2017-11-15 11:56:06 -08001877 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001878 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08001879 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001880 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001881 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1882 ->getRenderSurface()
1883 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001884 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001885 } else {
1886 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1887 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001888
David Sodman73beded2017-11-15 11:56:06 -08001889 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001890 mPreviousPresentFences[1] = mPreviousPresentFences[0];
1891 mPreviousPresentFences[0] = displayDevice
1892 ? getHwComposer().getPresentFence(*displayDevice->getId())
1893 : Fence::NO_FENCE;
1894 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08001895 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001896
Ana Krulece588e312018-09-18 12:32:24 -07001897 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08001898 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001899
Lloyd Piqueab039b52019-02-13 14:22:42 -08001900 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
1901 // be sampled a little later than when we started doing work for this frame,
1902 // but that should be okay since updateCompositorTiming has snapping logic.
1903 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
1904 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001905 CompositorTiming compositorTiming;
1906 {
David Sodman99974d22017-11-28 12:04:33 -08001907 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1908 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001909 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001910
Robert Carr2047fae2016-11-28 14:09:09 -08001911 mDrawingState.traverseInZOrder([&](Layer* layer) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001912 bool frameLatched =
1913 layer->onPostComposition(displayDevice->getId(), glCompositionDoneFenceTime,
1914 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001915 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001916 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001917 }
Robert Carr2047fae2016-11-28 14:09:09 -08001918 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001919
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001920 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001921 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001922 }
1923
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001924 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001925 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1926 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001927 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001928 }
1929 }
1930
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001931 if (mAnimCompositionPending) {
1932 mAnimCompositionPending = false;
1933
Brian Anderson4e606e32017-03-16 15:34:57 -07001934 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001935 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001936 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07001937 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001938 // The HWC doesn't support present fences, so use the refresh
1939 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07001940 const nsecs_t presentTime =
1941 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001942 mAnimFrameTracker.setActualPresentTime(presentTime);
1943 }
1944 mAnimFrameTracker.advanceFrame();
1945 }
Dan Stozab90cf072015-03-05 11:05:59 -08001946
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001947 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001948 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001949 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001950 }
1951
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001952 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001953
Lloyd Pique32cbe282018-10-19 13:09:22 -07001954 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1955 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001956 return;
1957 }
1958
1959 nsecs_t currentTime = systemTime();
1960 if (mHasPoweredOff) {
1961 mHasPoweredOff = false;
1962 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001963 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001964 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001965 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1966 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001967 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001968 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001969 }
David Sodman4a36e932017-11-07 14:29:47 -08001970 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001971 }
David Sodman4a36e932017-11-07 14:29:47 -08001972 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001973
1974 {
1975 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07001976 if (mTexturePool.size() < mTexturePoolSize) {
1977 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07001978 const size_t offset = mTexturePool.size();
1979 mTexturePool.resize(mTexturePoolSize);
1980 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1981 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07001982 } else if (mTexturePool.size() > mTexturePoolSize) {
1983 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
1984 const size_t offset = mTexturePoolSize;
1985 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
1986 mTexturePool.resize(mTexturePoolSize);
1987 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07001988 }
1989 }
Marissa Walle2ffb422018-10-12 11:33:52 -07001990
Ady Abrahambe0f9482019-04-24 15:41:53 -07001991 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07001992 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08001993
Kevin DuBois413287f2019-02-25 08:46:47 -08001994 if (mLumaSampling && mRegionSamplingThread) {
1995 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08001996 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07001997
1998 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
1999 // side-effect of getTotalSize(), so we check that again here
2000 if (ATRACE_ENABLED()) {
2001 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2002 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002003}
2004
Vishnu Nair4351ad52019-02-11 14:13:02 -08002005void SurfaceFlinger::computeLayerBounds() {
2006 for (const auto& pair : mDisplays) {
2007 const auto& displayDevice = pair.second;
2008 const auto display = displayDevice->getCompositionDisplay();
2009 for (const auto& layer : mDrawingState.layersSortedByZ) {
2010 // only consider the layers on the given layer stack
2011 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002012 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002013 }
2014
2015 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform());
2016 }
2017 }
2018}
2019
David Sodmanfa9b2af2017-12-24 13:28:59 -08002020void SurfaceFlinger::postFrame()
2021{
2022 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002023 const auto display = getDefaultDisplayDeviceLocked();
2024 if (display && getHwComposer().isConnected(*display->getId())) {
2025 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002026 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2027 logFrameStats();
2028 }
2029 }
2030}
2031
Mathias Agopian87baae12012-07-31 12:38:26 -07002032void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002033{
Mathias Agopian841cde52012-03-01 15:44:37 -08002034 ATRACE_CALL();
2035
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002036 // here we keep a copy of the drawing state (that is the state that's
2037 // going to be overwritten by handleTransactionLocked()) outside of
2038 // mStateLock so that the side-effects of the State assignment
2039 // don't happen with mStateLock held (which can cause deadlocks).
2040 State drawingState(mDrawingState);
2041
Mathias Agopianca4d3602011-05-19 15:38:14 -07002042 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002043 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002044
Mathias Agopianca4d3602011-05-19 15:38:14 -07002045 // Here we're guaranteed that some transaction flags are set
2046 // so we can call handleTransactionLocked() unconditionally.
2047 // We call getTransactionFlags(), which will also clear the flags,
2048 // with mStateLock held to guarantee that mCurrentState won't change
2049 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002050
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002051 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002052 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002053 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002054
Mathias Agopianca4d3602011-05-19 15:38:14 -07002055 mDebugInTransaction = 0;
2056 invalidateHwcGeometry();
2057 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002058}
2059
Lloyd Piqueba04e622017-12-14 17:11:26 -08002060void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2061 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002062 const std::optional<DisplayIdentificationInfo> info =
2063 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002064
Dominik Laskowski075d3172018-05-24 15:50:06 -07002065 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002066 continue;
2067 }
2068
Lloyd Piqueba04e622017-12-14 17:11:26 -08002069 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002070 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002071 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002072 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2073 initScheduler(info->id);
2074 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002075 mPhysicalDisplayTokens[info->id] = new BBinder();
2076 DisplayDeviceState state;
2077 state.displayId = info->id;
2078 state.isSecure = true; // All physical displays are currently considered secure.
2079 state.displayName = info->name;
2080 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2081 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002082 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002083 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002084 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002085
Dominik Laskowski075d3172018-05-24 15:50:06 -07002086 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2087 if (index >= 0) {
2088 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2089 mInterceptor->saveDisplayDeletion(state.sequenceId);
2090 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002091 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002092 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002093 }
2094
2095 processDisplayChangesLocked();
2096 }
2097
2098 mPendingHotplugEvents.clear();
2099}
2100
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002101void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002102 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2103 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002104}
2105
Lloyd Pique99d3da52018-01-22 17:48:03 -08002106sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002107 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002108 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002109 const sp<IGraphicBufferProducer>& producer) {
2110 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002111 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002112 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002113 creationArgs.isSecure = state.isSecure;
2114 creationArgs.displaySurface = dispSurface;
2115 creationArgs.hasWideColorGamut = false;
2116 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002117 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002118
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002119 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002120 creationArgs.isPrimary = isInternalDisplay;
2121
2122 if (useColorManagement && displayId) {
2123 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002124 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002125 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002126 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002127 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002128
Dominik Laskowski7e045462018-05-30 13:02:02 -07002129 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002130 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002131 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002132 }
tangrobin6753a022018-08-10 10:58:54 +08002133 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002134
Dominik Laskowski075d3172018-05-24 15:50:06 -07002135 if (displayId) {
2136 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002137 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002138 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002139 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002140
Lloyd Pique90c115d2018-09-18 21:39:42 -07002141 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002142 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002143 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002144
Lloyd Pique99d3da52018-01-22 17:48:03 -08002145 // Make sure that composition can never be stalled by a virtual display
2146 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002147 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002148 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002149 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2150 }
2151
Dominik Laskowski075d3172018-05-24 15:50:06 -07002152 creationArgs.displayInstallOrientation =
2153 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002154
Lloyd Pique99d3da52018-01-22 17:48:03 -08002155 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002156 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002157
Lloyd Pique90c115d2018-09-18 21:39:42 -07002158 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002159
2160 if (maxFrameBufferAcquiredBuffers >= 3) {
2161 nativeWindowSurface->preallocateBuffers();
2162 }
2163
2164 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002165 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002166 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002167 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002168 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002169 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002170 display->getCompositionDisplay()->setColorProfile(
2171 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2172 RenderIntent::COLORIMETRIC,
2173 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002174 if (!state.isVirtual()) {
2175 LOG_ALWAYS_FATAL_IF(!displayId);
2176 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002177 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002178
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002179 display->setLayerStack(state.layerStack);
2180 display->setProjection(state.orientation, state.viewport, state.frame);
2181 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002182
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002183 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002184}
2185
Lloyd Pique347200f2017-12-14 17:00:15 -08002186void SurfaceFlinger::processDisplayChangesLocked() {
2187 // here we take advantage of Vector's copy-on-write semantics to
2188 // improve performance by skipping the transaction entirely when
2189 // know that the lists are identical
2190 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2191 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2192 if (!curr.isIdenticalTo(draw)) {
2193 mVisibleRegionsDirty = true;
2194 const size_t cc = curr.size();
2195 size_t dc = draw.size();
2196
2197 // find the displays that were removed
2198 // (ie: in drawing state but not in current state)
2199 // also handle displays that changed
2200 // (ie: displays that are in both lists)
2201 for (size_t i = 0; i < dc;) {
2202 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2203 if (j < 0) {
2204 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002205 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002206 // Save display ID before disconnecting.
2207 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002208 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002209
2210 if (!display->isVirtual()) {
2211 LOG_ALWAYS_FATAL_IF(!displayId);
2212 dispatchDisplayHotplugEvent(displayId->value, false);
2213 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002214 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002215
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002216 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002217 } else {
2218 // this display is in both lists. see if something changed.
2219 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002220 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002221 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2222 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2223 if (state_binder != draw_binder) {
2224 // changing the surface is like destroying and
2225 // recreating the DisplayDevice, so we just remove it
2226 // from the drawing state, so that it get re-added
2227 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002228 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002229 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002230 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002231 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002232 mDrawingState.displays.removeItemsAt(i);
2233 dc--;
2234 // at this point we must loop to the next item
2235 continue;
2236 }
2237
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002238 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002239 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002240 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002241 }
2242 if ((state.orientation != draw[i].orientation) ||
2243 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002244 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002245 }
2246 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002247 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002248 }
2249 }
2250 }
2251 ++i;
2252 }
2253
2254 // find displays that were added
2255 // (ie: in current state but not in drawing state)
2256 for (size_t i = 0; i < cc; i++) {
2257 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2258 const DisplayDeviceState& state(curr[i]);
2259
Lloyd Pique542307f2018-10-19 13:24:08 -07002260 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002261 sp<IGraphicBufferProducer> producer;
2262 sp<IGraphicBufferProducer> bqProducer;
2263 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002264 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002265
Dominik Laskowski075d3172018-05-24 15:50:06 -07002266 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002267 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002268 // Virtual displays without a surface are dormant:
2269 // they have external state (layer stack, projection,
2270 // etc.) but no internal state (i.e. a DisplayDevice).
2271 if (state.surface != nullptr) {
2272 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002273 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002274 int width = 0;
2275 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2276 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2277 int height = 0;
2278 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2279 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2280 int intFormat = 0;
2281 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2282 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002283 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002284
Dominik Laskowski075d3172018-05-24 15:50:06 -07002285 displayId =
2286 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002287 }
2288
2289 // TODO: Plumb requested format back up to consumer
2290
2291 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002292 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002293 bqProducer, bqConsumer,
2294 state.displayName);
2295
2296 dispSurface = vds;
2297 producer = vds;
2298 }
2299 } else {
2300 ALOGE_IF(state.surface != nullptr,
2301 "adding a supported display, but rendering "
2302 "surface is provided (%p), ignoring it",
2303 state.surface.get());
2304
Dominik Laskowski075d3172018-05-24 15:50:06 -07002305 displayId = state.displayId;
2306 LOG_ALWAYS_FATAL_IF(!displayId);
2307 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002308 producer = bqProducer;
2309 }
2310
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002311 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002312 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002313 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002314 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002315 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002316 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002317 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002318 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002319 }
2320 }
2321 }
2322 }
2323 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002324
2325 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002326}
2327
Mathias Agopian87baae12012-07-31 12:38:26 -07002328void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002329{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002330 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2331
Dan Stoza7dde5992015-05-22 09:51:44 -07002332 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002333 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2334 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002335 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002336
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002337 /*
2338 * Traversal of the children
2339 * (perform the transaction for each of them if needed)
2340 */
2341
Marissa Wall06255332019-03-27 13:48:27 -07002342 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002343 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002344 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002345 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002346
2347 const uint32_t flags = layer->doTransaction(0);
2348 if (flags & Layer::eVisibleRegion)
2349 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002350
2351 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002352 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002353 }
Robert Carr2047fae2016-11-28 14:09:09 -08002354 });
Marissa Wall06255332019-03-27 13:48:27 -07002355 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002356 }
2357
2358 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002359 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002360 */
2361
Mathias Agopiane57f2922012-08-09 16:29:12 -07002362 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002363 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002364 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002365 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002366
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002367 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002368 // The transform hint might have changed for some layers
2369 // (either because a display has changed, or because a layer
2370 // as changed).
2371 //
2372 // Walk through all the layers in currentLayers,
2373 // and update their transform hint.
2374 //
2375 // If a layer is visible only on a single display, then that
2376 // display is used to calculate the hint, otherwise we use the
2377 // default display.
2378 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002379 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002380 // the hint is set before we acquire a buffer from the surface texture.
2381 //
2382 // NOTE: layer transactions have taken place already, so we use their
2383 // drawing state. However, SurfaceFlinger's own transaction has not
2384 // happened yet, so we must use the current state layer list
2385 // (soon to become the drawing state list).
2386 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002387 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002388 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002389 bool first = true;
2390 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002391 // NOTE: we rely on the fact that layers are sorted by
2392 // layerStack first (so we don't have to traverse the list
2393 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002394 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002395 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002396 currentlayerStack = layerStack;
2397 // figure out if this layerstack is mirrored
2398 // (more than one display) if so, pick the default display,
2399 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002400 hintDisplay = nullptr;
2401 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002402 if (display->getCompositionDisplay()
2403 ->belongsInOutput(layer->getLayerStack(),
2404 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002405 if (hintDisplay) {
2406 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002407 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002408 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002409 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002410 }
2411 }
2412 }
2413 }
Chet Haase91d25932013-04-11 15:24:55 -07002414
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002415 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002416 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2417 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002418
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002419 // could be null when this layer is using a layerStack
2420 // that is not visible on any display. Also can occur at
2421 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002422 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002423 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002424
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002425 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002426 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002427 if (hintDisplay) {
2428 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002429 }
Robert Carr2047fae2016-11-28 14:09:09 -08002430
2431 first = false;
2432 });
Mathias Agopian84300952012-11-21 16:02:13 -08002433 }
2434
2435
Mathias Agopian3559b072012-08-15 13:46:03 -07002436 /*
2437 * Perform our own transaction if needed
2438 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002439
2440 if (mLayersAdded) {
2441 mLayersAdded = false;
2442 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002443 mVisibleRegionsDirty = true;
2444 }
2445
2446 // some layers might have been removed, so
2447 // we need to update the regions they're exposing.
2448 if (mLayersRemoved) {
2449 mLayersRemoved = false;
2450 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002451 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002452 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002453 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002454 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002455 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002456 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002457 }
Robert Carr2047fae2016-11-28 14:09:09 -08002458 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002459 }
2460
Vishnu Nairec0ab382019-02-13 15:32:56 -08002461 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002462 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002463}
2464
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002465void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002466 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002467 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002468 return;
2469 }
2470
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002471 if (mVisibleRegionsDirty || mInputInfoChanged) {
2472 mInputInfoChanged = false;
2473 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002474 } else if (mInputWindowCommands.syncInputWindows) {
2475 // If the caller requested to sync input windows, but there are no
2476 // changes to input windows, notify immediately.
2477 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002478 }
2479
Arthur Hung6cbb9752019-09-05 16:38:18 +08002480 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002481}
2482
2483void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002484 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002485
2486 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2487 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002488 // When calculating the screen bounds we ignore the transparent region since it may
2489 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002490 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002491 }
2492 });
chaviw291d88a2019-02-14 10:33:58 -08002493
2494 mInputFlinger->setInputWindows(inputHandles,
2495 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2496 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002497}
2498
Vishnu Nairec0ab382019-02-13 15:32:56 -08002499void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002500 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002501 mPendingInputWindowCommands.clear();
2502}
2503
Riley Andrews03414a12014-07-01 14:22:59 -07002504void SurfaceFlinger::updateCursorAsync()
2505{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002506 compositionengine::CompositionRefreshArgs refreshArgs;
2507 for (const auto& [_, display] : mDisplays) {
2508 if (display->getId()) {
2509 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002510 }
2511 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002512
2513 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002514}
2515
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002516void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2517 if (mScheduler) {
2518 // In practice it's not allowed to hotplug in/out the primary display once it's been
2519 // connected during startup, but some tests do it, so just warn and return.
2520 ALOGW("Can't re-init scheduler");
2521 return;
2522 }
2523
2524 int currentConfig = getHwComposer().getActiveConfigIndex(primaryDisplayId);
2525 mRefreshRateConfigs =
2526 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2527 getHwComposer().getConfigs(
2528 primaryDisplayId),
2529 currentConfig);
2530 mRefreshRateStats =
2531 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2532 currentConfig, HWC_POWER_MODE_OFF);
2533 mRefreshRateStats->setConfigMode(currentConfig);
2534
2535 // start the EventThread
2536 mScheduler =
2537 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
2538 *mRefreshRateConfigs);
2539 mAppConnectionHandle =
2540 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
2541 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2542 impl::EventThread::InterceptVSyncsCallback());
2543 mSfConnectionHandle =
2544 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
2545 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2546 [this](nsecs_t timestamp) {
2547 mInterceptor->saveVSyncEvent(timestamp);
2548 });
2549
2550 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2551 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
2552 mPhaseOffsets->getCurrentOffsets());
2553
2554 mRegionSamplingThread =
2555 new RegionSamplingThread(*this, *mScheduler,
2556 RegionSamplingThread::EnvironmentTimingTunables());
2557
2558 mScheduler->setChangeRefreshRateCallback(
2559 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
2560 Mutex::Autolock lock(mStateLock);
2561 setRefreshRateTo(type, event);
2562 });
2563}
2564
Mathias Agopian4fec8732012-06-29 14:12:52 -07002565void SurfaceFlinger::commitTransaction()
2566{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002567 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002568
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002569 mTransactionPending = false;
2570 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002571 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002572}
2573
Lloyd Pique58e24a32019-08-01 15:50:14 -07002574void SurfaceFlinger::commitTransactionLocked() {
2575 if (!mLayersPendingRemoval.isEmpty()) {
2576 // Notify removed layers now that they can't be drawn from
2577 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002578 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002579
2580 // Ensure any buffers set to display on any children are released.
2581 if (l->isRemovedFromCurrentState()) {
2582 l->latchAndReleaseBuffer();
2583 }
2584
2585 // If the layer has been removed and has no parent, then it will not be reachable
2586 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2587 // ensure we can copy its current to drawing state.
2588 if (!l->getParent()) {
2589 mOffscreenLayers.emplace(l.get());
2590 }
2591 }
2592 mLayersPendingRemoval.clear();
2593 }
2594
2595 // If this transaction is part of a window animation then the next frame
2596 // we composite should be considered an animation as well.
2597 mAnimCompositionPending = mAnimTransactionPending;
2598
2599 mDrawingState = mCurrentState;
2600 // clear the "changed" flags in current state
2601 mCurrentState.colorMatrixChanged = false;
2602
2603 mDrawingState.traverseInZOrder([&](Layer* layer) {
2604 layer->commitChildList();
2605
2606 // If the layer can be reached when traversing mDrawingState, then the layer is no
2607 // longer offscreen. Remove the layer from the offscreenLayer set.
2608 if (mOffscreenLayers.count(layer)) {
2609 mOffscreenLayers.erase(layer);
2610 }
2611 });
2612
2613 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002614 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002615}
2616
Nataniel Borges2b796da2019-02-15 13:32:18 -08002617void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2618 if (mTracingEnabledChanged) {
2619 mTracingEnabled = mTracing.isEnabled();
2620 mTracingEnabledChanged = false;
2621 }
2622
2623 // Synchronize with Tracing thread
2624 std::unique_lock<std::mutex> lock;
2625 if (mTracingEnabled) {
2626 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2627 }
2628
2629 lockedOperation();
2630
2631 // Synchronize with Tracing thread
2632 if (mTracingEnabled) {
2633 lock.unlock();
2634 }
2635}
2636
chaviw74d90ad2019-04-26 14:45:26 -07002637void SurfaceFlinger::commitOffscreenLayers() {
2638 for (Layer* offscreenLayer : mOffscreenLayers) {
2639 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2640 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2641 if (!trFlags) return;
2642
2643 layer->doTransaction(0);
2644 layer->commitChildList();
2645 });
2646 }
2647}
2648
Chia-I Wuab0c3192017-08-01 11:29:00 -07002649void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002650 for (const auto& [token, displayDevice] : mDisplays) {
2651 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002652 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002653 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002654 }
2655 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002656}
2657
Dan Stoza6b9454d2014-11-07 16:00:59 -08002658bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002659{
Ady Abraham09bd3922019-04-08 10:44:56 -07002660 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002661 ALOGV("handlePageFlip");
2662
Brian Andersond6927fb2016-07-23 23:37:30 -07002663 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002664
Mathias Agopian4fec8732012-06-29 14:12:52 -07002665 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002666 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002667 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002668
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002669 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2670
Eric Penner51c59cd2014-07-28 19:51:58 -07002671 // Store the set of layers that need updates. This set must not change as
2672 // buffers are being latched, as this could result in a deadlock.
2673 // Example: Two producers share the same command stream and:
2674 // 1.) Layer 0 is latched
2675 // 2.) Layer 0 gets a new frame
2676 // 2.) Layer 1 gets a new frame
2677 // 3.) Layer 1 is latched.
2678 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2679 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002680 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002681 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002682 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002683 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002684 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002685 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002686 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002687 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002688 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002689 } else {
2690 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002691 }
Robert Carr2047fae2016-11-28 14:09:09 -08002692 });
2693
chaviw49a108c2019-08-12 11:23:06 -07002694 // The client can continue submitting buffers for offscreen layers, but they will not
2695 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2696 // layers to ensure dequeueBuffer doesn't block indefinitely.
2697 for (Layer* offscreenLayer : mOffscreenLayers) {
2698 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2699 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2700 }
2701
Lloyd Piquef2c79392018-12-20 16:23:33 -08002702 if (!mLayersWithQueuedFrames.empty()) {
2703 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2704 // writes to Layer current state. See also b/119481871
2705 Mutex::Autolock lock(mStateLock);
2706
2707 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002708 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002709 mLayersPendingRefresh.push_back(layer);
2710 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002711 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002712 if (layer->isBufferLatched()) {
2713 newDataLatched = true;
2714 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002715 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002716 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002717
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002718 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002719
2720 // If we will need to wake up at some time in the future to deal with a
2721 // queued frame that shouldn't be displayed during this vsync period, wake
2722 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002723 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002724 signalLayerUpdate();
2725 }
2726
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002727 // enter boot animation on first buffer latch
2728 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2729 ALOGI("Enter boot animation");
2730 mBootStage = BootStage::BOOTANIMATION;
2731 }
2732
chaviw74b03172019-08-19 11:09:03 -07002733 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2734
Dan Stoza6b9454d2014-11-07 16:00:59 -08002735 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002736 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002737}
2738
Mathias Agopianad456f92011-01-13 17:53:01 -08002739void SurfaceFlinger::invalidateHwcGeometry()
2740{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002741 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002742}
2743
Robert Carrc0df3122019-04-11 13:18:21 -07002744status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2745 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2746 const sp<IBinder>& parentHandle,
2747 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002748 // add this layer to the current state list
2749 {
2750 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002751 sp<Layer> parent;
2752 if (parentHandle != nullptr) {
2753 parent = fromHandle(parentHandle);
2754 if (parent == nullptr) {
2755 return NAME_NOT_FOUND;
2756 }
2757 } else {
2758 parent = parentLayer;
2759 }
2760
Robert Carr1f0a16a2016-10-24 16:27:39 -07002761 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002762 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002763 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002764 return NO_MEMORY;
2765 }
Robert Carrc0df3122019-04-11 13:18:21 -07002766
2767 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2768
Robert Carrb89ea9d2018-12-10 13:01:14 -08002769 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002770 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002771 } else if (parent == nullptr) {
2772 lbc->onRemovedFromCurrentState();
2773 } else if (parent->isRemovedFromCurrentState()) {
2774 parent->addChild(lbc);
2775 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002776 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002777 parent->addChild(lbc);
2778 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002779
Yiwei Zhang243b3782018-05-15 17:40:04 -07002780 if (gbc != nullptr) {
2781 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2782 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2783 mMaxGraphicBufferProducerListSize,
2784 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2785 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002786 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002787 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002788 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002789 }
2790
Mathias Agopian96f08192010-06-02 23:28:45 -07002791 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002792 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002793
Dan Stoza7d89d062015-04-30 13:29:25 -07002794 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002795}
2796
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002797uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002798 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002799}
2800
Mathias Agopian3f844832013-08-07 21:24:32 -07002801uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002802 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002803}
2804
Mathias Agopian3f844832013-08-07 21:24:32 -07002805uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002806 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002807}
2808
2809uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002810 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002811 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002812 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002813 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002814 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002815 }
2816 return old;
2817}
2818
Marissa Wall713b63f2018-10-17 15:42:43 -07002819bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002820 // to prevent onHandleDestroyed from being called while the lock is held,
2821 // we must keep a copy of the transactions (specifically the composer
2822 // states) around outside the scope of the lock
2823 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002824 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002825 {
2826 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002827
Valerie Haufce31b82019-04-30 16:41:14 -07002828 auto it = mTransactionQueues.begin();
2829 while (it != mTransactionQueues.end()) {
2830 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002831
Valerie Haufce31b82019-04-30 16:41:14 -07002832 while (!transactionQueue.empty()) {
2833 const auto& transaction = transactionQueue.front();
2834 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002835 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002836 transaction.states)) {
2837 setTransactionFlags(eTransactionFlushNeeded);
2838 break;
2839 }
2840 transactions.push_back(transaction);
2841 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2842 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002843 transaction.buffer, transaction.postTime,
2844 transaction.privileged, transaction.hasListenerCallbacks,
2845 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002846 transactionQueue.pop();
2847 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002848 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002849
Valerie Haufce31b82019-04-30 16:41:14 -07002850 if (transactionQueue.empty()) {
2851 it = mTransactionQueues.erase(it);
2852 mTransactionCV.broadcast();
2853 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002854 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002855 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002856 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002857 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002858 return flushedATransaction;
2859}
2860
2861bool SurfaceFlinger::transactionFlushNeeded() {
2862 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07002863}
2864
chaviwca27f252018-02-06 16:46:39 -08002865
Marissa Wall17b4e452018-12-26 16:32:34 -08002866bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002867 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08002868 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002869 if (!useCachedExpectedPresentTime)
2870 populateExpectedPresentTime();
2871
2872 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08002873 // Do not present if the desiredPresentTime has not passed unless it is more than one second
2874 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
2875 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
2876 desiredPresentTime < expectedPresentTime + s2ns(1)) {
2877 return false;
2878 }
2879
Marissa Wall713b63f2018-10-17 15:42:43 -07002880 for (const ComposerState& state : states) {
2881 const layer_state_t& s = state.state;
2882 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
2883 continue;
2884 }
2885 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08002886 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07002887 }
2888 }
Marissa Wall17b4e452018-12-26 16:32:34 -08002889 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002890}
2891
Valerie Hau9dab9732019-08-20 09:29:25 -07002892void SurfaceFlinger::setTransactionState(
2893 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2894 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
2895 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
2896 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002897 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08002898
Valerie Haubc6ddb12019-03-08 11:10:15 -08002899 const int64_t postTime = systemTime();
2900
Robert Carr14167e02019-02-13 13:50:55 -08002901 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
2902
Mathias Agopian698c0872011-06-28 19:09:31 -07002903 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07002904
Marissa Wall713b63f2018-10-17 15:42:43 -07002905 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07002906 auto itr = mTransactionQueues.find(applyToken);
2907 // if this is an animation frame, wait until prior animation frame has
2908 // been applied by SF
2909 if (flags & eAnimation) {
2910 while (itr != mTransactionQueues.end()) {
2911 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2912 if (CC_UNLIKELY(err != NO_ERROR)) {
2913 ALOGW_IF(err == TIMED_OUT,
2914 "setTransactionState timed out "
2915 "waiting for animation frame to apply");
2916 break;
2917 }
2918 itr = mTransactionQueues.find(applyToken);
2919 }
2920 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002921
2922 // Expected present time is computed and cached on invalidate, so it may be stale.
2923 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
2924 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08002925 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002926 uncacheBuffer, postTime, privileged,
2927 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002928 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002929 return;
2930 }
2931
Valerie Haubc6ddb12019-03-08 11:10:15 -08002932 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002933 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
2934 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07002935}
2936
Valerie Hau9dab9732019-08-20 09:29:25 -07002937void SurfaceFlinger::applyTransactionState(
2938 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2939 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
2940 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
2941 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
2942 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07002943 uint32_t transactionFlags = 0;
2944
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002945 if (flags & eAnimation) {
2946 // For window updates that are part of an animation we must wait for
2947 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07002948 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002949 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002950 if (CC_UNLIKELY(err != NO_ERROR)) {
2951 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002952 // caller after a few seconds.
2953 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2954 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002955 mAnimTransactionPending = false;
2956 break;
2957 }
2958 }
2959 }
2960
chaviwca27f252018-02-06 16:46:39 -08002961 for (const DisplayState& display : displays) {
2962 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002963 }
2964
Valerie Hau9dab9732019-08-20 09:29:25 -07002965 // start and end registration for listeners w/ no surface so they can get their callback. Note
2966 // that listeners with SurfaceControls will start registration during setClientStateLocked
2967 // below.
2968 for (const auto& listener : listenerCallbacks) {
2969 mTransactionCompletedThread.startRegistration(listener);
2970 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07002971 }
2972
Valerie Hau9dab9732019-08-20 09:29:25 -07002973 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07002974 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08002975 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07002976 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
2977 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07002978 }
2979
Valerie Hau9dab9732019-08-20 09:29:25 -07002980 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07002981 mTransactionCompletedThread.endRegistration(listenerCallback);
2982 }
2983
Marissa Walle2ffb422018-10-12 11:33:52 -07002984 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07002985 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07002986 mTransactionCompletedThread.sendCallbacks();
2987 }
2988 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08002989
chaviw273171b2018-12-26 11:46:30 -08002990 transactionFlags |= addInputWindowCommands(inputWindowCommands);
2991
Marissa Wall947d34e2019-03-29 14:03:53 -07002992 if (uncacheBuffer.isValid()) {
2993 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07002994 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07002995 }
2996
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02002997 // If a synchronous transaction is explicitly requested without any changes, force a transaction
2998 // anyway. This can be used as a flush mechanism for previous async transactions.
2999 // Empty animation transaction can be used to simulate back-pressure, so also force a
3000 // transaction for empty animation transactions.
3001 if (transactionFlags == 0 &&
3002 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003003 transactionFlags = eTransactionNeeded;
3004 }
3005
Marissa Wall06255332019-03-27 13:48:27 -07003006 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3007 // so we don't have to wake up again next frame to preform an uneeded traversal.
3008 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3009 transactionFlags = transactionFlags & (~eTraversalNeeded);
3010 mTraversalNeededMainThread = true;
3011 }
3012
Mathias Agopian386aa982011-11-07 21:58:03 -08003013 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003014 if (mInterceptor->isEnabled()) {
3015 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003016 }
Irvel468051e2016-06-13 16:44:44 -07003017
Mathias Agopian386aa982011-11-07 21:58:03 -08003018 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003019 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3020 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003021 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003022
3023 // if this is a synchronous transaction, wait for it to take effect
3024 // before returning.
3025 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003026 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003027 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003028 if (flags & eAnimation) {
3029 mAnimTransactionPending = true;
3030 }
chaviw4fe36852019-04-15 16:25:49 -07003031 if (mPendingInputWindowCommands.syncInputWindows) {
3032 mPendingSyncInputWindows = true;
3033 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003034
3035 // applyTransactionState can be called by either the main SF thread or by
3036 // another process through setTransactionState. While a given process may wish
3037 // to wait on synchronous transactions, the main SF thread should never
3038 // be blocked. Therefore, we only wait if isMainThread is false.
3039 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003040 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3041 if (CC_UNLIKELY(err != NO_ERROR)) {
3042 // just in case something goes wrong in SF, return to the
3043 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003044 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3045 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003046 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003047 break;
3048 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003049 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003050 }
3051}
3052
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003053uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3054 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3055 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003056
Mathias Agopiane57f2922012-08-09 16:29:12 -07003057 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003058 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3059
3060 const uint32_t what = s.what;
3061 if (what & DisplayState::eSurfaceChanged) {
3062 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3063 state.surface = s.surface;
3064 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003065 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003066 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003067 if (what & DisplayState::eLayerStackChanged) {
3068 if (state.layerStack != s.layerStack) {
3069 state.layerStack = s.layerStack;
3070 flags |= eDisplayTransactionNeeded;
3071 }
3072 }
3073 if (what & DisplayState::eDisplayProjectionChanged) {
3074 if (state.orientation != s.orientation) {
3075 state.orientation = s.orientation;
3076 flags |= eDisplayTransactionNeeded;
3077 }
3078 if (state.frame != s.frame) {
3079 state.frame = s.frame;
3080 flags |= eDisplayTransactionNeeded;
3081 }
3082 if (state.viewport != s.viewport) {
3083 state.viewport = s.viewport;
3084 flags |= eDisplayTransactionNeeded;
3085 }
3086 }
3087 if (what & DisplayState::eDisplaySizeChanged) {
3088 if (state.width != s.width) {
3089 state.width = s.width;
3090 flags |= eDisplayTransactionNeeded;
3091 }
3092 if (state.height != s.height) {
3093 state.height = s.height;
3094 flags |= eDisplayTransactionNeeded;
3095 }
3096 }
3097
Mathias Agopiane57f2922012-08-09 16:29:12 -07003098 return flags;
3099}
3100
Robert Carr14167e02019-02-13 13:50:55 -08003101bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003102 IPCThreadState* ipc = IPCThreadState::self();
3103 const int pid = ipc->getCallingPid();
3104 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003105 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003106 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003107 return false;
3108 }
3109 return true;
3110}
3111
Marissa Wall3dad52d2019-03-22 14:03:19 -07003112uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003113 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3114 bool privileged,
3115 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003116 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003117
Valerie Hau9dab9732019-08-20 09:29:25 -07003118 for (auto& listener : s.listeners) {
3119 // note that startRegistration will not re-register if the listener has
3120 // already be registered for a prior surface control
3121 mTransactionCompletedThread.startRegistration(listener);
3122 listenerCallbacks.insert(listener);
3123 }
3124
Vishnu Nairf03652d2019-07-16 17:56:56 -07003125 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003126 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003127 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003128 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003129 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003130 }
chaviw8b3871a2017-11-01 17:41:01 -07003131 return 0;
3132 }
3133
chaviw8b3871a2017-11-01 17:41:01 -07003134 uint32_t flags = 0;
3135
Garfield Tan8a3083e2018-12-03 13:21:07 -08003136 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003137
3138 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3139 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003140 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003141 layer->pushPendingState();
3142 }
3143
chaviw8b3871a2017-11-01 17:41:01 -07003144 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003145 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003146 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003147 }
chaviw8b3871a2017-11-01 17:41:01 -07003148 }
3149 if (what & layer_state_t::eLayerChanged) {
3150 // NOTE: index needs to be calculated before we update the state
3151 const auto& p = layer->getParent();
3152 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003153 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003154 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003155 mCurrentState.layersSortedByZ.removeAt(idx);
3156 mCurrentState.layersSortedByZ.add(layer);
3157 // we need traversal (state changed)
3158 // AND transaction (list changed)
3159 flags |= eTransactionNeeded|eTraversalNeeded;
3160 }
chaviw8b3871a2017-11-01 17:41:01 -07003161 } else {
3162 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003163 flags |= eTransactionNeeded|eTraversalNeeded;
3164 }
3165 }
chaviw8b3871a2017-11-01 17:41:01 -07003166 }
3167 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003168 // NOTE: index needs to be calculated before we update the state
3169 const auto& p = layer->getParent();
3170 if (p == nullptr) {
3171 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3172 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3173 mCurrentState.layersSortedByZ.removeAt(idx);
3174 mCurrentState.layersSortedByZ.add(layer);
3175 // we need traversal (state changed)
3176 // AND transaction (list changed)
3177 flags |= eTransactionNeeded|eTraversalNeeded;
3178 }
3179 } else {
3180 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3181 flags |= eTransactionNeeded|eTraversalNeeded;
3182 }
chaviw8b3871a2017-11-01 17:41:01 -07003183 }
3184 }
3185 if (what & layer_state_t::eSizeChanged) {
3186 if (layer->setSize(s.w, s.h)) {
3187 flags |= eTraversalNeeded;
3188 }
3189 }
3190 if (what & layer_state_t::eAlphaChanged) {
3191 if (layer->setAlpha(s.alpha))
3192 flags |= eTraversalNeeded;
3193 }
3194 if (what & layer_state_t::eColorChanged) {
3195 if (layer->setColor(s.color))
3196 flags |= eTraversalNeeded;
3197 }
Peiyong Lind3788632018-09-18 16:01:31 -07003198 if (what & layer_state_t::eColorTransformChanged) {
3199 if (layer->setColorTransform(s.colorTransform)) {
3200 flags |= eTraversalNeeded;
3201 }
3202 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003203 if (what & layer_state_t::eBackgroundColorChanged) {
3204 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3205 flags |= eTraversalNeeded;
3206 }
3207 }
chaviw8b3871a2017-11-01 17:41:01 -07003208 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003209 // TODO: b/109894387
3210 //
3211 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3212 // rotation. To see the problem observe that if we have a square parent, and a child
3213 // of the same size, then we rotate the child 45 degrees around it's center, the child
3214 // must now be cropped to a non rectangular 8 sided region.
3215 //
3216 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3217 // private API, and the WindowManager only uses rotation in one case, which is on a top
3218 // level layer in which cropping is not an issue.
3219 //
3220 // However given that abuse of rotation matrices could lead to surfaces extending outside
3221 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3222 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3223 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003224 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003225 flags |= eTraversalNeeded;
3226 }
3227 if (what & layer_state_t::eTransparentRegionChanged) {
3228 if (layer->setTransparentRegionHint(s.transparentRegion))
3229 flags |= eTraversalNeeded;
3230 }
3231 if (what & layer_state_t::eFlagsChanged) {
3232 if (layer->setFlags(s.flags, s.mask))
3233 flags |= eTraversalNeeded;
3234 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003235 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003236 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003237 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003238 if (what & layer_state_t::eCornerRadiusChanged) {
3239 if (layer->setCornerRadius(s.cornerRadius))
3240 flags |= eTraversalNeeded;
3241 }
chaviw8b3871a2017-11-01 17:41:01 -07003242 if (what & layer_state_t::eLayerStackChanged) {
3243 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3244 // We only allow setting layer stacks for top level layers,
3245 // everything else inherits layer stack from its parent.
3246 if (layer->hasParent()) {
3247 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003248 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003249 } else if (idx < 0) {
3250 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003251 "that also does not appear in the top level layer list. Something"
3252 " has gone wrong.",
3253 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003254 } else if (layer->setLayerStack(s.layerStack)) {
3255 mCurrentState.layersSortedByZ.removeAt(idx);
3256 mCurrentState.layersSortedByZ.add(layer);
3257 // we need traversal (state changed)
3258 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003259 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003260 }
3261 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003262 if (what & layer_state_t::eDeferTransaction_legacy) {
3263 if (s.barrierHandle_legacy != nullptr) {
3264 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3265 } else if (s.barrierGbp_legacy != nullptr) {
3266 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003267 if (authenticateSurfaceTextureLocked(gbp)) {
3268 const auto& otherLayer =
3269 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003270 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003271 } else {
3272 ALOGE("Attempt to defer transaction to to an"
3273 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003274 }
3275 }
chaviw8b3871a2017-11-01 17:41:01 -07003276 // We don't trigger a traversal here because if no other state is
3277 // changed, we don't want this to cause any more work
3278 }
chaviw8b3871a2017-11-01 17:41:01 -07003279 if (what & layer_state_t::eReparentChildren) {
3280 if (layer->reparentChildren(s.reparentHandle)) {
3281 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003282 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003283 }
chaviw8b3871a2017-11-01 17:41:01 -07003284 if (what & layer_state_t::eDetachChildren) {
3285 layer->detachChildren();
3286 }
3287 if (what & layer_state_t::eOverrideScalingModeChanged) {
3288 layer->setOverrideScalingMode(s.overrideScalingMode);
3289 // We don't trigger a traversal here because if no other state is
3290 // changed, we don't want this to cause any more work
3291 }
Marissa Wall61c58622018-07-18 10:12:20 -07003292 if (what & layer_state_t::eTransformChanged) {
3293 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3294 }
3295 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3296 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3297 flags |= eTraversalNeeded;
3298 }
3299 if (what & layer_state_t::eCropChanged) {
3300 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3301 }
Marissa Wall861616d2018-10-22 12:52:23 -07003302 if (what & layer_state_t::eFrameChanged) {
3303 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3304 }
Marissa Wall61c58622018-07-18 10:12:20 -07003305 if (what & layer_state_t::eAcquireFenceChanged) {
3306 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3307 }
3308 if (what & layer_state_t::eDataspaceChanged) {
3309 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3310 }
3311 if (what & layer_state_t::eHdrMetadataChanged) {
3312 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3313 }
3314 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3315 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3316 }
3317 if (what & layer_state_t::eApiChanged) {
3318 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3319 }
3320 if (what & layer_state_t::eSidebandStreamChanged) {
3321 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3322 }
Robert Carr720e5062018-07-30 17:45:14 -07003323 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003324 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003325 layer->setInputInfo(s.inputInfo);
3326 flags |= eTraversalNeeded;
3327 } else {
3328 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3329 }
Robert Carr720e5062018-07-30 17:45:14 -07003330 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003331 if (what & layer_state_t::eMetadataChanged) {
3332 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3333 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003334 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3335 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3336 flags |= eTraversalNeeded;
3337 }
3338 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003339 // This has to happen after we reparent children because when we reparent to null we remove
3340 // child layers from current state and remove its relative z. If the children are reparented in
3341 // the same transaction, then we have to make sure we reparent the children first so we do not
3342 // lose its relative z order.
3343 if (what & layer_state_t::eReparent) {
3344 bool hadParent = layer->hasParent();
3345 if (layer->reparent(s.parentHandleForChild)) {
3346 if (!hadParent) {
3347 mCurrentState.layersSortedByZ.remove(layer);
3348 }
3349 flags |= eTransactionNeeded | eTraversalNeeded;
3350 }
3351 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003352 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003353 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3354 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003355 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3356 }
3357 }
Marissa Wall78b72202019-03-15 14:58:34 -07003358 bool bufferChanged = what & layer_state_t::eBufferChanged;
3359 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3360 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003361 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003362 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003363 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3364 if (success) {
3365 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3366 success = ClientCache::getInstance()
3367 .registerErasedRecipient(s.cachedBuffer,
3368 wp<ClientCache::ErasedRecipient>(this));
3369 if (!success) {
3370 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3371 }
3372 }
Marissa Wall78b72202019-03-15 14:58:34 -07003373 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003374 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003375 } else if (bufferChanged) {
3376 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003377 }
Marissa Wall78b72202019-03-15 14:58:34 -07003378 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003379 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003380 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003381 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003382 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003383 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3384 // Do not put anything that updates layer state or modifies flags after
3385 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003386 return flags;
3387}
3388
chaviw273171b2018-12-26 11:46:30 -08003389uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3390 uint32_t flags = 0;
3391 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3392 flags |= eTraversalNeeded;
3393 }
3394
chaviwa911b102019-02-14 10:18:33 -08003395 if (inputWindowCommands.syncInputWindows) {
3396 flags |= eTraversalNeeded;
3397 }
3398
Vishnu Nairec0ab382019-02-13 15:32:56 -08003399 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003400 return flags;
3401}
3402
chaviwfe94a222019-08-21 13:52:59 -07003403status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3404 sp<IBinder>* outHandle) {
3405 if (!mirrorFromHandle) {
3406 return NAME_NOT_FOUND;
3407 }
3408
3409 sp<Layer> mirrorLayer;
3410 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003411 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003412
3413 {
3414 Mutex::Autolock _l(mStateLock);
3415 mirrorFrom = fromHandle(mirrorFromHandle);
3416 if (!mirrorFrom) {
3417 return NAME_NOT_FOUND;
3418 }
3419
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003420 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3421 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003422 if (result != NO_ERROR) {
3423 return result;
3424 }
3425
3426 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3427 }
3428
3429 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3430}
3431
Marissa Wall2d814fb2019-04-09 18:52:57 +00003432status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3433 uint32_t h, PixelFormat format, uint32_t flags,
3434 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003435 sp<IGraphicBufferProducer>* gbp,
3436 const sp<IBinder>& parentHandle,
3437 const sp<Layer>& parentLayer) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003438 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003439 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003440 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003441 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003442 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003443
Robert Carrc0df3122019-04-11 13:18:21 -07003444 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3445 "Expected only one of parentLayer or parentHandle to be non-null. "
3446 "Programmer error?");
3447
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003448 status_t result = NO_ERROR;
3449
3450 sp<Layer> layer;
3451
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003452 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003453
Evan Roskya1f1e152019-01-24 16:17:46 -08003454 bool primaryDisplayOnly = false;
3455
3456 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3457 // TODO b/64227542
3458 if (metadata.has(METADATA_WINDOW_TYPE)) {
3459 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3460 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003461 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003462 primaryDisplayOnly = true;
3463 }
3464 }
3465
Mathias Agopian3165cc22012-08-08 19:42:09 -07003466 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003467 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003468 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3469 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003470
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003471 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003472 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003473 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
3474 std::move(metadata), handle, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003475 break;
chaviw13fdc492017-06-27 12:40:18 -07003476 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003477 // check if buffer size is set for color layer.
3478 if (w > 0 || h > 0) {
3479 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3480 int(w), int(h));
3481 return BAD_VALUE;
3482 }
3483
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003484 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3485 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003486 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003487 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003488 // check if buffer size is set for container layer.
3489 if (w > 0 || h > 0) {
3490 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3491 int(w), int(h));
3492 return BAD_VALUE;
3493 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003494 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3495 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003496 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003497 default:
3498 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003499 break;
3500 }
3501
Dan Stoza7d89d062015-04-30 13:29:25 -07003502 if (result != NO_ERROR) {
3503 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003504 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003505
Evan Roskya1f1e152019-01-24 16:17:46 -08003506 if (primaryDisplayOnly) {
3507 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003508 }
3509
Robert Carrb89ea9d2018-12-10 13:01:14 -08003510 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003511 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3512 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003513 if (result != NO_ERROR) {
3514 return result;
3515 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003516 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003517
3518 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003519 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003520}
3521
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003522std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3523 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003524
3525 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003526 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003527
Dan Stoza436ccf32018-06-21 12:10:12 -07003528 // Grab the state lock since we're accessing mCurrentState
3529 Mutex::Autolock lock(mStateLock);
3530
Cody Northropbc755282017-03-31 12:00:08 -06003531 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003532 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003533 while (matchFound) {
3534 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003535 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003536 if (layer->getName() == uniqueName) {
3537 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003538 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003539 }
3540 });
3541 }
3542
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003543 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003544 return uniqueName;
3545}
3546
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003547status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003548 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003549 LayerMetadata metadata, PixelFormat& format,
3550 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003551 sp<IGraphicBufferProducer>* gbp,
3552 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003553 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003554 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003555 case PIXEL_FORMAT_TRANSPARENT:
3556 case PIXEL_FORMAT_TRANSLUCENT:
3557 format = PIXEL_FORMAT_RGBA_8888;
3558 break;
3559 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003560 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003561 break;
3562 }
3563
chaviwb4c6e582019-08-16 14:35:07 -07003564 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003565 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003566 args.textureName = getNewTexture();
3567 {
3568 // Grab the SF state lock during this since it's the only safe way to access
3569 // RenderEngine when creating a BufferLayerConsumer
3570 // TODO: Check if this lock is still needed here
3571 Mutex::Autolock lock(mStateLock);
3572 layer = getFactory().createBufferQueueLayer(args);
3573 }
3574
Marissa Wallfd668622018-05-10 10:21:13 -07003575 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003576 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003577 *handle = layer->getHandle();
3578 *gbp = layer->getProducer();
3579 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003580 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003581
Marissa Wallfd668622018-05-10 10:21:13 -07003582 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003583 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003584}
3585
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003586status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003587 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003588 LayerMetadata metadata, sp<IBinder>* handle,
3589 sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003590 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003591 args.displayDevice = getDefaultDisplayDevice();
3592 args.textureName = getNewTexture();
3593 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Marissa Wall61c58622018-07-18 10:12:20 -07003594 *handle = layer->getHandle();
3595 *outLayer = layer;
3596
3597 return NO_ERROR;
3598}
3599
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003600status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003601 uint32_t h, uint32_t flags, LayerMetadata metadata,
3602 sp<IBinder>* handle, sp<Layer>* outLayer) {
3603 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003604 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003605 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003606 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003607}
3608
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003609status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003610 uint32_t w, uint32_t h, uint32_t flags,
3611 LayerMetadata metadata, sp<IBinder>* handle,
3612 sp<Layer>* outLayer) {
3613 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003614 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003615 *handle = (*outLayer)->getHandle();
3616 return NO_ERROR;
3617}
3618
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003619void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003620 mLayersPendingRemoval.add(layer);
3621 mLayersRemoved = true;
3622 setTransactionFlags(eTransactionNeeded);
3623}
3624
Robert Carr695d5282018-12-18 15:27:58 -08003625void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003626{
Robert Carr2e102c92018-10-23 12:11:15 -07003627 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003628 // If a layer has a parent, we allow it to out-live it's handle
3629 // with the idea that the parent holds a reference and will eventually
3630 // be cleaned up. However no one cleans up the top-level so we do so
3631 // here.
3632 if (layer->getParent() == nullptr) {
3633 mCurrentState.layersSortedByZ.remove(layer);
3634 }
3635 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003636
3637 auto it = mLayersByLocalBinderToken.begin();
3638 while (it != mLayersByLocalBinderToken.end()) {
3639 if (it->second == layer) {
3640 it = mLayersByLocalBinderToken.erase(it);
3641 } else {
3642 it++;
3643 }
3644 }
3645
Robert Carr695d5282018-12-18 15:27:58 -08003646 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003647}
3648
Mathias Agopianb60314a2012-04-10 22:09:54 -07003649// ---------------------------------------------------------------------------
3650
Andy McFadden13a082e2012-08-24 10:16:42 -07003651void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003652 const auto display = getDefaultDisplayDeviceLocked();
3653 if (!display) return;
3654
3655 const sp<IBinder> token = display->getDisplayToken().promote();
3656 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003657
Jesse Hall01e29052013-02-19 16:13:35 -08003658 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003659 Vector<ComposerState> state;
3660 Vector<DisplayState> displays;
3661 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003662 d.what = DisplayState::eDisplayProjectionChanged |
3663 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003664 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003665 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003666 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003667 d.frame.makeInvalid();
3668 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003669 d.width = 0;
3670 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003671 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003672 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3673 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003674
Dominik Laskowskie9774092018-12-11 10:04:24 -08003675 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003676
Dominik Laskowski83b88212018-12-11 13:34:06 -08003677 const nsecs_t vsyncPeriod = getVsyncPeriod();
3678 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003679
Brian Andersond0010582017-03-07 13:20:31 -08003680 // Use phase of 0 since phase is not known.
3681 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003682 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003683 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003684}
3685
3686void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003687 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003688 postMessageAsync(
3689 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003690}
3691
Ady Abraham27c70212019-06-11 10:52:26 -07003692void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3693 if (mHWCVsyncState != enabled) {
3694 getHwComposer().setVsyncEnabled(displayId, enabled);
3695 mHWCVsyncState = enabled;
3696 }
3697}
3698
Dominik Laskowskie9774092018-12-11 10:04:24 -08003699void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003700 if (display->isVirtual()) {
3701 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003702 return;
3703 }
3704
Dominik Laskowski075d3172018-05-24 15:50:06 -07003705 const auto displayId = display->getId();
3706 LOG_ALWAYS_FATAL_IF(!displayId);
3707
Dominik Laskowski34157762018-10-31 13:07:19 -07003708 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003709
3710 int currentMode = display->getPowerMode();
3711 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003712 return;
3713 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003714
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003715 display->setPowerMode(mode);
3716
Lloyd Pique4dccc412018-01-22 17:21:36 -08003717 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003718 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003719 }
3720
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003721 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003722 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003723 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003724 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003725 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003726 mScheduler->onScreenAcquired(mAppConnectionHandle);
3727 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003728 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003729
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003730 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003731 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003732 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003733
3734 struct sched_param param = {0};
3735 param.sched_priority = 1;
3736 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3737 ALOGW("Couldn't set SCHED_FIFO on display on");
3738 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003739 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003740 // Turn off the display
3741 struct sched_param param = {0};
3742 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3743 ALOGW("Couldn't set SCHED_OTHER on display off");
3744 }
3745
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003746 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003747 mScheduler->disableHardwareVsync(true);
3748 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003749 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003750
Ady Abraham27c70212019-06-11 10:52:26 -07003751 // Make sure HWVsync is disabled before turning off the display
3752 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3753
Dominik Laskowski075d3172018-05-24 15:50:06 -07003754 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003755 mVisibleRegionsDirty = true;
3756 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003757 } else if (mode == HWC_POWER_MODE_DOZE ||
3758 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003759 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003760 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003761 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003762 mScheduler->onScreenAcquired(mAppConnectionHandle);
3763 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003764 }
3765 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3766 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003767 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003768 mScheduler->disableHardwareVsync(true);
3769 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003770 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003771 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003772 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003773 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003774 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003775 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003776
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003777 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003778 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003779 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003780 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003781 }
3782
Dominik Laskowski34157762018-10-31 13:07:19 -07003783 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003784}
3785
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003786void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003787 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003788 const auto display = getDisplayDevice(displayToken);
3789 if (!display) {
3790 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3791 displayToken.get());
3792 } else if (display->isVirtual()) {
3793 ALOGW("Attempt to set power mode %d for virtual display", mode);
3794 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003795 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003796 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003797 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003798}
3799
3800// ---------------------------------------------------------------------------
3801
Dominik Laskowskic2867142019-01-21 11:33:38 -08003802status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3803 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003804 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003805
Mathias Agopianbd115332013-04-18 16:41:04 -07003806 IPCThreadState* ipc = IPCThreadState::self();
3807 const int pid = ipc->getCallingPid();
3808 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003809
Mathias Agopianbd115332013-04-18 16:41:04 -07003810 if ((uid != AID_SHELL) &&
3811 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003812 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3813 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003814 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003815 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003816 // (this would indicate SF is stuck, but we want to be able to
3817 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003818 status_t err = mStateLock.timedLock(s2ns(1));
3819 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003820 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003821 StringAppendF(&result,
3822 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3823 "(no locks held)\n",
3824 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003825 }
3826
Dominik Laskowskic2867142019-01-21 11:33:38 -08003827 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003828 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003829 {"--dispsync"s,
3830 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003831 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003832 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3833 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3834 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3835 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3836 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3837 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003838 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003839 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3840 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003841
Dominik Laskowskic2867142019-01-21 11:33:38 -08003842 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003843
Dominik Laskowski46470112019-08-02 13:13:11 -07003844 const auto it = dumpers.find(flag);
3845 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003846 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07003847 } else if (!asProto) {
3848 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003849 }
3850
Mathias Agopian9795c422009-08-26 16:36:26 -07003851 if (locked) {
3852 mStateLock.unlock();
3853 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003854
Dominik Laskowski46470112019-08-02 13:13:11 -07003855 if (it == dumpers.end()) {
3856 const LayersProto layersProto = dumpProtoFromMainThread();
3857 if (asProto) {
3858 result.append(layersProto.SerializeAsString());
3859 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07003860 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07003861 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3862 result.append(LayerProtoParser::layerTreeToString(layerTree));
3863 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07003864 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07003865 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003866 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003867 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08003868 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003869 return NO_ERROR;
3870}
3871
Nataniel Borges8e7dc722019-02-28 15:10:28 -08003872status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
3873 if (asProto && mTracing.isEnabled()) {
3874 mTracing.writeToFileAsync();
3875 }
3876
3877 return doDump(fd, DumpArgs(), asProto);
3878}
3879
Dominik Laskowskic2867142019-01-21 11:33:38 -08003880void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003881 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003882 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003883}
3884
Dominik Laskowskic2867142019-01-21 11:33:38 -08003885void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003886 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003887
Dominik Laskowskic2867142019-01-21 11:33:38 -08003888 if (args.size() > 1) {
3889 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08003890 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003891 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003892 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003893 }
Robert Carr2047fae2016-11-28 14:09:09 -08003894 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08003895 } else {
3896 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003897 }
3898}
3899
Dominik Laskowskic2867142019-01-21 11:33:38 -08003900void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003901 const bool clearAll = args.size() < 2;
3902 const auto name = clearAll ? String8() : String8(args[1]);
3903
Robert Carr2047fae2016-11-28 14:09:09 -08003904 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003905 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003906 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003907 }
Robert Carr2047fae2016-11-28 14:09:09 -08003908 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003909
Svetoslavd85084b2014-03-20 10:28:31 -07003910 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003911}
3912
Dominik Laskowskic2867142019-01-21 11:33:38 -08003913void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
3914 mTimeStats->parseArgs(asProto, args, result);
3915}
3916
Jamie Gennis6547ff42013-07-16 20:12:42 -07003917// This should only be called from the main thread. Otherwise it would need
3918// the lock and should use mCurrentState rather than mDrawingState.
3919void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003920 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003921 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003922 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003923
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003924 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07003925}
3926
Yiwei Zhang5434a782018-12-05 18:06:32 -08003927void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003928 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003929
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003930 if (isLayerTripleBufferingDisabled())
3931 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003932
Yiwei Zhang5434a782018-12-05 18:06:32 -08003933 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
3934 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
3935 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
3936 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
3937 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3938 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003939 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003940}
3941
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003942void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07003943 mScheduler->dump(result);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003944 StringAppendF(&result, "+ Refresh rate switching: %s\n",
3945 mRefreshRateConfigs->refreshRateSwitchingSupported() ? "on" : "off");
Dominik Laskowski98041832019-08-01 18:35:59 -07003946 StringAppendF(&result, "+ Smart video mode: %s\n\n", mUseSmart90ForVideo ? "on" : "off");
3947
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003948 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07003949 result.append("\n");
3950
Ana Krulec757f63a2019-01-25 10:46:18 -08003951 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003952 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07003953 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08003954 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003955
Ady Abraham42b3beb2019-07-09 18:09:52 -07003956 StringAppendF(&result, "Allowed Display Configs: ");
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003957 for (int32_t configId : mAllowedDisplayConfigs) {
3958 StringAppendF(&result, "%" PRIu32 " Hz, ",
3959 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07003960 }
3961 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
3962 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07003963
Ana Krulecc2870422019-01-29 19:00:58 -08003964 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003965}
3966
Yiwei Zhang5434a782018-12-05 18:06:32 -08003967void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
3968 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003969 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3970 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003971 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003972 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003973 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003974 }
David Sodman4a36e932017-11-07 14:29:47 -08003975 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003976 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003977 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003978 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
3979 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003980}
3981
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003982void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
3983 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003984 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3985 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003986 for (const auto& segment : history) {
3987 if (!segment.usedThirdBuffer) {
3988 stats.twoBufferTime += segment.totalTime;
3989 }
3990 if (segment.occupancyAverage < 1.0f) {
3991 stats.doubleBufferedTime += segment.totalTime;
3992 } else if (segment.occupancyAverage < 2.0f) {
3993 stats.tripleBufferedTime += segment.totalTime;
3994 }
3995 ++stats.numSegments;
3996 stats.totalTime += segment.totalTime;
3997 }
3998}
3999
Yiwei Zhang5434a782018-12-05 18:06:32 -08004000void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4001 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004002
4003 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4004 const size_t count = currentLayers.size();
4005 for (size_t i=0 ; i<count ; i++) {
4006 currentLayers[i]->dumpFrameEvents(result);
4007 }
4008}
4009
Yiwei Zhang5434a782018-12-05 18:06:32 -08004010void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004011 result.append("Buffering stats:\n");
4012 result.append(" [Layer name] <Active time> <Two buffer> "
4013 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004014 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004015 typedef std::tuple<std::string, float, float, float> BufferTuple;
4016 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004017 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004018 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004019 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004020 if (stats.numSegments == 0) {
4021 continue;
4022 }
4023 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4024 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4025 stats.totalTime;
4026 float doubleBufferRatio = static_cast<float>(
4027 stats.doubleBufferedTime) / stats.totalTime;
4028 float tripleBufferRatio = static_cast<float>(
4029 stats.tripleBufferedTime) / stats.totalTime;
4030 sorted.insert({activeTime, {name, twoBufferRatio,
4031 doubleBufferRatio, tripleBufferRatio}});
4032 }
4033 for (const auto& sortedPair : sorted) {
4034 float activeTime = sortedPair.first;
4035 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004036 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4037 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004038 }
4039 result.append("\n");
4040}
4041
Yiwei Zhang5434a782018-12-05 18:06:32 -08004042void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004043 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004044 const auto displayId = display->getId();
4045 if (!displayId) {
4046 continue;
4047 }
4048 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004049 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004050 continue;
4051 }
4052
Yiwei Zhang5434a782018-12-05 18:06:32 -08004053 StringAppendF(&result,
4054 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4055 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004056 uint8_t port;
4057 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004058 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004059 result.append("no identification data\n");
4060 continue;
4061 }
4062
4063 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004064 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004065 continue;
4066 }
4067
4068 const auto edid = parseEdid(data);
4069 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004070 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004071 continue;
4072 }
4073
Yiwei Zhang5434a782018-12-05 18:06:32 -08004074 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004075 result.append(edid->displayName.data(), edid->displayName.length());
4076 result.append("\"\n");
4077 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004078}
4079
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004080void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4081 std::string& result) const {
4082 hwc2_display_t hwcDisplayId;
4083 uint8_t port;
4084 DisplayIdentificationData data;
4085
4086 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4087 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4088 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4089 }
4090}
4091
Yiwei Zhang5434a782018-12-05 18:06:32 -08004092void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004093 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004094 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4095 StringAppendF(&result, "DisplayColorSetting: %s\n",
4096 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004097
4098 // TODO: print out if wide-color mode is active or not
4099
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004100 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004101 const auto displayId = display->getId();
4102 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004103 continue;
4104 }
4105
Yiwei Zhang5434a782018-12-05 18:06:32 -08004106 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004107 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004108 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004109 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004110 }
4111
Lloyd Pique32cbe282018-10-19 13:09:22 -07004112 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004113 StringAppendF(&result, " Current color mode: %s (%d)\n",
4114 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004115 }
4116 result.append("\n");
4117}
4118
Vishnu Nair8406fd72019-07-30 11:29:31 -07004119LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004120 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004121 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004122 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004123 layer->writeToProtoDrawingState(layerProto, traceFlags);
4124 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004125 });
4126
4127 return layersProto;
4128}
4129
Vishnu Nair0f085c62019-08-30 08:49:12 -07004130void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4131 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4132 // it.
4133 LayerProto* rootProto = layersProto.add_layers();
4134 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4135 rootProto->set_id(offscreenRootLayerId);
4136 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004137 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004138
4139 for (Layer* offscreenLayer : mOffscreenLayers) {
4140 // Add layer as child of the fake root
4141 rootProto->add_children(offscreenLayer->sequence);
4142
4143 // Add layer
4144 LayerProto* layerProto = layersProto.add_layers();
4145 offscreenLayer->writeToProtoDrawingState(layerProto, traceFlags);
4146 offscreenLayer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing,
4147 traceFlags);
4148 layerProto->set_parent(offscreenRootLayerId);
4149
4150 // Add children
4151 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4152 if (layer == offscreenLayer) {
4153 return;
4154 }
4155 LayerProto* childProto = layersProto.add_layers();
4156 layer->writeToProtoDrawingState(childProto, traceFlags);
4157 layer->writeToProtoCommonState(childProto, LayerVector::StateSet::Drawing, traceFlags);
4158 });
4159 }
4160}
4161
Vishnu Nair8406fd72019-07-30 11:29:31 -07004162LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4163 LayersProto layersProto;
4164 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4165 return layersProto;
4166}
4167
Vishnu Nair0f085c62019-08-30 08:49:12 -07004168void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4169 result.append("Offscreen Layers:\n");
4170 postMessageSync(new LambdaMessage([&]() {
4171 for (Layer* offscreenLayer : mOffscreenLayers) {
4172 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4173 layer->dumpCallingUidPid(result);
4174 });
4175 }
4176 }));
4177}
4178
Dominik Laskowskic2867142019-01-21 11:33:38 -08004179void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4180 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004181 Colorizer colorizer(colorize);
4182
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004183 // figure out if we're stuck somewhere
4184 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004185 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004186 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4187
4188 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004189 * Dump library configuration.
4190 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004191
4192 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004193 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004194 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004195 appendSfConfigString(result);
4196 appendUiConfigString(result);
4197 appendGuiConfigString(result);
4198 result.append("\n");
4199
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004200 result.append("\nDisplay identification data:\n");
4201 dumpDisplayIdentificationData(result);
4202
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004203 result.append("\nWide-Color information:\n");
4204 dumpWideColorInfo(result);
4205
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004206 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004207 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004208 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004209 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004210 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004211
Andy McFadden41d67d72014-04-25 16:58:34 -07004212 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004213 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004214 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004215 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004216 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004217
Dan Stozab90cf072015-03-05 11:05:59 -08004218 dumpStaticScreenStats(result);
4219 result.append("\n");
4220
Alec Mouri40189b02019-03-05 15:07:54 -08004221 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4222 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4223 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004224
Dan Stozae77c7662016-05-13 11:37:28 -07004225 dumpBufferingStats(result);
4226
Andy McFadden4803b742012-09-24 19:07:20 -07004227 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004228 * Dump the visible layer list
4229 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004230 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004231 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004232 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4233 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004234 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004235
Chia-I Wu2f884132018-09-13 15:17:58 -07004236 {
Lloyd Pique207def92019-02-28 16:09:52 -08004237 StringAppendF(&result, "Composition layers\n");
4238 mDrawingState.traverseInZOrder([&](Layer* layer) {
4239 auto compositionLayer = layer->getCompositionLayer();
4240 if (compositionLayer) compositionLayer->dump(result);
4241 });
4242 }
4243
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004244 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004245 * Dump Display state
4246 */
4247
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004248 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004249 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004250 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004251 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004252 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004253 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004254 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004255
4256 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004257 * Dump CompositionEngine state
4258 */
4259
4260 mCompositionEngine->dump(result);
4261
4262 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004263 * Dump SurfaceFlinger global state
4264 */
4265
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004266 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004267 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004268 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004269
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004270 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004271
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004272 DebugEGLImageTracker::getInstance()->dump(result);
4273
Dominik Laskowski075d3172018-05-24 15:50:06 -07004274 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004275 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4276 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004277 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4278 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004279 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004280 StringAppendF(&result,
4281 " transaction-flags : %08x\n"
4282 " gpu_to_cpu_unsupported : %d\n",
4283 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004284
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004285 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004286 displayId && getHwComposer().isConnected(*displayId)) {
4287 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004288 StringAppendF(&result,
4289 " refresh-rate : %f fps\n"
4290 " x-dpi : %f\n"
4291 " y-dpi : %f\n",
4292 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4293 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004294 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004295
Yiwei Zhang5434a782018-12-05 18:06:32 -08004296 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004297
Dan Stozae22aec72016-08-01 13:20:59 -07004298 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004299 * Tracing state
4300 */
4301 mTracing.dump(result);
4302 result.append("\n");
4303
4304 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004305 * HWC layer minidump
4306 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004307 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004308 const auto displayId = display->getId();
4309 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004310 continue;
4311 }
4312
Yiwei Zhang5434a782018-12-05 18:06:32 -08004313 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004314 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004315 const sp<DisplayDevice> displayDevice = display;
4316 mCurrentState.traverseInZOrder(
4317 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004318 result.append("\n");
4319 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004320
4321 /*
4322 * Dump HWComposer state
4323 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004324 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004325 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004326 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004327 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004328 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004329 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004330
4331 /*
4332 * Dump gralloc state
4333 */
4334 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4335 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004336
4337 /*
4338 * Dump VrFlinger state if in use.
4339 */
4340 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4341 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004342 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004343 result.append("\n");
4344 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004345
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004346 result.append(mTimeStats->miniDump());
4347 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004348}
4349
Chia-I Wu28f320b2018-05-03 11:02:56 -07004350void SurfaceFlinger::updateColorMatrixLocked() {
4351 mat4 colorMatrix;
4352 if (mGlobalSaturationFactor != 1.0f) {
4353 // Rec.709 luma coefficients
4354 float3 luminance{0.213f, 0.715f, 0.072f};
4355 luminance *= 1.0f - mGlobalSaturationFactor;
4356 mat4 saturationMatrix = mat4(
4357 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4358 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4359 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4360 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4361 );
4362 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4363 } else {
4364 colorMatrix = mClientColorMatrix * mDaltonizer();
4365 }
4366
4367 if (mCurrentState.colorMatrix != colorMatrix) {
4368 mCurrentState.colorMatrix = colorMatrix;
4369 mCurrentState.colorMatrixChanged = true;
4370 setTransactionFlags(eTransactionNeeded);
4371 }
4372}
4373
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004374status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004375#pragma clang diagnostic push
4376#pragma clang diagnostic error "-Wswitch-enum"
4377 switch (static_cast<ISurfaceComposerTag>(code)) {
4378 // These methods should at minimum make sure that the client requested
4379 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004380 case BOOT_FINISHED:
4381 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004382 case CREATE_DISPLAY:
4383 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004384 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004385 case GET_ANIMATION_FRAME_STATS:
4386 case GET_HDR_CAPABILITIES:
4387 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004388 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004389 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004390 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004391 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004392 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004393 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004394 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004395 case GET_DISPLAYED_CONTENT_SAMPLE:
4396 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004397 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4398 IPCThreadState* ipc = IPCThreadState::self();
4399 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4400 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004401 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004402 }
Robert Carr1db73f62016-12-21 12:58:51 -08004403 return OK;
4404 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004405 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004406 IPCThreadState* ipc = IPCThreadState::self();
4407 const int pid = ipc->getCallingPid();
4408 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004409 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4410 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004411 return PERMISSION_DENIED;
4412 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004413 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004414 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004415 // Used by apps to hook Choreographer to SurfaceFlinger.
4416 case CREATE_DISPLAY_EVENT_CONNECTION:
4417 // The following calls are currently used by clients that do not
4418 // request necessary permissions. However, they do not expose any secret
4419 // information, so it is OK to pass them.
4420 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004421 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004422 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004423 case GET_PHYSICAL_DISPLAY_IDS:
4424 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004425 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004426 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004427 case GET_DISPLAY_CONFIGS:
4428 case GET_DISPLAY_STATS:
4429 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4430 // Calling setTransactionState is safe, because you need to have been
4431 // granted a reference to Client* and Handle* to do anything with it.
4432 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004433 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004434 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004435 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004436 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004437 case IS_WIDE_COLOR_DISPLAY:
4438 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4439 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004440 return OK;
4441 }
Chong Zhangda6c1592019-07-16 13:45:06 -07004442 case CAPTURE_LAYERS: {
4443 IPCThreadState* ipc = IPCThreadState::self();
4444 const int pid = ipc->getCallingPid();
4445 const int uid = ipc->getCallingUid();
4446 // allow media to capture layer for video thumbnails
4447 if ((uid != AID_GRAPHICS && uid != AID_MEDIA) &&
4448 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4449 ALOGE("Permission Denial: can't capture layer pid=%d, uid=%d", pid, uid);
4450 return PERMISSION_DENIED;
4451 }
4452 return OK;
4453 }
Dan Stoza84ab9372018-12-17 15:27:57 -08004454 case CAPTURE_SCREEN:
4455 case ADD_REGION_SAMPLING_LISTENER:
4456 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004457 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004458 IPCThreadState* ipc = IPCThreadState::self();
4459 const int pid = ipc->getCallingPid();
4460 const int uid = ipc->getCallingUid();
4461 if ((uid != AID_GRAPHICS) &&
4462 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4463 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4464 return PERMISSION_DENIED;
4465 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004466 return OK;
4467 }
4468 // The following codes are deprecated and should never be allowed to access SF.
4469 case CONNECT_DISPLAY_UNUSED:
4470 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4471 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4472 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004473 }
chaviw93df2ea2019-04-30 16:45:12 -07004474 case CAPTURE_SCREEN_BY_ID: {
4475 IPCThreadState* ipc = IPCThreadState::self();
4476 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004477 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004478 return OK;
4479 }
4480 return PERMISSION_DENIED;
4481 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004482 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004483
4484 // These codes are used for the IBinder protocol to either interrogate the recipient
4485 // side of the transaction for its canonical interface descriptor or to dump its state.
4486 // We let them pass by default.
4487 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4488 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4489 code == IBinder::SYSPROPS_TRANSACTION) {
4490 return OK;
4491 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004492 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004493 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004494 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004495 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4496 return OK;
4497 }
4498 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4499 return PERMISSION_DENIED;
4500#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004501}
4502
Ana Krulec13be8ad2018-08-21 02:43:56 +00004503status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4504 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004505 status_t credentialCheck = CheckTransactCodeCredentials(code);
4506 if (credentialCheck != OK) {
4507 return credentialCheck;
4508 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004509
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004510 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4511 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004512 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004513 IPCThreadState* ipc = IPCThreadState::self();
4514 const int uid = ipc->getCallingUid();
4515 if (CC_UNLIKELY(uid != AID_SYSTEM
4516 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004517 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004518 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004519 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004520 return PERMISSION_DENIED;
4521 }
4522 int n;
4523 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004524 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004525 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004526 return NO_ERROR;
4527 case 1002: // SHOW_UPDATES
4528 n = data.readInt32();
4529 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004530 invalidateHwcGeometry();
4531 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004532 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004533 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004534 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004535 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004536 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004537 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004538 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004539 setTransactionFlags(
4540 eTransactionNeeded|
4541 eDisplayTransactionNeeded|
4542 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004543 return NO_ERROR;
4544 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004545 case 1006:{ // send empty update
4546 signalRefresh();
4547 return NO_ERROR;
4548 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004549 case 1008: // toggle use of hw composer
4550 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004551 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004552 invalidateHwcGeometry();
4553 repaintEverything();
4554 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004555 case 1009: // toggle use of transform hint
4556 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004557 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004558 invalidateHwcGeometry();
4559 repaintEverything();
4560 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004561 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004562 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004563 reply->writeInt32(0);
4564 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004565 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004566 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004567 return NO_ERROR;
4568 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004569 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004570 if (!display) {
4571 return NAME_NOT_FOUND;
4572 }
4573
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004574 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004575 return NO_ERROR;
4576 }
4577 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004578 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004579 // daltonize
4580 n = data.readInt32();
4581 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004582 case 1:
4583 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4584 break;
4585 case 2:
4586 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4587 break;
4588 case 3:
4589 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4590 break;
4591 default:
4592 mDaltonizer.setType(ColorBlindnessType::None);
4593 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004594 }
4595 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004596 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004597 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004598 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004599 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004600
4601 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004602 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004603 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004604 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004605 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004606 // apply a color matrix
4607 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004608 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004609 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004610 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004611 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004612 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004613 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004614 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004615 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004616 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004617 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004618
4619 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4620 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004621 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004622 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4623 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4624 }
4625
Chia-I Wu28f320b2018-05-03 11:02:56 -07004626 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004627 return NO_ERROR;
4628 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004629 case 1016: { // Unused.
4630 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004631 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004632 case 1017: {
4633 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004634 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004635 return NO_ERROR;
4636 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004637 case 1018: { // Modify Choreographer's phase offset
4638 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004639 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004640 return NO_ERROR;
4641 }
4642 case 1019: { // Modify SurfaceFlinger's phase offset
4643 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004644 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004645 return NO_ERROR;
4646 }
Irvel468051e2016-06-13 16:44:44 -07004647 case 1020: { // Layer updates interceptor
4648 n = data.readInt32();
4649 if (n) {
4650 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004651 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004652 }
4653 else{
4654 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004655 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004656 }
4657 return NO_ERROR;
4658 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004659 case 1021: { // Disable HWC virtual displays
4660 n = data.readInt32();
4661 mUseHwcVirtualDisplays = !n;
4662 return NO_ERROR;
4663 }
Romain Guy0147a172017-06-01 13:53:56 -07004664 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004665 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004666 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004667
Chia-I Wu28f320b2018-05-03 11:02:56 -07004668 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004669 return NO_ERROR;
4670 }
Romain Guy54f154a2017-10-24 21:40:32 +01004671 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004672 int32_t colorMode;
4673
Chia-I Wu0d711262018-05-21 15:19:35 -07004674 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004675 if (data.readInt32(&colorMode) == NO_ERROR) {
4676 mForceColorMode = static_cast<ColorMode>(colorMode);
4677 }
Romain Guy54f154a2017-10-24 21:40:32 +01004678 invalidateHwcGeometry();
4679 repaintEverything();
4680 return NO_ERROR;
4681 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004682 // Deprecate, use 1030 to check whether the device is color managed.
4683 case 1024: {
4684 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004685 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004686 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004687 n = data.readInt32();
4688 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004689 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004690 Mutex::Autolock lock(mStateLock);
4691 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004692 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004693 reply->writeInt32(NO_ERROR);
4694 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004695 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004696 bool writeFile = false;
4697 {
4698 Mutex::Autolock lock(mStateLock);
4699 mTracingEnabledChanged = true;
4700 writeFile = mTracing.disable();
4701 }
4702
4703 if (writeFile) {
4704 reply->writeInt32(mTracing.writeToFile());
4705 } else {
4706 reply->writeInt32(NO_ERROR);
4707 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004708 }
4709 return NO_ERROR;
4710 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004711 case 1026: { // Get layer tracing status
4712 reply->writeBool(mTracing.isEnabled());
4713 return NO_ERROR;
4714 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004715 // Is a DisplayColorSetting supported?
4716 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004717 const auto display = getDefaultDisplayDevice();
4718 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004719 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004720 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004721
4722 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4723 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004724 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004725 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004726 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004727 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004728 reply->writeBool(true);
4729 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004730 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004731 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004732 break;
4733 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004734 reply->writeBool(
4735 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004736 break;
4737 }
4738 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004739 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004740 // Is VrFlinger active?
4741 case 1028: {
4742 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004743 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004744 return NO_ERROR;
4745 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004746 // Set buffer size for SF tracing (value in KB)
4747 case 1029: {
4748 n = data.readInt32();
4749 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4750 ALOGW("Invalid buffer size: %d KB", n);
4751 reply->writeInt32(BAD_VALUE);
4752 return BAD_VALUE;
4753 }
4754
4755 ALOGD("Updating trace buffer to %d KB", n);
4756 mTracing.setBufferSize(n * 1024);
4757 reply->writeInt32(NO_ERROR);
4758 return NO_ERROR;
4759 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004760 // Is device color managed?
4761 case 1030: {
4762 reply->writeBool(useColorManagement);
4763 return NO_ERROR;
4764 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004765 // Override default composition data space
4766 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4767 // && adb shell stop zygote && adb shell start zygote
4768 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4769 // adb shell stop zygote && adb shell start zygote
4770 case 1031: {
4771 Mutex::Autolock _l(mStateLock);
4772 n = data.readInt32();
4773 if (n) {
4774 n = data.readInt32();
4775 if (n) {
4776 Dataspace dataspace = static_cast<Dataspace>(n);
4777 if (!validateCompositionDataspace(dataspace)) {
4778 return BAD_VALUE;
4779 }
4780 mDefaultCompositionDataspace = dataspace;
4781 }
4782 n = data.readInt32();
4783 if (n) {
4784 Dataspace dataspace = static_cast<Dataspace>(n);
4785 if (!validateCompositionDataspace(dataspace)) {
4786 return BAD_VALUE;
4787 }
4788 mWideColorGamutCompositionDataspace = dataspace;
4789 }
4790 } else {
4791 // restore composition data space.
4792 mDefaultCompositionDataspace = defaultCompositionDataspace;
4793 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4794 }
4795 return NO_ERROR;
4796 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004797 // Set trace flags
4798 case 1033: {
4799 n = data.readUint32();
4800 ALOGD("Updating trace flags to 0x%x", n);
4801 mTracing.setTraceFlags(n);
4802 reply->writeInt32(NO_ERROR);
4803 return NO_ERROR;
4804 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004805 case 1034: {
4806 // TODO(b/129297325): expose this via developer menu option
4807 n = data.readInt32();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004808 if (n && !mRefreshRateOverlay &&
4809 mRefreshRateConfigs->refreshRateSwitchingSupported()) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07004810 RefreshRateType type;
4811 {
4812 std::lock_guard<std::mutex> lock(mActiveConfigLock);
4813 type = mDesiredActiveConfig.type;
4814 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004815 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07004816 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004817 } else if (!n) {
4818 mRefreshRateOverlay.reset();
4819 }
4820 return NO_ERROR;
4821 }
Ady Abraham34392f72019-04-10 11:29:27 -07004822 case 1035: {
4823 n = data.readInt32();
4824 mDebugDisplayConfigSetByBackdoor = false;
4825 if (n >= 0) {
4826 const auto displayToken = getInternalDisplayToken();
4827 status_t result = setAllowedDisplayConfigs(displayToken, {n});
4828 if (result != NO_ERROR) {
4829 return result;
4830 }
4831 mDebugDisplayConfigSetByBackdoor = true;
4832 }
4833 return NO_ERROR;
4834 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004835 }
4836 }
4837 return err;
4838}
4839
Steven Thomas6d8110b2017-08-31 18:24:21 -07004840void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004841 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004842 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004843}
4844
Ana Krulec7d1d6832018-12-27 11:10:09 -08004845void SurfaceFlinger::repaintEverythingForHWC() {
4846 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004847 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004848}
4849
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004850// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4851class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004852public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004853 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4854 ~WindowDisconnector() {
4855 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004856 }
4857
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004858private:
4859 ANativeWindow* mWindow;
4860 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004861};
4862
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004863status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07004864 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
4865 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004866 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07004867 uint32_t reqWidth, uint32_t reqHeight,
4868 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08004869 ISurfaceComposer::Rotation rotation,
4870 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004871 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004872
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004873 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004874
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07004875 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
4876
Chia-I Wu20261cb2018-08-23 12:55:44 -07004877 sp<DisplayDevice> display;
4878 {
4879 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004880
Chia-I Wu20261cb2018-08-23 12:55:44 -07004881 display = getDisplayDeviceLocked(displayToken);
4882 if (!display) return BAD_VALUE;
4883
Chia-I Wucb023152018-08-28 12:57:23 -07004884 // set the requested width/height to the logical display viewport size
4885 // by default
4886 if (reqWidth == 0 || reqHeight == 0) {
4887 reqWidth = uint32_t(display->getViewport().width());
4888 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07004889 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004890 }
4891
Peiyong Lin0e003c92018-09-17 11:09:51 -07004892 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08004893 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004894
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08004895 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4896 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07004897 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07004898 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004899}
4900
chaviw93df2ea2019-04-30 16:45:12 -07004901static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
4902 switch (colorMode) {
4903 case ColorMode::DISPLAY_P3:
4904 case ColorMode::BT2100_PQ:
4905 case ColorMode::BT2100_HLG:
4906 case ColorMode::DISPLAY_BT2020:
4907 return Dataspace::DISPLAY_P3;
4908 default:
4909 return Dataspace::V0_SRGB;
4910 }
4911}
4912
4913const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
4914 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
4915 if (displayToken) {
4916 return getDisplayDeviceLocked(displayToken);
4917 }
4918 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
4919 // may not have a displayId.
4920 for (const auto& [token, display] : mDisplays) {
4921 if (display->getLayerStack() == displayOrLayerStack) {
4922 return display;
4923 }
4924 }
4925 return nullptr;
4926}
4927
4928status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
4929 sp<GraphicBuffer>* outBuffer) {
4930 sp<DisplayDevice> display;
4931 uint32_t width;
4932 uint32_t height;
4933 ui::Transform::orientation_flags captureOrientation;
4934 {
4935 Mutex::Autolock _l(mStateLock);
4936 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
4937 if (!display) {
4938 return BAD_VALUE;
4939 }
4940
4941 width = uint32_t(display->getViewport().width());
4942 height = uint32_t(display->getViewport().height());
4943
4944 captureOrientation = fromSurfaceComposerRotation(
4945 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07004946 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
4947 captureOrientation = ui::Transform::orientation_flags::ROT_270;
4948 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
4949 captureOrientation = ui::Transform::orientation_flags::ROT_90;
4950 }
chaviw93df2ea2019-04-30 16:45:12 -07004951 *outDataspace =
4952 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
4953 }
4954
4955 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
4956 false /* captureSecureLayers */);
4957
4958 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4959 std::placeholders::_1);
4960 bool ignored = false;
4961 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
4962 false /* useIdentityTransform */,
4963 ignored /* outCapturedSecureLayers */);
4964}
4965
Robert Carr866455f2019-04-02 16:28:26 -07004966status_t SurfaceFlinger::captureLayers(
4967 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
4968 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
4969 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
4970 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004971 ATRACE_CALL();
4972
4973 class LayerRenderArea : public RenderArea {
4974 public:
Robert Carr578038f2018-03-09 12:25:24 -08004975 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004976 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
4977 bool childrenOnly)
4978 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08004979 mLayer(layer),
4980 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004981 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08004982 mFlinger(flinger),
4983 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004984 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004985 Rect getBounds() const override {
4986 const Layer::State& layerState(mLayer->getDrawingState());
4987 return mLayer->getBufferSize(layerState);
4988 }
Marissa Wall61c58622018-07-18 10:12:20 -07004989 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004990 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07004991 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08004992 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004993 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08004994 }
chaviwa76b2712017-09-20 12:02:26 -07004995 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004996 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004997 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004998 Rect getSourceCrop() const override {
4999 if (mCrop.isEmpty()) {
5000 return getBounds();
5001 } else {
5002 return mCrop;
5003 }
5004 }
Robert Carr578038f2018-03-09 12:25:24 -08005005 class ReparentForDrawing {
5006 public:
5007 const sp<Layer>& oldParent;
5008 const sp<Layer>& newParent;
5009
Vishnu Nair4351ad52019-02-11 14:13:02 -08005010 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5011 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005012 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005013 // Compute and cache the bounds for the new parent layer.
5014 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform());
Robert Carr15eae092018-03-23 13:43:53 -07005015 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005016 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005017 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005018 };
5019
5020 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005021 const Rect sourceCrop = getSourceCrop();
5022 // no need to check rotation because there is none
5023 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5024 sourceCrop.height() != getReqHeight();
5025
Robert Carr578038f2018-03-09 12:25:24 -08005026 if (!mChildrenOnly) {
5027 mTransform = mLayer->getTransform().inverse();
5028 drawLayers();
5029 } else {
5030 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005031 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5032 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005033 // In the "childrenOnly" case we reparent the children to a screenshot
5034 // layer which has no properties set and which does not draw.
5035 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005036 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5037 "Screenshot Parent"s, w, h, 0,
5038 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005039
Vishnu Nair4351ad52019-02-11 14:13:02 -08005040 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005041 drawLayers();
5042 }
5043 }
chaviwa76b2712017-09-20 12:02:26 -07005044
chaviwa76b2712017-09-20 12:02:26 -07005045 private:
chaviw7206d492017-11-10 16:16:12 -08005046 const sp<Layer> mLayer;
5047 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005048
Peiyong Linefefaac2018-08-17 12:27:51 -07005049 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005050 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005051
5052 SurfaceFlinger* mFlinger;
5053 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005054 };
5055
Robert Carrc0df3122019-04-11 13:18:21 -07005056 int reqWidth = 0;
5057 int reqHeight = 0;
5058 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005059 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005060 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005061
Robert Carrc0df3122019-04-11 13:18:21 -07005062 {
5063 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005064
Robert Carrc0df3122019-04-11 13:18:21 -07005065 parent = fromHandle(layerHandleBinder);
5066 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5067 ALOGE("captureLayers called with an invalid or removed parent");
5068 return NAME_NOT_FOUND;
5069 }
5070
5071 const int uid = IPCThreadState::self()->getCallingUid();
5072 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5073 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5074 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5075 return PERMISSION_DENIED;
5076 }
5077
5078 if (sourceCrop.width() <= 0) {
5079 crop.left = 0;
5080 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5081 }
5082
5083 if (sourceCrop.height() <= 0) {
5084 crop.top = 0;
5085 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5086 }
5087 reqWidth = crop.width() * frameScale;
5088 reqHeight = crop.height() * frameScale;
5089
5090 for (const auto& handle : excludeHandles) {
5091 sp<Layer> excludeLayer = fromHandle(handle);
5092 if (excludeLayer != nullptr) {
5093 excludeLayers.emplace(excludeLayer);
5094 } else {
5095 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5096 return NAME_NOT_FOUND;
5097 }
5098 }
5099 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005100
Chia-I Wu20261cb2018-08-23 12:55:44 -07005101 // really small crop or frameScale
5102 if (reqWidth <= 0) {
5103 reqWidth = 1;
5104 }
5105 if (reqHeight <= 0) {
5106 reqHeight = 1;
5107 }
5108
Robert Carr866455f2019-04-02 16:28:26 -07005109 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5110 auto traverseLayers = [parent, childrenOnly,
5111 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005112 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5113 if (!layer->isVisible()) {
5114 return;
Robert Carr578038f2018-03-09 12:25:24 -08005115 } else if (childrenOnly && layer == parent.get()) {
5116 return;
chaviwa76b2712017-09-20 12:02:26 -07005117 }
Robert Carr866455f2019-04-02 16:28:26 -07005118
5119 sp<Layer> p = layer;
5120 while (p != nullptr) {
5121 if (excludeLayers.count(p) != 0) {
5122 return;
5123 }
5124 p = p->getParent();
5125 }
5126
chaviwa76b2712017-09-20 12:02:26 -07005127 visitor(layer);
5128 });
5129 };
Robert Carr108b2c72019-04-02 16:32:58 -07005130
5131 bool outCapturedSecureLayers = false;
5132 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5133 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005134}
5135
5136status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5137 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005138 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005139 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005140 bool useIdentityTransform,
5141 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005142 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005143
Peiyong Lin0e003c92018-09-17 11:09:51 -07005144 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005145 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5146 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005147 *outBuffer =
5148 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5149 static_cast<android_pixel_format>(reqPixelFormat), 1,
5150 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005151
Robert Carr108b2c72019-04-02 16:32:58 -07005152 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5153 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005154}
5155
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005156status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5157 TraverseLayersFunction traverseLayers,
5158 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005159 bool useIdentityTransform,
5160 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005161 // This mutex protects syncFd and captureResult for communication of the return values from the
5162 // main thread back to this Binder thread
5163 std::mutex captureMutex;
5164 std::condition_variable captureCondition;
5165 std::unique_lock<std::mutex> captureLock(captureMutex);
5166 int syncFd = -1;
5167 std::optional<status_t> captureResult;
5168
Robert Carr03480e22018-01-04 16:02:06 -08005169 const int uid = IPCThreadState::self()->getCallingUid();
5170 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5171
Dominik Laskowski8c001672018-05-30 16:52:06 -07005172 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005173 // If there is a refresh pending, bug out early and tell the binder thread to try again
5174 // after the refresh.
5175 if (mRefreshPending) {
5176 ATRACE_NAME("Skipping screenshot for now");
5177 std::unique_lock<std::mutex> captureLock(captureMutex);
5178 captureResult = std::make_optional<status_t>(EAGAIN);
5179 captureCondition.notify_one();
5180 return;
5181 }
5182
5183 status_t result = NO_ERROR;
5184 int fd = -1;
5185 {
5186 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005187 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005188 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005189 useIdentityTransform, forSystem, &fd,
5190 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005191 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005192 }
5193
5194 {
5195 std::unique_lock<std::mutex> captureLock(captureMutex);
5196 syncFd = fd;
5197 captureResult = std::make_optional<status_t>(result);
5198 captureCondition.notify_one();
5199 }
5200 });
5201
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005202 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005203 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005204 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005205 while (*captureResult == EAGAIN) {
5206 captureResult.reset();
5207 result = postMessageAsync(message);
5208 if (result != NO_ERROR) {
5209 return result;
5210 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005211 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005212 }
5213 result = *captureResult;
5214 }
5215
5216 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005217 sync_wait(syncFd, -1);
5218 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005219 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005220
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005221 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005222}
5223
chaviwa76b2712017-09-20 12:02:26 -07005224void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005225 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005226 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5227 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005228 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005229
chaviwa76b2712017-09-20 12:02:26 -07005230 const auto reqWidth = renderArea.getReqWidth();
5231 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005232 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005233 const auto transform = renderArea.getTransform();
5234 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005235
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005236 renderengine::DisplaySettings clientCompositionDisplay;
5237 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005238
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005239 // assume that bounds are never offset, and that they are the same as the
5240 // buffer bounds.
5241 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005242 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005243 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005244
5245 // Now take into account the rotation flag. We append a transform that
5246 // rotates the layer stack about the origin, then translate by buffer
5247 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005248 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005249 int displacementX = 0;
5250 int displacementY = 0;
5251 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5252 switch (rotation) {
5253 case ui::Transform::ROT_90:
5254 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005255 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005256 break;
5257 case ui::Transform::ROT_180:
5258 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005259 displacementY = renderArea.getBounds().getWidth();
5260 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005261 break;
5262 case ui::Transform::ROT_270:
5263 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005264 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005265 break;
5266 default:
5267 break;
5268 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005269
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005270 // We need to transform the clipping window into the right spot.
5271 // First, rotate the clipping rectangle by the rotation hint to get the
5272 // right orientation
5273 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5274 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5275 const vec4 rotClipTL = rotMatrix * clipTL;
5276 const vec4 rotClipBR = rotMatrix * clipBR;
5277 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5278 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5279 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5280 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5281
5282 // Now reposition the clipping rectangle with the displacement vector
5283 // computed above.
5284 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005285 clientCompositionDisplay.clip =
5286 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5287 newClipRight + displacementX, newClipBottom + displacementY);
5288
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005289 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005290 clientCompositionDisplay.globalTransform =
5291 clipTransform * clientCompositionDisplay.globalTransform;
5292
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005293 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5294 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005295
chaviw50da5042018-04-09 13:49:37 -07005296 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005297
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005298 renderengine::LayerSettings fillLayer;
5299 fillLayer.source.buffer.buffer = nullptr;
5300 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5301 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5302 fillLayer.alpha = half(alpha);
5303 clientCompositionLayers.push_back(fillLayer);
5304
5305 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005306 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005307 const bool supportProtectedContent = false;
5308 Region clip(renderArea.getBounds());
5309 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5310 clip,
5311 useIdentityTransform,
5312 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5313 renderArea.isSecure(),
5314 supportProtectedContent,
5315 clearRegion,
5316 };
5317 auto result = layer->prepareClientComposition(targetSettings);
5318 if (result) {
5319 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005320 }
chaviwa76b2712017-09-20 12:02:26 -07005321 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005322
5323 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005324 // Use an empty fence for the buffer fence, since we just created the buffer so
5325 // there is no need for synchronization with the GPU.
5326 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005327 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005328 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005329 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005330 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005331
5332 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005333}
5334
chaviwa76b2712017-09-20 12:02:26 -07005335status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5336 TraverseLayersFunction traverseLayers,
5337 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005338 bool useIdentityTransform, bool forSystem,
5339 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005340 ATRACE_CALL();
5341
chaviwa76b2712017-09-20 12:02:26 -07005342 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005343 outCapturedSecureLayers =
5344 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005345 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005346
Robert Carr03480e22018-01-04 16:02:06 -08005347 // We allow the system server to take screenshots of secure layers for
5348 // use in situations like the Screen-rotation animation and place
5349 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005350 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005351 ALOGW("FB is protected: PERMISSION_DENIED");
5352 return PERMISSION_DENIED;
5353 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005354 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005355 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005356}
5357
chaviw95ef3c42019-02-14 10:55:09 -08005358void SurfaceFlinger::setInputWindowsFinished() {
5359 Mutex::Autolock _l(mStateLock);
5360
5361 mPendingSyncInputWindows = false;
5362 mTransactionCV.broadcast();
5363}
chaviw5f21a5e2019-02-14 10:00:34 -08005364
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005365// ---------------------------------------------------------------------------
5366
Dan Stoza412903f2017-04-27 13:42:17 -07005367void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5368 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005369}
5370
Dan Stoza412903f2017-04-27 13:42:17 -07005371void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5372 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005373}
5374
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005375void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005376 const LayerVector::Visitor& visitor) {
5377 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005378 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005379 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005380 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005381 continue;
5382 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005383 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005384 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005385 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005386 return;
5387 }
chaviwa76b2712017-09-20 12:02:26 -07005388 if (!layer->isVisible()) {
5389 return;
5390 }
5391 visitor(layer);
5392 });
5393 }
5394}
5395
Dominik Laskowski22488f62019-03-28 09:53:04 -07005396void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5397 const std::vector<int32_t>& allowedConfigs) {
5398 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08005399 return;
5400 }
5401
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005402 const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
5403 allowedConfigs.end());
5404 if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
5405 return;
5406 }
5407
Ady Abraham838de062019-02-04 10:24:03 -08005408 ALOGV("Updating allowed configs");
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005409 mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
5410
5411 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5412 // that listeners that care about a change in allowed configs can get the notification.
5413 // Giving current ActiveConfig so that most other listeners would just drop the event
5414 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5415 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08005416
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005417 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5418 const auto& type = mScheduler->getPreferredRefreshRateType();
5419 const auto& config = mRefreshRateConfigs->getRefreshRateFromType(type);
5420 if (isDisplayConfigAllowed(config.configId)) {
5421 ALOGV("switching to Scheduler preferred config %d", config.configId);
5422 setDesiredActiveConfig({type, config.configId, Scheduler::ConfigEvent::Changed});
5423 } else {
5424 // Set the highest allowed config by iterating backwards on available refresh rates
5425 const auto& refreshRates = mRefreshRateConfigs->getRefreshRateMap();
5426 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
5427 if (isDisplayConfigAllowed(iter->second.configId)) {
5428 ALOGV("switching to allowed config %d", iter->second.configId);
5429 setDesiredActiveConfig(
5430 {iter->first, iter->second.configId, Scheduler::ConfigEvent::Changed});
5431 break;
5432 }
5433 }
5434 }
5435 } else if (!allowedConfigs.empty()) {
5436 ALOGV("switching to config %d", allowedConfigs[0]);
5437 setDesiredActiveConfig(
5438 {RefreshRateType::DEFAULT, allowedConfigs[0], Scheduler::ConfigEvent::Changed});
5439 }
Ady Abraham838de062019-02-04 10:24:03 -08005440}
5441
Dominik Laskowski22488f62019-03-28 09:53:04 -07005442status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005443 const std::vector<int32_t>& allowedConfigs) {
5444 ATRACE_CALL();
5445
Dominik Laskowski22488f62019-03-28 09:53:04 -07005446 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005447 return BAD_VALUE;
5448 }
5449
Ady Abraham34392f72019-04-10 11:29:27 -07005450 if (mDebugDisplayConfigSetByBackdoor) {
5451 // ignore this request as config is overridden by backdoor
5452 return NO_ERROR;
5453 }
5454
Ady Abraham838de062019-02-04 10:24:03 -08005455 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005456 const auto display = getDisplayDeviceLocked(displayToken);
5457 if (!display) {
5458 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5459 displayToken.get());
5460 } else if (display->isVirtual()) {
5461 ALOGW("Attempt to set allowed display configs for virtual display");
5462 } else {
5463 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5464 }
Ady Abraham838de062019-02-04 10:24:03 -08005465 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005466
Ady Abraham838de062019-02-04 10:24:03 -08005467 return NO_ERROR;
5468}
5469
Dominik Laskowski22488f62019-03-28 09:53:04 -07005470status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005471 std::vector<int32_t>* outAllowedConfigs) {
5472 ATRACE_CALL();
5473
Dominik Laskowski22488f62019-03-28 09:53:04 -07005474 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005475 return BAD_VALUE;
5476 }
5477
Dominik Laskowski22488f62019-03-28 09:53:04 -07005478 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005479
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005480 const auto display = getDisplayDeviceLocked(displayToken);
5481 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005482 return NAME_NOT_FOUND;
5483 }
5484
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005485 if (display->isPrimary()) {
5486 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
5487 }
5488
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005489 return NO_ERROR;
5490}
5491
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005492void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005493 mFlinger->setInputWindowsFinished();
5494}
5495
Robert Carrc0df3122019-04-11 13:18:21 -07005496sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5497 BBinder *b = handle->localBinder();
5498 if (b == nullptr) {
5499 return nullptr;
5500 }
5501 auto it = mLayersByLocalBinderToken.find(b);
5502 if (it != mLayersByLocalBinderToken.end()) {
5503 return it->second.promote();
5504 }
5505 return nullptr;
5506}
5507
Alec Mouri4545a8a2019-08-08 20:05:32 -07005508void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5509 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5510}
5511
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005512} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005513
Mathias Agopian3f844832013-08-07 21:24:32 -07005514#if defined(__gl_h_)
5515#error "don't include gl/gl.h in this file"
5516#endif
5517
5518#if defined(__gl2_h_)
5519#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005520#endif