blob: 004240bd5ba62551f16c1c7622998a9606ae1920 [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 mPendingSyncInputWindows(false) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800264
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700265SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800266 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800267
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900268 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800269
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900270 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700271
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900272 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700273
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900274 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800275
Steven Thomas050b2c82017-03-06 11:45:16 -0800276 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900277 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800278
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900279 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800280
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900281 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700282
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900283 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600284
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900285 mDefaultCompositionDataspace =
286 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700287 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
288 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900289 defaultCompositionDataspace = mDefaultCompositionDataspace;
290 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
291 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
292 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
293 wideColorGamutCompositionPixelFormat =
294 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700295
Yichi Chenda901bf2019-06-28 14:58:27 +0800296 mColorSpaceAgnosticDataspace =
297 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
298
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900299 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800300
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900301 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
302 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
303 switch (tmpPrimaryDisplayOrientation) {
304 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700305 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800306 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900307 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700308 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800309 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900310 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700311 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800312 break;
313 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700314 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800315 break;
316 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700317 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800318
Sundong Ahn85131bd2019-02-18 15:51:53 +0900319 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800320
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800321 // debugging stuff...
322 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700323
Mathias Agopianb4b17302013-03-20 18:36:41 -0700324 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700325 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700326
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800327 property_get("debug.sf.showupdates", value, "0");
328 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700329
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700330 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000331
332 // DDMS debugging deprecated (b/120782499)
333 property_get("debug.sf.ddms", value, "0");
334 int debugDdms = atoi(value);
335 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700336
337 property_get("debug.sf.disable_backpressure", value, "0");
338 mPropagateBackpressure = !atoi(value);
339 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700340
Ady Abrahamadb9a992019-09-19 21:21:55 +0000341 property_get("debug.sf.enable_gl_backpressure", value, "0");
342 mPropagateBackpressureClientComposition = atoi(value);
343 ALOGI_IF(mPropagateBackpressureClientComposition,
344 "Enabling backpressure propagation for Client Composition");
345
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800346 property_get("debug.sf.enable_hwc_vds", value, "0");
347 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800348 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800349
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800350 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800351 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800352 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700353
Yiwei Zhang243b3782018-05-15 17:40:04 -0700354 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700355 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
356 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
357
Dan Stozaec460082018-12-17 15:35:09 -0800358 property_get("debug.sf.luma_sampling", value, "1");
359 mLumaSampling = atoi(value);
360
Romain Guy11d63f42017-07-20 12:47:14 -0700361 // We should be reading 'persist.sys.sf.color_saturation' here
362 // but since /data may be encrypted, we need to wait until after vold
363 // comes online to attempt to read the property. The property is
364 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800365
366 if (useTrebleTestingOverride()) {
367 // Without the override SurfaceFlinger cannot connect to HIDL
368 // services that are not listed in the manifests. Considered
369 // deriving the setting from the set service name, but it
370 // would be brittle if the name that's not 'default' is used
371 // for production purposes later on.
372 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
373 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800374}
375
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800376void SurfaceFlinger::onFirstRef()
377{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800378 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800379}
380
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700381SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800382
Dan Stozac7014012014-02-14 15:03:43 -0800383void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800384{
385 // the window manager died on us. prepare its eulogy.
386
Andy McFadden13a082e2012-08-24 10:16:42 -0700387 // restore initial conditions (default device unblank, etc)
388 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800389
390 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700391 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800392}
393
Robert Carr1db73f62016-12-21 12:58:51 -0800394static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700395 status_t err = client->initCheck();
396 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800397 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800398 }
Robert Carr1db73f62016-12-21 12:58:51 -0800399 return nullptr;
400}
401
402sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
403 return initClient(new Client(this));
404}
405
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700406sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
407 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700408{
409 class DisplayToken : public BBinder {
410 sp<SurfaceFlinger> flinger;
411 virtual ~DisplayToken() {
412 // no more references, this display must be terminated
413 Mutex::Autolock _l(flinger->mStateLock);
414 flinger->mCurrentState.displays.removeItem(this);
415 flinger->setTransactionFlags(eDisplayTransactionNeeded);
416 }
417 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700418 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700419 : flinger(flinger) {
420 }
421 };
422
423 sp<BBinder> token = new DisplayToken(this);
424
425 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700426 // Display ID is assigned when virtual display is allocated by HWC.
427 DisplayDeviceState state;
428 state.isSecure = secure;
429 state.displayName = displayName;
430 mCurrentState.displays.add(token, state);
431 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700432 return token;
433}
434
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700435void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700436 Mutex::Autolock _l(mStateLock);
437
Dominik Laskowski075d3172018-05-24 15:50:06 -0700438 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
439 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700440 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700441 return;
442 }
443
Dominik Laskowski075d3172018-05-24 15:50:06 -0700444 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
445 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700446 ALOGE("destroyDisplay called for non-virtual display");
447 return;
448 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700449 mInterceptor->saveDisplayDeletion(state.sequenceId);
450 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700451 setTransactionFlags(eDisplayTransactionNeeded);
452}
453
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800454std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
455 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700456
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800457 const auto internalDisplayId = getInternalDisplayIdLocked();
458 if (!internalDisplayId) {
459 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700460 }
461
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800462 std::vector<PhysicalDisplayId> displayIds;
463 displayIds.reserve(mPhysicalDisplayTokens.size());
464 displayIds.push_back(internalDisplayId->value);
465
466 for (const auto& [id, token] : mPhysicalDisplayTokens) {
467 if (id != *internalDisplayId) {
468 displayIds.push_back(id.value);
469 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700470 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700471
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800472 return displayIds;
473}
474
475sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
476 Mutex::Autolock lock(mStateLock);
477 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700478}
479
Ady Abraham37965d42018-11-01 13:43:32 -0700480status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
481 if (!outGetColorManagement) {
482 return BAD_VALUE;
483 }
484 *outGetColorManagement = useColorManagement;
485 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700486}
487
Lloyd Pique441d5042018-10-18 16:49:51 -0700488HWComposer& SurfaceFlinger::getHwComposer() const {
489 return mCompositionEngine->getHwComposer();
490}
491
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700492renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
493 return mCompositionEngine->getRenderEngine();
494}
495
Lloyd Pique70d91362018-10-18 16:02:55 -0700496compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
497 return *mCompositionEngine.get();
498}
499
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800500void SurfaceFlinger::bootFinished()
501{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700502 if (mStartPropertySetThread->join() != NO_ERROR) {
503 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800504 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800505 const nsecs_t now = systemTime();
506 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000507 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700508
Mikael Pessa90092f42019-08-26 17:22:04 -0700509 mFrameTracer->initialize();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700510
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700511 // wait patiently for the window manager death
512 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700513 mWindowManager = defaultServiceManager()->getService(name);
514 if (mWindowManager != 0) {
515 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700516 }
Robert Carr720e5062018-07-30 17:45:14 -0700517 sp<IBinder> input(defaultServiceManager()->getService(
518 String16("inputflinger")));
519 if (input == nullptr) {
520 ALOGE("Failed to link to input service");
521 } else {
522 mInputFlinger = interface_cast<IInputFlinger>(input);
523 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700524
Steven Thomas050b2c82017-03-06 11:45:16 -0800525 if (mVrFlinger) {
526 mVrFlinger->OnBootFinished();
527 }
528
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700529 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700530 // formerly we would just kill the process, but we now ask it to exit so it
531 // can choose where to stop the animation.
532 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700533
534 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
535 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
536 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700537
Ana Krulecbd6654b2019-02-15 15:18:15 -0800538 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800539 readPersistentProperties();
540 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800541
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700542 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
543 // set the refresh rate according to the policy
Ady Abraham2139f732019-11-13 18:56:40 -0800544 const auto& performanceRefreshRate = mRefreshRateConfigs->getMaxRefreshRateByPolicy();
545 changeRefreshRateLocked(performanceRefreshRate, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800546 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800547 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800548}
549
Dan Stoza436ccf32018-06-21 12:10:12 -0700550uint32_t SurfaceFlinger::getNewTexture() {
551 {
552 std::lock_guard lock(mTexturePoolMutex);
553 if (!mTexturePool.empty()) {
554 uint32_t name = mTexturePool.back();
555 mTexturePool.pop_back();
556 ATRACE_INT("TexturePoolSize", mTexturePool.size());
557 return name;
558 }
559
560 // The pool was too small, so increase it for the future
561 ++mTexturePoolSize;
562 }
563
564 // The pool was empty, so we need to get a new texture name directly using a
565 // blocking call to the main thread
566 uint32_t name = 0;
567 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
568 return name;
569}
570
Mathias Agopian3f844832013-08-07 21:24:32 -0700571void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700572 std::lock_guard lock(mTexturePoolMutex);
573 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
574 // to actually delete this or not based on mTexturePoolSize
575 mTexturePool.push_back(texture);
576 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700577}
578
Wei Wangf9b05ee2017-07-19 20:59:39 -0700579// Do not call property_set on main thread which will be blocked by init
580// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700581void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700582 ALOGI( "SurfaceFlinger's main thread ready to run. "
583 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700584 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800585
Steven Thomasb02664d2017-07-26 18:48:28 -0700586 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700587 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800588 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700589 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
590 renderengine::RenderEngineCreationArgs::Builder()
591 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
592 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
593 .setUseColorManagerment(useColorManagement)
594 .setEnableProtectedContext(enable_protected_contents(false))
595 .setPrecacheToneMapperShaderOnly(false)
596 .setContextPriority(useContextPriority
597 ? renderengine::RenderEngine::ContextPriority::HIGH
598 : renderengine::RenderEngine::ContextPriority::MEDIUM)
599 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800600 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700601
602 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
603 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700604 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
605 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800606 // Process any initial hotplug and resulting display changes.
607 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700608 const auto display = getDefaultDisplayDeviceLocked();
609 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700610 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700611 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800612
Steven Thomas050b2c82017-03-06 11:45:16 -0800613 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700614 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700615 // This callback is called from the vr flinger dispatch thread. We
616 // need to call signalTransaction(), which requires holding
617 // mStateLock when we're not on the main thread. Acquiring
618 // mStateLock from the vr flinger dispatch thread might trigger a
619 // deadlock in surface flinger (see b/66916578), so post a message
620 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700621 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700622 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
623 mVrFlingerRequestsDisplay = requestDisplay;
624 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700625 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800626 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700627 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
628 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700629 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700630 .value_or(0),
631 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800632 if (!mVrFlinger) {
633 ALOGE("Failed to start vrflinger");
634 }
635 }
636
Mathias Agopian92a979a2012-08-02 18:32:23 -0700637 // initialize our drawing state
638 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700639
Andy McFadden13a082e2012-08-24 10:16:42 -0700640 // set initial conditions (e.g. unblank default device)
641 initializeDisplays();
642
Steven Thomas137d4bc2019-07-25 16:55:14 -0700643 char primeShaderCache[PROPERTY_VALUE_MAX];
644 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
645 if (atoi(primeShaderCache)) {
646 getRenderEngine().primeCache();
647 }
Dan Stoza4e637772016-07-28 13:31:51 -0700648
Wei Wangf9b05ee2017-07-19 20:59:39 -0700649 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700650
651 const bool presentFenceReliable =
652 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
653 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700654
655 if (mStartPropertySetThread->Start() != NO_ERROR) {
656 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800657 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800658
Dan Stoza9e56aa02015-11-02 13:00:03 -0800659 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700660}
661
Romain Guy11d63f42017-07-20 12:47:14 -0700662void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700663 Mutex::Autolock _l(mStateLock);
664
Romain Guy11d63f42017-07-20 12:47:14 -0700665 char value[PROPERTY_VALUE_MAX];
666
667 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800668 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700669 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800670 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100671
672 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700673 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800674
675 property_get("persist.sys.sf.color_mode", value, "0");
676 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700677}
678
Mathias Agopiana67e4182012-06-19 17:26:12 -0700679void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800680 // Start boot animation service by setting a property mailbox
681 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700682 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800683 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700684 if (mStartPropertySetThread->join() != NO_ERROR) {
685 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800686 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700687}
688
Mathias Agopian875d8e12013-06-07 15:35:48 -0700689size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700690 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700691}
692
Mathias Agopian875d8e12013-06-07 15:35:48 -0700693size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700694 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700695}
696
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800697// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800698
Jamie Gennis582270d2011-08-17 18:19:00 -0700699bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800700 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800701 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800702 return authenticateSurfaceTextureLocked(bufferProducer);
703}
704
705bool SurfaceFlinger::authenticateSurfaceTextureLocked(
706 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800707 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800708 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800709}
710
Brian Anderson6b376712017-04-04 10:51:39 -0700711status_t SurfaceFlinger::getSupportedFrameTimestamps(
712 std::vector<FrameEvent>* outSupported) const {
713 *outSupported = {
714 FrameEvent::REQUESTED_PRESENT,
715 FrameEvent::ACQUIRE,
716 FrameEvent::LATCH,
717 FrameEvent::FIRST_REFRESH_START,
718 FrameEvent::LAST_REFRESH_START,
719 FrameEvent::GPU_COMPOSITION_DONE,
720 FrameEvent::DEQUEUE_READY,
721 FrameEvent::RELEASE,
722 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700723 ConditionalLock _l(mStateLock,
724 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700725 if (!getHwComposer().hasCapability(
726 HWC2::Capability::PresentFenceIsNotReliable)) {
727 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
728 }
729 return NO_ERROR;
730}
731
Dominik Laskowski22488f62019-03-28 09:53:04 -0700732status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
733 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700734 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700735 return BAD_VALUE;
736 }
737
Dominik Laskowski22488f62019-03-28 09:53:04 -0700738 Mutex::Autolock lock(mStateLock);
739
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800740 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700741 if (!displayId) {
742 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700743 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700744
Mathias Agopian8b736f12012-08-13 17:54:26 -0700745 // TODO: Not sure if display density should handled by SF any longer
746 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700747 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700748 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700749 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800750 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700751 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700752 }
753 return density;
754 }
755 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700756 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700757 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700758 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700759 return getDensityFromProperty("ro.sf.lcd_density"); }
760 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700761
Dan Stoza7f7da322014-05-02 15:26:25 -0700762 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700763
Dominik Laskowski075d3172018-05-24 15:50:06 -0700764 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700765 DisplayInfo info = DisplayInfo();
766
Dan Stoza9e56aa02015-11-02 13:00:03 -0800767 float xdpi = hwConfig->getDpiX();
768 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700769
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700770 info.w = hwConfig->getWidth();
771 info.h = hwConfig->getHeight();
772 // Default display viewport to display width and height
773 info.viewportW = info.w;
774 info.viewportH = info.h;
775
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800776 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700777 // The density of the device is provided by a build property
778 float density = Density::getBuildDensity() / 160.0f;
779 if (density == 0) {
780 // the build doesn't provide a density -- this is wrong!
781 // use xdpi instead
782 ALOGE("ro.sf.lcd_density must be defined as a build property");
783 density = xdpi / 160.0f;
784 }
785 if (Density::getEmuDensity()) {
786 // if "qemu.sf.lcd_density" is specified, it overrides everything
787 xdpi = ydpi = density = Density::getEmuDensity();
788 density /= 160.0f;
789 }
790 info.density = density;
791
792 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700793 const auto display = getDefaultDisplayDeviceLocked();
794 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700795
796 // This is for screenrecord
797 const Rect viewport = display->getViewport();
798 if (viewport.isValid()) {
799 info.viewportW = uint32_t(viewport.getWidth());
800 info.viewportH = uint32_t(viewport.getHeight());
801 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700802 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700803 } else {
804 // TODO: where should this value come from?
805 static const int TV_DENSITY = 213;
806 info.density = TV_DENSITY / 160.0f;
807 info.orientation = 0;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700808
809 const auto display = getDisplayDeviceLocked(displayToken);
810 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700811 }
812
Dan Stoza7f7da322014-05-02 15:26:25 -0700813 info.xdpi = xdpi;
814 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800815 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham2139f732019-11-13 18:56:40 -0800816
Ady Abraham9e16a482019-12-03 17:19:41 -0800817 const auto offset = mPhaseConfiguration->getOffsetsForRefreshRate(info.fps);
Ady Abraham796beb02019-04-11 15:23:07 -0700818 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800819
Andy McFadden91b2ca82014-06-13 14:04:23 -0700820 // This is how far in advance a buffer must be queued for
821 // presentation at a given time. If you want a buffer to appear
822 // on the screen at time N, you must submit the buffer before
823 // (N - presentationDeadline).
824 //
825 // Normally it's one full refresh period (to give SF a chance to
826 // latch the buffer), but this can be reduced by configuring a
827 // DispSync offset. Any additional delays introduced by the hardware
828 // composer or panel must be accounted for here.
829 //
830 // We add an additional 1ms to allow for processing time and
831 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700832 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700833
834 // All non-virtual displays are currently considered secure.
835 info.secure = true;
836
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800837 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700838 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800839 std::swap(info.w, info.h);
840 }
841
Michael Wright28f24d02016-07-12 13:30:53 -0700842 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700843 }
844
Dan Stoza7f7da322014-05-02 15:26:25 -0700845 return NO_ERROR;
846}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700847
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700848status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
849 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700850 return BAD_VALUE;
851 }
852
Ana Krulecc2870422019-01-29 19:00:58 -0800853 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700854 return NO_ERROR;
855}
856
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700857int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
858 const auto display = getDisplayDevice(displayToken);
859 if (!display) {
860 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800861 return BAD_VALUE;
862 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700863
Steven Thomasc9098452019-09-30 17:15:05 -0700864 if (display->isPrimary()) {
865 std::lock_guard<std::mutex> lock(mActiveConfigLock);
866 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800867 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700868 }
Steven Thomasc9098452019-09-30 17:15:05 -0700869 }
Ady Abraham2139f732019-11-13 18:56:40 -0800870
871 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700872}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700873
Ady Abraham03b02dd2019-03-21 15:40:11 -0700874void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800875 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800876 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
877 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800878
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800879 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800880 // config twice. However event generation config might have changed so we need to update it
881 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800882 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700883 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
884 mDesiredActiveConfig = info;
885 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800886
887 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800888 // This will trigger HWC refresh without resetting the idle timer.
889 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700890 // Start receiving vsync samples now, so that we can detect a period
891 // switch.
892 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700893 // As we called to set period, we will call to onRefreshRateChangeCompleted once
894 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700895 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800896
Ady Abraham9e16a482019-12-03 17:19:41 -0800897 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
898 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800899 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800900 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700901
902 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800903 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700904 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800905}
906
907status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
908 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800909
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100910 if (!displayToken) {
911 return BAD_VALUE;
912 }
Ady Abraham838de062019-02-04 10:24:03 -0800913
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100914 status_t result = NO_ERROR;
915
916 postMessageSync(new LambdaMessage([&]() {
917 const auto display = getDisplayDeviceLocked(displayToken);
918 if (!display) {
919 ALOGE("Attempt to set allowed display configs for invalid display token %p",
920 displayToken.get());
921 result = BAD_VALUE;
922 } else if (display->isVirtual()) {
923 ALOGW("Attempt to set allowed display configs for virtual display");
924 result = BAD_VALUE;
925 } else {
926 HwcConfigIndexType config(mode);
927 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
928 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
929 refreshRate.fps);
930 }
931 }));
932
933 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800934}
935
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800936void SurfaceFlinger::setActiveConfigInternal() {
937 ATRACE_CALL();
938
Dominik Laskowski22488f62019-03-28 09:53:04 -0700939 const auto display = getDefaultDisplayDeviceLocked();
940 if (!display) {
941 return;
942 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800943
Dominik Laskowski22488f62019-03-28 09:53:04 -0700944 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800945 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700946 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800947 display->setActiveConfig(mUpcomingActiveConfig.configId);
948
Ady Abraham2139f732019-11-13 18:56:40 -0800949 auto refreshRate =
950 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800951 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
952 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800953 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700954
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800955 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700956 const nsecs_t vsyncPeriod =
957 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
958 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800959 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700960 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800961 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800962}
963
Ady Abraham53852a52019-05-28 18:07:44 -0700964void SurfaceFlinger::desiredActiveConfigChangeDone() {
965 std::lock_guard<std::mutex> lock(mActiveConfigLock);
966 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
967 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700968
969 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham2139f732019-11-13 18:56:40 -0800970 auto refreshRate =
971 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800972 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
973 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700974}
975
Dominik Laskowski22488f62019-03-28 09:53:04 -0700976bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800977 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800978 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -0800979 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700980 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800981 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700982 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800983 return true;
984 }
985
986 // We received the present fence from the HWC, so we assume it successfully updated
987 // the config, hence we update SF.
988 mCheckPendingFence = false;
989 setActiveConfigInternal();
990 }
991
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800992 // Store the local variable to release the lock.
993 ActiveConfigInfo desiredActiveConfig;
994 {
995 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800996 if (!mDesiredActiveConfigChanged) {
997 return false;
998 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800999 desiredActiveConfig = mDesiredActiveConfig;
1000 }
1001
Ady Abraham2139f732019-11-13 18:56:40 -08001002 auto refreshRate =
1003 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
1004 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
1005 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -07001006 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001007 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
1008 // display is not valid or we are already in the requested mode
1009 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -07001010 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001011 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001012 }
Ady Abrahamb838aed2019-02-12 15:30:16 -08001013
Ady Abraham838de062019-02-04 10:24:03 -08001014 // Desired active config was set, it is different than the config currently in use, however
1015 // allowed configs might have change by the time we process the refresh.
1016 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -07001017 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001018 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001019 return false;
1020 }
Alec Mouri7f015182019-07-11 13:56:22 -07001021
Ady Abrahamb838aed2019-02-12 15:30:16 -08001022 mUpcomingActiveConfig = desiredActiveConfig;
1023 const auto displayId = display->getId();
1024 LOG_ALWAYS_FATAL_IF(!displayId);
1025
Ady Abraham2139f732019-11-13 18:56:40 -08001026 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001027
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001028 // TODO(b/142753666) use constrains
1029 HWC2::VsyncPeriodChangeConstraints constraints;
1030 constraints.desiredTimeNanos = systemTime();
1031 constraints.seamlessRequired = false;
1032
1033 HWC2::VsyncPeriodChangeTimeline outTimeline;
1034 auto status =
1035 getHwComposer().setActiveConfigWithConstraints(*displayId,
1036 mUpcomingActiveConfig.configId.value(),
1037 constraints, &outTimeline);
1038 if (status != NO_ERROR) {
1039 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1040 return false;
1041 }
1042
1043 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1044 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001045 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001046 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001047}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001048
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001049status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1050 Vector<ColorMode>* outColorModes) {
1051 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001052 return BAD_VALUE;
1053 }
1054
Peiyong Lina52f0292018-03-14 17:26:31 -07001055 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001056 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001057 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001058 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1059
1060 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1061 if (!displayId) {
1062 return NAME_NOT_FOUND;
1063 }
1064
Dominik Laskowski075d3172018-05-24 15:50:06 -07001065 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001066 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001067 }
Michael Wright28f24d02016-07-12 13:30:53 -07001068 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001069
1070 // If it's built-in display and the configuration claims it's not wide color capable,
1071 // filter out all wide color modes. The typical reason why this happens is that the
1072 // hardware is not good enough to support GPU composition of wide color, and thus the
1073 // OEMs choose to disable this capability.
1074 if (isInternalDisplay && !hasWideColorDisplay) {
1075 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1076 isWideColorMode);
1077 } else {
1078 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1079 }
Michael Wright28f24d02016-07-12 13:30:53 -07001080
1081 return NO_ERROR;
1082}
1083
Daniel Solomon42d04562019-01-20 21:03:19 -08001084status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1085 ui::DisplayPrimaries &primaries) {
1086 if (!displayToken) {
1087 return BAD_VALUE;
1088 }
1089
1090 // Currently we only support this API for a single internal display.
1091 if (getInternalDisplayToken() != displayToken) {
1092 return BAD_VALUE;
1093 }
1094
1095 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1096 return NO_ERROR;
1097}
1098
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001099ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1100 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001101 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001102 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001103 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001104}
1105
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001106status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001107 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001108 Vector<ColorMode> modes;
1109 getDisplayColorModes(displayToken, &modes);
1110 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1111 if (mode < ColorMode::NATIVE || !exists) {
1112 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1113 decodeColorMode(mode).c_str(), mode, displayToken.get());
1114 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001115 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001116 const auto display = getDisplayDevice(displayToken);
1117 if (!display) {
1118 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1119 decodeColorMode(mode).c_str(), mode, displayToken.get());
1120 } else if (display->isVirtual()) {
1121 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1122 decodeColorMode(mode).c_str(), mode);
1123 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001124 display->getCompositionDisplay()->setColorProfile(
1125 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1126 RenderIntent::COLORIMETRIC,
1127 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001128 }
1129 }));
1130
Michael Wright28f24d02016-07-12 13:30:53 -07001131 return NO_ERROR;
1132}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001133
Galia Peycheva5492cb52019-10-30 14:13:16 +01001134status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1135 bool* outSupport) const {
1136 Mutex::Autolock _l(mStateLock);
1137
1138 if (!displayToken) {
1139 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1140 return BAD_VALUE;
1141 }
1142 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1143 if (!displayId) {
1144 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1145 displayToken.get());
1146 return NAME_NOT_FOUND;
1147 }
1148 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1149 HWC2::DisplayCapability::AutoLowLatencyMode);
1150 return NO_ERROR;
1151}
1152
1153void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1154 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1155}
1156
1157void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1158 if (!displayToken) {
1159 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1160 return;
1161 }
1162 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1163 if (!displayId) {
1164 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1165 displayToken.get());
1166 return;
1167 }
1168
1169 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1170}
1171
1172status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1173 bool* outSupport) const {
1174 Mutex::Autolock _l(mStateLock);
1175
1176 if (!displayToken) {
1177 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1178 return BAD_VALUE;
1179 }
1180 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1181 if (!displayId) {
1182 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1183 displayToken.get());
1184 return NAME_NOT_FOUND;
1185 }
1186
1187 std::vector<HWC2::ContentType> outSupportedContentTypes;
1188 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1189 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1190 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1191 return NO_ERROR;
1192}
1193
1194void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1195 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1196}
1197
1198void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1199 if (!displayToken) {
1200 ALOGE("setGameContentType() failed. Missing display token.");
1201 return;
1202 }
1203 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1204 if (!displayId) {
1205 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1206 displayToken.get());
1207 return;
1208 }
1209
1210 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1211 getHwComposer().setContentType(*displayId, type);
1212}
1213
Svetoslavd85084b2014-03-20 10:28:31 -07001214status_t SurfaceFlinger::clearAnimationFrameStats() {
1215 Mutex::Autolock _l(mStateLock);
1216 mAnimFrameTracker.clearStats();
1217 return NO_ERROR;
1218}
1219
1220status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1221 Mutex::Autolock _l(mStateLock);
1222 mAnimFrameTracker.getStats(outStats);
1223 return NO_ERROR;
1224}
1225
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001226status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1227 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001228 Mutex::Autolock _l(mStateLock);
1229
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001230 const auto display = getDisplayDeviceLocked(displayToken);
1231 if (!display) {
1232 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001233 return BAD_VALUE;
1234 }
1235
Peiyong Linfb069302018-04-25 14:34:31 -07001236 // At this point the DisplayDeivce should already be set up,
1237 // meaning the luminance information is already queried from
1238 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001239 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001240 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1241 capabilities.getDesiredMaxLuminance(),
1242 capabilities.getDesiredMaxAverageLuminance(),
1243 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001244
1245 return NO_ERROR;
1246}
1247
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001248status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1249 ui::PixelFormat* outFormat,
1250 ui::Dataspace* outDataspace,
1251 uint8_t* outComponentMask) const {
1252 if (!outFormat || !outDataspace || !outComponentMask) {
1253 return BAD_VALUE;
1254 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001255 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001256 if (!display || !display->getId()) {
1257 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1258 return BAD_VALUE;
1259 }
1260 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1261 outDataspace, outComponentMask);
1262}
1263
Kevin DuBois74e53772018-11-19 10:52:38 -08001264status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1265 bool enable, uint8_t componentMask,
1266 uint64_t maxFrames) const {
1267 const auto display = getDisplayDevice(displayToken);
1268 if (!display || !display->getId()) {
1269 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1270 return BAD_VALUE;
1271 }
1272
1273 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1274 componentMask, maxFrames);
1275}
1276
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001277status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1278 uint64_t maxFrames, uint64_t timestamp,
1279 DisplayedFrameStats* outStats) const {
1280 const auto display = getDisplayDevice(displayToken);
1281 if (!display || !display->getId()) {
1282 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1283 return BAD_VALUE;
1284 }
1285
1286 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1287 outStats);
1288}
1289
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001290status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1291 if (!outSupported) {
1292 return BAD_VALUE;
1293 }
1294 *outSupported = getRenderEngine().supportsProtectedContent();
1295 return NO_ERROR;
1296}
1297
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001298status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1299 bool* outIsWideColorDisplay) const {
1300 if (!displayToken || !outIsWideColorDisplay) {
1301 return BAD_VALUE;
1302 }
1303 Mutex::Autolock _l(mStateLock);
1304 const auto display = getDisplayDeviceLocked(displayToken);
1305 if (!display) {
1306 return BAD_VALUE;
1307 }
Peiyong Linff84a152019-05-17 18:36:19 -07001308
1309 // Use hasWideColorDisplay to override built-in display.
1310 const auto displayId = display->getId();
1311 if (displayId && displayId == getInternalDisplayIdLocked()) {
1312 *outIsWideColorDisplay = hasWideColorDisplay;
1313 return NO_ERROR;
1314 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001315 *outIsWideColorDisplay = display->hasWideColorGamut();
1316 return NO_ERROR;
1317}
1318
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001319status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001320 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001321 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001322
Dominik Laskowski6505f792019-09-18 11:10:05 -07001323 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1324 mEventQueue->setEventConnection(
1325 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001326 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001327 }));
1328
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001329 return NO_ERROR;
1330}
1331
1332status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001333 Mutex::Autolock lock(mStateLock);
1334 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001335}
1336
Lloyd Pique755e3192018-01-31 16:46:15 -08001337status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1338 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001339 // Try to acquire a lock for 1s, fail gracefully
1340 const status_t err = mStateLock.timedLock(s2ns(1));
1341 const bool locked = (err == NO_ERROR);
1342 if (!locked) {
1343 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1344 return TIMED_OUT;
1345 }
1346
1347 outLayers->clear();
1348 mCurrentState.traverseInZOrder([&](Layer* layer) {
1349 outLayers->push_back(layer->getLayerDebugInfo());
1350 });
1351
1352 mStateLock.unlock();
1353 return NO_ERROR;
1354}
1355
Peiyong Linc6780972018-10-28 15:24:08 -07001356status_t SurfaceFlinger::getCompositionPreference(
1357 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1358 Dataspace* outWideColorGamutDataspace,
1359 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001360 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001361 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001362 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001363 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001364 return NO_ERROR;
1365}
1366
Dan Stozaec460082018-12-17 15:35:09 -08001367status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1368 const sp<IBinder>& stopLayerHandle,
1369 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001370 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001371 return BAD_VALUE;
1372 }
1373 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001374 return NO_ERROR;
1375}
1376
Dan Stozaec460082018-12-17 15:35:09 -08001377status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001378 if (!listener) {
1379 return BAD_VALUE;
1380 }
Dan Stozaec460082018-12-17 15:35:09 -08001381 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001382 return NO_ERROR;
1383}
Dan Gittik57e63c52019-01-18 16:37:54 +00001384
1385status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1386 bool* outSupport) const {
1387 if (!displayToken || !outSupport) {
1388 return BAD_VALUE;
1389 }
1390 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1391 if (!displayId) {
1392 return NAME_NOT_FOUND;
1393 }
1394 *outSupport =
1395 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1396 return NO_ERROR;
1397}
1398
1399status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1400 float brightness) const {
1401 if (!displayToken) {
1402 return BAD_VALUE;
1403 }
1404 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1405 if (!displayId) {
1406 return NAME_NOT_FOUND;
1407 }
1408 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1409}
1410
Ady Abraham8532d012019-05-08 14:50:56 -07001411status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1412 PowerHint powerHint = static_cast<PowerHint>(hintId);
1413
1414 if (powerHint == PowerHint::INTERACTION) {
1415 mScheduler->notifyTouchEvent();
1416 }
1417
1418 return NO_ERROR;
1419}
1420
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001421// ----------------------------------------------------------------------------
1422
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001423sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001424 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001425 const auto& handle =
1426 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001427
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001428 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001429}
1430
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001431// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001432
1433void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001434 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001435}
1436
1437void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001438 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001439 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001440}
1441
1442void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001443 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001444 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001445}
1446
1447void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001448 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001449 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001450}
1451
1452status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001453 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001454 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001455}
1456
1457status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001458 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001459 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001460 if (res == NO_ERROR) {
1461 msg->wait();
1462 }
1463 return res;
1464}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001465
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001466void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001467 do {
1468 waitForEvent();
1469 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001470}
1471
Dominik Laskowski83b88212018-12-11 13:34:06 -08001472nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001473 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001474 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1475 return 0;
1476 }
1477
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001478 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001479}
1480
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001481void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001482 int64_t timestamp,
1483 std::optional<hwc2_vsync_period_t> /*vsyncPeriod*/) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001484 ATRACE_NAME("SF onVsync");
1485
Ady Abraham7159f572019-10-11 11:10:18 -07001486 // TODO(b/140201379): use vsyncPeriod in the new DispSync
1487
Steven Thomas3cfac282017-02-06 12:29:30 -08001488 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001489 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001490 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001491 return;
1492 }
1493
Dominik Laskowski075d3172018-05-24 15:50:06 -07001494 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001495 return;
1496 }
1497
Dominik Laskowski075d3172018-05-24 15:50:06 -07001498 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001499 // For now, we don't do anything with external display vsyncs.
1500 return;
1501 }
1502
Alec Mourif8e689c2019-05-20 18:32:22 -07001503 bool periodFlushed = false;
1504 mScheduler->addResyncSample(timestamp, &periodFlushed);
1505 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001506 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001507 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001508}
1509
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001510void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001511 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1512 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001513}
1514
Ady Abraham2139f732019-11-13 18:56:40 -08001515bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001516 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001517}
1518
Ady Abraham2139f732019-11-13 18:56:40 -08001519void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1520 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001521 const auto display = getDefaultDisplayDeviceLocked();
1522 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001523 return;
1524 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001525 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001526
Ana Krulec7d1d6832018-12-27 11:10:09 -08001527 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001528 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1529 ALOGV("Skipping config %d as it is not part of allowed configs",
1530 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001531 return;
1532 }
1533
Ady Abraham2139f732019-11-13 18:56:40 -08001534 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001535}
1536
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001537void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001538 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001539 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001540 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001541
Lloyd Piqueba04e622017-12-14 17:11:26 -08001542 // Ignore events that do not have the right sequenceId.
1543 if (sequenceId != getBE().mComposerSequenceId) {
1544 return;
1545 }
1546
Steven Thomasb02664d2017-07-26 18:48:28 -07001547 // Only lock if we're not on the main thread. This function is normally
1548 // called on a hwbinder thread, but for the primary display it's called on
1549 // the main thread with the state lock already held, so don't attempt to
1550 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001551 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001552
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001553 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001554
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001555 if (std::this_thread::get_id() == mMainThreadId) {
1556 // Process all pending hot plug events immediately if we are on the main thread.
1557 processDisplayHotplugEventsLocked();
1558 }
1559
Lloyd Piqueba04e622017-12-14 17:11:26 -08001560 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001561}
1562
Ady Abraham7159f572019-10-11 11:10:18 -07001563void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001564 int32_t sequenceId, hwc2_display_t /*display*/,
1565 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1566 Mutex::Autolock lock(mStateLock);
1567 if (sequenceId != getBE().mComposerSequenceId) {
1568 return;
1569 }
1570 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001571}
1572
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001573void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1574 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1575 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1576}
1577
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001578void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001579 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001580 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001581 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001582 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001583 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001584}
1585
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001586void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001587 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001588
1589 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1590 // display power state.
1591 postMessageAsync(new LambdaMessage(
1592 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1593}
1594
1595void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1596 ATRACE_CALL();
1597
Ady Abraham27c70212019-06-11 10:52:26 -07001598 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1599
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001600 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001601 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1602 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001603 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001604 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001605 }
Mathias Agopian86303202012-07-24 22:46:10 -07001606}
1607
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001608// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001609void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001610 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001611 // Clear the drawing state so that the logic inside of
1612 // handleTransactionLocked will fire. It will determine the delta between
1613 // mCurrentState and mDrawingState and re-apply all changes when we make the
1614 // transition.
1615 mDrawingState.displays.clear();
1616 mDisplays.clear();
1617}
1618
Steven Thomas050b2c82017-03-06 11:45:16 -08001619void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001620 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001621 if (!mVrFlinger)
1622 return;
1623 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001624 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001625 return;
1626 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001627
Lloyd Pique441d5042018-10-18 16:49:51 -07001628 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001629 ALOGE("Vr flinger is only supported for remote hardware composer"
1630 " service connections. Ignoring request to transition to vr"
1631 " flinger.");
1632 mVrFlingerRequestsDisplay = false;
1633 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001634 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001635
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001636 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001637
Steven Thomas0123ac62018-07-12 11:32:34 -07001638 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001639 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001640
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001641 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001642
1643 // Clear out all the output layers from the composition engine for all
1644 // displays before destroying the hardware composer interface. This ensures
1645 // any HWC layers are destroyed through that interface before it becomes
1646 // invalid.
1647 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001648 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001649 }
1650
Steven Thomas0123ac62018-07-12 11:32:34 -07001651 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1652 // called below. Clear the reference now so we don't accidentally use it
1653 // later.
1654 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001655
Steven Thomasb02664d2017-07-26 18:48:28 -07001656 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001657 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001658 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001659
Steven Thomasb02664d2017-07-26 18:48:28 -07001660 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001661 // Delete the current instance before creating the new one
1662 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1663 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1664 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1665 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001666
Lloyd Pique441d5042018-10-18 16:49:51 -07001667 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001668 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001669
1670 if (vrFlingerRequestsDisplay) {
1671 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001672 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001673
1674 mVisibleRegionsDirty = true;
1675 invalidateHwcGeometry();
1676
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001677 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001678 display = getDefaultDisplayDeviceLocked();
1679 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001680 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001681
Steven Thomasb02664d2017-07-26 18:48:28 -07001682 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001683 const nsecs_t vsyncPeriod = getVsyncPeriod();
1684 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001685
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001686 // The present fences returned from vr_hwc are not an accurate
1687 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001688 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001689
Steven Thomasb02664d2017-07-26 18:48:28 -07001690 // Use phase of 0 since phase is not known.
1691 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001692 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001693 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001694
Ana Krulecc2870422019-01-29 19:00:58 -08001695 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001696
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001697 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001698 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001699}
1700
Ady Abraham11579302019-09-19 12:35:58 -07001701bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1702 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001703 // We are storing the last 2 present fences. If sf's phase offset is to be
1704 // woken up before the actual vsync but targeting the next vsync, we need to check
1705 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001706 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1707 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001708
Ady Abraham11579302019-09-19 12:35:58 -07001709 if (fence == Fence::NO_FENCE) {
1710 return false;
1711 }
1712
1713 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1714 fence->wait(graceTimeMs);
1715 }
1716
1717 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001718}
1719
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001720void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001721 DisplayStatInfo stats;
1722 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001723 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001724 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001725 mExpectedPresentTime.store(
1726 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001727}
1728
Dominik Laskowski22488f62019-03-28 09:53:04 -07001729void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001730 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001731 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001732 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001733 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001734 // calculate the expected present time once and use the cached
1735 // value throughout this frame to make sure all layers are
1736 // seeing this same value.
1737 populateExpectedPresentTime();
1738
Ady Abraham11579302019-09-19 12:35:58 -07001739 // When Backpressure propagation is enabled we want to give a small grace period
1740 // for the present fence to fire instead of just giving up on this frame to handle cases
1741 // where present fence is just about to get signaled.
1742 const int graceTimeForPresentFenceMs =
1743 (mPropagateBackpressure &&
1744 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1745 ? 1
1746 : 0;
1747 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1748 previousFrameMissed(
1749 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001750 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1751 mHadDeviceComposition && frameMissed};
1752 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1753 mHadClientComposition && frameMissed};
1754
Alec Mouricc0fc602019-02-26 21:45:19 -08001755 if (frameMissed) {
1756 mFrameMissedCount++;
1757 mTimeStats->incrementMissedFrames();
1758 }
1759
Alec Mouri40189b02019-03-05 15:07:54 -08001760 if (hwcFrameMissed) {
1761 mHwcFrameMissedCount++;
1762 }
1763
1764 if (gpuFrameMissed) {
1765 mGpuFrameMissedCount++;
1766 }
1767
Dominik Laskowski49cea512019-11-12 14:13:23 -08001768 mScheduler->chooseRefreshRateForContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001769
Ady Abrahamb838aed2019-02-12 15:30:16 -08001770 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001771 break;
1772 }
1773
Ady Abrahamadb9a992019-09-19 21:21:55 +00001774 if (frameMissed && mPropagateBackpressure) {
1775 if ((hwcFrameMissed && !gpuFrameMissed) ||
1776 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001777 signalLayerUpdate();
1778 break;
1779 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001780 }
Dan Stoza50182882016-07-08 12:02:20 -07001781
Steven Thomas050b2c82017-03-06 11:45:16 -08001782 // Now that we're going to make it to the handleMessageTransaction()
1783 // call below it's safe to call updateVrFlinger(), which will
1784 // potentially trigger a display handoff.
1785 updateVrFlinger();
1786
Dan Stoza6b9454d2014-11-07 16:00:59 -08001787 bool refreshNeeded = handleMessageTransaction();
1788 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001789
1790 updateCursorAsync();
1791 updateInputFlinger();
1792
Dan Stoza58784442014-12-02 16:58:17 -08001793 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001794 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001795 // Signal a refresh if a transaction modified the window state,
1796 // a new buffer was latched, or if HWC has requested a full
1797 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001798 if (mFrameStartTime <= 0) {
1799 // We should only use the time of the first invalidate
1800 // message that signals a refresh as the beginning of the
1801 // frame. Otherwise the real frame time will be
1802 // underestimated.
1803 mFrameStartTime = frameStart;
1804 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001805 signalRefresh();
1806 }
1807 break;
1808 }
1809 case MessageQueue::REFRESH: {
1810 handleMessageRefresh();
1811 break;
1812 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001813 }
1814}
1815
Dan Stoza6b9454d2014-11-07 16:00:59 -08001816bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001817 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001818 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001819
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001820 bool flushedATransaction = flushTransactionQueues();
1821
1822 bool runHandleTransaction = transactionFlags &&
1823 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1824
1825 if (runHandleTransaction) {
1826 handleTransaction(eTransactionMask);
1827 } else {
1828 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001829 }
1830
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001831 if (transactionFlushNeeded()) {
1832 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001833 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001834
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001835 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001836}
1837
Mathias Agopian4fec8732012-06-29 14:12:52 -07001838void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001839 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001840
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001841 mRefreshPending = false;
1842
Lloyd Piqueab039b52019-02-13 14:22:42 -08001843 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001844 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001845 for (const auto& [_, display] : mDisplays) {
1846 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1847 }
1848 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1849 auto compositionLayer = layer->getCompositionLayer();
1850 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1851 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001852 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1853 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1854 auto compositionLayer = layer->getCompositionLayer();
Adithya Srinivasan87c1b80e2019-11-21 11:43:06 -08001855 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001856 }
1857
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001858 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001859 refreshArgs.outputColorSetting = useColorManagement
1860 ? mDisplayColorSetting
1861 : compositionengine::OutputColorSetting::kUnmanaged;
1862 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1863 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001864
1865 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1866 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001867
1868 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1869 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1870 mDrawingState.colorMatrixChanged = false;
1871 }
1872
1873 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1874
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001875 if (mDebugRegion != 0) {
1876 refreshArgs.devOptFlashDirtyRegionsDelay =
1877 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1878 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001879
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001880 mGeometryInvalid = false;
1881
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001882 // Store the present time just before calling to the composition engine so we could notify
1883 // the scheduler.
1884 const auto presentTime = systemTime();
1885
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001886 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001887 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1888 // Reset the frame start time now that we've recorded this frame.
1889 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001890
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001891 mScheduler->onDisplayRefreshed(presentTime);
1892
David Sodmanfa9b2af2017-12-24 13:28:59 -08001893 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001894 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001895
Lloyd Pique66d68602019-02-13 14:23:31 -08001896 mHadClientComposition =
1897 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1898 auto& displayDevice = tokenDisplayPair.second;
1899 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1900 });
1901 mHadDeviceComposition =
1902 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1903 auto& displayDevice = tokenDisplayPair.second;
1904 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1905 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001906
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001907 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001908
David Sodman7e4ae112018-02-09 15:02:28 -08001909 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001910 if (mVisibleRegionsDirty) {
1911 mVisibleRegionsDirty = false;
1912 if (mTracingEnabled) {
1913 mTracing.notify("visibleRegionsDirty");
1914 }
1915 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001916
1917 if (mCompositionEngine->needsAnotherUpdate()) {
1918 signalLayerUpdate();
1919 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001920}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001921
David Sodmanfa9b2af2017-12-24 13:28:59 -08001922
1923bool SurfaceFlinger::handleMessageInvalidate() {
1924 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001925 bool refreshNeeded = handlePageFlip();
1926
Vishnu Nair4351ad52019-02-11 14:13:02 -08001927 if (mVisibleRegionsDirty) {
1928 computeLayerBounds();
1929 }
1930
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001931 for (auto& layer : mLayersPendingRefresh) {
1932 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001933 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001934 invalidateLayerStack(layer, visibleReg);
1935 }
1936 mLayersPendingRefresh.clear();
1937 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001938}
1939
Ana Krulece588e312018-09-18 12:32:24 -07001940void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1941 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001942 // Update queue of past composite+present times and determine the
1943 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001944 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001945 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001946 while (!getBE().mCompositePresentTimes.empty()) {
1947 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001948 // Cached values should have been updated before calling this method,
1949 // which helps avoid duplicate syscalls.
1950 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1951 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1952 break;
1953 }
1954 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001955 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001956 }
1957
1958 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001959 while (getBE().mCompositePresentTimes.size() > 16) {
1960 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001961 }
1962
Ana Krulece588e312018-09-18 12:32:24 -07001963 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001964}
1965
Ana Krulece588e312018-09-18 12:32:24 -07001966void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1967 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001968 // Integer division and modulo round toward 0 not -inf, so we need to
1969 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08001970 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
1971 ? (stats.vsyncPeriod -
1972 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
1973 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001974
Ady Abraham9e16a482019-12-03 17:19:41 -08001975 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001976 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001977 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001978 }
1979
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001980 // Snap the latency to a value that removes scheduling jitter from the
1981 // composition and present times, which often have >1ms of jitter.
1982 // Reducing jitter is important if an app attempts to extrapolate
1983 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08001984 // Snapping also allows an app to precisely calculate
1985 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001986 nsecs_t bias = stats.vsyncPeriod / 2;
1987 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1988 nsecs_t snappedCompositeToPresentLatency =
1989 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001990
David Sodman99974d22017-11-28 12:04:33 -08001991 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001992 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1993 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001994 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001995}
1996
David Sodman2b406362017-12-15 13:33:47 -08001997void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001998{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001999 ATRACE_CALL();
2000 ALOGV("postComposition");
2001
Brian Anderson3546a3f2016-07-14 11:51:14 -07002002 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07002003 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07002004 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07002005 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07002006 }
2007
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07002008 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07002009 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002010
David Sodman73beded2017-11-15 11:56:06 -08002011 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07002012 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08002013 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002014 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07002015 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
2016 ->getRenderSurface()
2017 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002018 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002019 } else {
2020 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2021 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002022
David Sodman73beded2017-11-15 11:56:06 -08002023 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002024 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2025 mPreviousPresentFences[0] = displayDevice
2026 ? getHwComposer().getPresentFence(*displayDevice->getId())
2027 : Fence::NO_FENCE;
2028 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002029 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002030
Ana Krulece588e312018-09-18 12:32:24 -07002031 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002032 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002033
Lloyd Piqueab039b52019-02-13 14:22:42 -08002034 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2035 // be sampled a little later than when we started doing work for this frame,
2036 // but that should be okay since updateCompositorTiming has snapping logic.
2037 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2038 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002039 CompositorTiming compositorTiming;
2040 {
David Sodman99974d22017-11-28 12:04:33 -08002041 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2042 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002043 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002044
Robert Carr2047fae2016-11-28 14:09:09 -08002045 mDrawingState.traverseInZOrder([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002046 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2047 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002048 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002049 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002050 }
Robert Carr2047fae2016-11-28 14:09:09 -08002051 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002052
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002053 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002054 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002055 }
2056
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002057 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002058 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2059 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002060 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002061 }
2062 }
2063
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002064 if (mAnimCompositionPending) {
2065 mAnimCompositionPending = false;
2066
Brian Anderson4e606e32017-03-16 15:34:57 -07002067 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002068 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002069 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002070 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002071 // The HWC doesn't support present fences, so use the refresh
2072 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002073 const nsecs_t presentTime =
2074 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002075 mAnimFrameTracker.setActualPresentTime(presentTime);
2076 }
2077 mAnimFrameTracker.advanceFrame();
2078 }
Dan Stozab90cf072015-03-05 11:05:59 -08002079
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002080 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002081 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002082 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002083 }
2084
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002085 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002086
Lloyd Pique32cbe282018-10-19 13:09:22 -07002087 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2088 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002089 return;
2090 }
2091
2092 nsecs_t currentTime = systemTime();
2093 if (mHasPoweredOff) {
2094 mHasPoweredOff = false;
2095 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002096 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002097 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002098 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2099 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002100 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002101 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002102 }
David Sodman4a36e932017-11-07 14:29:47 -08002103 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002104 }
David Sodman4a36e932017-11-07 14:29:47 -08002105 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002106
2107 {
2108 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002109 if (mTexturePool.size() < mTexturePoolSize) {
2110 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002111 const size_t offset = mTexturePool.size();
2112 mTexturePool.resize(mTexturePoolSize);
2113 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2114 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002115 } else if (mTexturePool.size() > mTexturePoolSize) {
2116 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2117 const size_t offset = mTexturePoolSize;
2118 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2119 mTexturePool.resize(mTexturePoolSize);
2120 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002121 }
2122 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002123
Ady Abrahambe0f9482019-04-24 15:41:53 -07002124 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002125 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002126
Kevin DuBois413287f2019-02-25 08:46:47 -08002127 if (mLumaSampling && mRegionSamplingThread) {
2128 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002129 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002130
2131 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2132 // side-effect of getTotalSize(), so we check that again here
2133 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002134 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002135 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2136 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002137}
2138
Vishnu Nair4351ad52019-02-11 14:13:02 -08002139void SurfaceFlinger::computeLayerBounds() {
2140 for (const auto& pair : mDisplays) {
2141 const auto& displayDevice = pair.second;
2142 const auto display = displayDevice->getCompositionDisplay();
2143 for (const auto& layer : mDrawingState.layersSortedByZ) {
2144 // only consider the layers on the given layer stack
2145 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002146 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002147 }
2148
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002149 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2150 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002151 }
2152 }
2153}
2154
David Sodmanfa9b2af2017-12-24 13:28:59 -08002155void SurfaceFlinger::postFrame()
2156{
2157 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002158 const auto display = getDefaultDisplayDeviceLocked();
2159 if (display && getHwComposer().isConnected(*display->getId())) {
2160 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002161 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2162 logFrameStats();
2163 }
2164 }
2165}
2166
Mathias Agopian87baae12012-07-31 12:38:26 -07002167void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002168{
Mathias Agopian841cde52012-03-01 15:44:37 -08002169 ATRACE_CALL();
2170
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002171 // here we keep a copy of the drawing state (that is the state that's
2172 // going to be overwritten by handleTransactionLocked()) outside of
2173 // mStateLock so that the side-effects of the State assignment
2174 // don't happen with mStateLock held (which can cause deadlocks).
2175 State drawingState(mDrawingState);
2176
Mathias Agopianca4d3602011-05-19 15:38:14 -07002177 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002178 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002179
Mathias Agopianca4d3602011-05-19 15:38:14 -07002180 // Here we're guaranteed that some transaction flags are set
2181 // so we can call handleTransactionLocked() unconditionally.
2182 // We call getTransactionFlags(), which will also clear the flags,
2183 // with mStateLock held to guarantee that mCurrentState won't change
2184 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002185
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002186 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002187 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002188 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002189
Mathias Agopianca4d3602011-05-19 15:38:14 -07002190 mDebugInTransaction = 0;
2191 invalidateHwcGeometry();
2192 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002193}
2194
Lloyd Piqueba04e622017-12-14 17:11:26 -08002195void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2196 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002197 const std::optional<DisplayIdentificationInfo> info =
2198 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002199
Dominik Laskowski075d3172018-05-24 15:50:06 -07002200 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002201 continue;
2202 }
2203
Lloyd Piqueba04e622017-12-14 17:11:26 -08002204 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002205 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002206 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002207 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2208 initScheduler(info->id);
2209 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002210 mPhysicalDisplayTokens[info->id] = new BBinder();
2211 DisplayDeviceState state;
2212 state.displayId = info->id;
2213 state.isSecure = true; // All physical displays are currently considered secure.
2214 state.displayName = info->name;
2215 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2216 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002217 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002218 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002219 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002220
Dominik Laskowski075d3172018-05-24 15:50:06 -07002221 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2222 if (index >= 0) {
2223 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2224 mInterceptor->saveDisplayDeletion(state.sequenceId);
2225 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002226 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002227 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002228 }
2229
2230 processDisplayChangesLocked();
2231 }
2232
2233 mPendingHotplugEvents.clear();
2234}
2235
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002236void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002237 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2238 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002239}
2240
Lloyd Pique99d3da52018-01-22 17:48:03 -08002241sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002242 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002243 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002244 const sp<IGraphicBufferProducer>& producer) {
2245 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002246 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002247 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002248 creationArgs.isSecure = state.isSecure;
2249 creationArgs.displaySurface = dispSurface;
2250 creationArgs.hasWideColorGamut = false;
2251 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002252 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002253
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002254 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002255 creationArgs.isPrimary = isInternalDisplay;
2256
2257 if (useColorManagement && displayId) {
2258 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002259 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002260 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002261 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002262 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002263
Dominik Laskowski7e045462018-05-30 13:02:02 -07002264 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002265 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002266 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002267 }
tangrobin6753a022018-08-10 10:58:54 +08002268 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002269
Dominik Laskowski075d3172018-05-24 15:50:06 -07002270 if (displayId) {
2271 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002272 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002273 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002274 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002275
Lloyd Pique90c115d2018-09-18 21:39:42 -07002276 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002277 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002278 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002279
Lloyd Pique99d3da52018-01-22 17:48:03 -08002280 // Make sure that composition can never be stalled by a virtual display
2281 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002282 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002283 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002284 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2285 }
2286
Dominik Laskowski075d3172018-05-24 15:50:06 -07002287 creationArgs.displayInstallOrientation =
2288 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002289
Lloyd Pique99d3da52018-01-22 17:48:03 -08002290 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002291 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002292
Lloyd Pique90c115d2018-09-18 21:39:42 -07002293 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002294
2295 if (maxFrameBufferAcquiredBuffers >= 3) {
2296 nativeWindowSurface->preallocateBuffers();
2297 }
2298
2299 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002300 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002301 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002302 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002303 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002304 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002305 display->getCompositionDisplay()->setColorProfile(
2306 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2307 RenderIntent::COLORIMETRIC,
2308 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002309 if (!state.isVirtual()) {
2310 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002311 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2312 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002313 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002314
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315 display->setLayerStack(state.layerStack);
2316 display->setProjection(state.orientation, state.viewport, state.frame);
2317 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002318
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002319 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002320}
2321
Lloyd Pique347200f2017-12-14 17:00:15 -08002322void SurfaceFlinger::processDisplayChangesLocked() {
2323 // here we take advantage of Vector's copy-on-write semantics to
2324 // improve performance by skipping the transaction entirely when
2325 // know that the lists are identical
2326 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2327 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2328 if (!curr.isIdenticalTo(draw)) {
2329 mVisibleRegionsDirty = true;
2330 const size_t cc = curr.size();
2331 size_t dc = draw.size();
2332
2333 // find the displays that were removed
2334 // (ie: in drawing state but not in current state)
2335 // also handle displays that changed
2336 // (ie: displays that are in both lists)
2337 for (size_t i = 0; i < dc;) {
2338 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2339 if (j < 0) {
2340 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002341 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002342 // Save display ID before disconnecting.
2343 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002344 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002345
2346 if (!display->isVirtual()) {
2347 LOG_ALWAYS_FATAL_IF(!displayId);
2348 dispatchDisplayHotplugEvent(displayId->value, false);
2349 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002350 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002351
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002352 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002353 } else {
2354 // this display is in both lists. see if something changed.
2355 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002356 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002357 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2358 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2359 if (state_binder != draw_binder) {
2360 // changing the surface is like destroying and
2361 // recreating the DisplayDevice, so we just remove it
2362 // from the drawing state, so that it get re-added
2363 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002364 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002365 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002366 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002367 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002368 mDrawingState.displays.removeItemsAt(i);
2369 dc--;
2370 // at this point we must loop to the next item
2371 continue;
2372 }
2373
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002374 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002375 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002376 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002377 }
2378 if ((state.orientation != draw[i].orientation) ||
2379 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002380 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002381 }
2382 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002383 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002384 }
2385 }
2386 }
2387 ++i;
2388 }
2389
2390 // find displays that were added
2391 // (ie: in current state but not in drawing state)
2392 for (size_t i = 0; i < cc; i++) {
2393 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2394 const DisplayDeviceState& state(curr[i]);
2395
Lloyd Pique542307f2018-10-19 13:24:08 -07002396 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002397 sp<IGraphicBufferProducer> producer;
2398 sp<IGraphicBufferProducer> bqProducer;
2399 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002400 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002401
Dominik Laskowski075d3172018-05-24 15:50:06 -07002402 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002403 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002404 // Virtual displays without a surface are dormant:
2405 // they have external state (layer stack, projection,
2406 // etc.) but no internal state (i.e. a DisplayDevice).
2407 if (state.surface != nullptr) {
2408 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002409 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002410 int width = 0;
2411 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2412 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2413 int height = 0;
2414 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2415 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2416 int intFormat = 0;
2417 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2418 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002419 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002420
Dominik Laskowski075d3172018-05-24 15:50:06 -07002421 displayId =
2422 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002423 }
2424
2425 // TODO: Plumb requested format back up to consumer
2426
2427 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002428 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002429 bqProducer, bqConsumer,
2430 state.displayName);
2431
2432 dispSurface = vds;
2433 producer = vds;
2434 }
2435 } else {
2436 ALOGE_IF(state.surface != nullptr,
2437 "adding a supported display, but rendering "
2438 "surface is provided (%p), ignoring it",
2439 state.surface.get());
2440
Dominik Laskowski075d3172018-05-24 15:50:06 -07002441 displayId = state.displayId;
2442 LOG_ALWAYS_FATAL_IF(!displayId);
2443 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002444 producer = bqProducer;
2445 }
2446
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002447 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002448 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002449 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002450 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002451 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002452 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002453 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002454 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002455 }
2456 }
2457 }
2458 }
2459 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002460
2461 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002462}
2463
Mathias Agopian87baae12012-07-31 12:38:26 -07002464void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002465{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002466 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2467
Dan Stoza7dde5992015-05-22 09:51:44 -07002468 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002469 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2470 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002471 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002472
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002473 /*
2474 * Traversal of the children
2475 * (perform the transaction for each of them if needed)
2476 */
2477
Marissa Wall06255332019-03-27 13:48:27 -07002478 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002479 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002480 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002481 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002482
2483 const uint32_t flags = layer->doTransaction(0);
2484 if (flags & Layer::eVisibleRegion)
2485 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002486
2487 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002488 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002489 }
Robert Carr2047fae2016-11-28 14:09:09 -08002490 });
Marissa Wall06255332019-03-27 13:48:27 -07002491 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002492 }
2493
2494 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002495 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002496 */
2497
Mathias Agopiane57f2922012-08-09 16:29:12 -07002498 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002499 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002500 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002501 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002502
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002503 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002504 // The transform hint might have changed for some layers
2505 // (either because a display has changed, or because a layer
2506 // as changed).
2507 //
2508 // Walk through all the layers in currentLayers,
2509 // and update their transform hint.
2510 //
2511 // If a layer is visible only on a single display, then that
2512 // display is used to calculate the hint, otherwise we use the
2513 // default display.
2514 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002515 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002516 // the hint is set before we acquire a buffer from the surface texture.
2517 //
2518 // NOTE: layer transactions have taken place already, so we use their
2519 // drawing state. However, SurfaceFlinger's own transaction has not
2520 // happened yet, so we must use the current state layer list
2521 // (soon to become the drawing state list).
2522 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002523 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002524 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002525 bool first = true;
2526 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002527 // NOTE: we rely on the fact that layers are sorted by
2528 // layerStack first (so we don't have to traverse the list
2529 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002530 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002531 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002532 currentlayerStack = layerStack;
2533 // figure out if this layerstack is mirrored
2534 // (more than one display) if so, pick the default display,
2535 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002536 hintDisplay = nullptr;
2537 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002538 if (display->getCompositionDisplay()
2539 ->belongsInOutput(layer->getLayerStack(),
2540 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002541 if (hintDisplay) {
2542 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002543 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002544 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002545 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002546 }
2547 }
2548 }
2549 }
Chet Haase91d25932013-04-11 15:24:55 -07002550
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002551 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002552 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2553 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002554
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002555 // could be null when this layer is using a layerStack
2556 // that is not visible on any display. Also can occur at
2557 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002558 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002559 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002560
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002561 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002562 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002563 if (hintDisplay) {
2564 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002565 }
Robert Carr2047fae2016-11-28 14:09:09 -08002566
2567 first = false;
2568 });
Mathias Agopian84300952012-11-21 16:02:13 -08002569 }
2570
2571
Mathias Agopian3559b072012-08-15 13:46:03 -07002572 /*
2573 * Perform our own transaction if needed
2574 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002575
2576 if (mLayersAdded) {
2577 mLayersAdded = false;
2578 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002579 mVisibleRegionsDirty = true;
2580 }
2581
2582 // some layers might have been removed, so
2583 // we need to update the regions they're exposing.
2584 if (mLayersRemoved) {
2585 mLayersRemoved = false;
2586 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002587 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002588 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002589 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002590 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002591 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002592 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002593 }
Robert Carr2047fae2016-11-28 14:09:09 -08002594 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002595 }
2596
Vishnu Nairec0ab382019-02-13 15:32:56 -08002597 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002598 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002599}
2600
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002601void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002602 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002603 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002604 return;
2605 }
2606
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002607 if (mVisibleRegionsDirty || mInputInfoChanged) {
2608 mInputInfoChanged = false;
2609 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002610 } else if (mInputWindowCommands.syncInputWindows) {
2611 // If the caller requested to sync input windows, but there are no
2612 // changes to input windows, notify immediately.
2613 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002614 }
2615
Arthur Hung6cbb9752019-09-05 16:38:18 +08002616 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002617}
2618
2619void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002620 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002621
2622 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2623 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002624 // When calculating the screen bounds we ignore the transparent region since it may
2625 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002626 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002627 }
2628 });
chaviw291d88a2019-02-14 10:33:58 -08002629
2630 mInputFlinger->setInputWindows(inputHandles,
2631 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2632 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002633}
2634
Vishnu Nairec0ab382019-02-13 15:32:56 -08002635void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002636 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002637 mPendingInputWindowCommands.clear();
2638}
2639
Riley Andrews03414a12014-07-01 14:22:59 -07002640void SurfaceFlinger::updateCursorAsync()
2641{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002642 compositionengine::CompositionRefreshArgs refreshArgs;
2643 for (const auto& [_, display] : mDisplays) {
2644 if (display->getId()) {
2645 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002646 }
2647 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002648
2649 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002650}
2651
Ady Abraham2139f732019-11-13 18:56:40 -08002652void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
2653 Scheduler::ConfigEvent event) {
2654 Mutex::Autolock lock(mStateLock);
2655 changeRefreshRateLocked(refreshRate, event);
2656}
2657
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002658void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2659 if (mScheduler) {
2660 // In practice it's not allowed to hotplug in/out the primary display once it's been
2661 // connected during startup, but some tests do it, so just warn and return.
2662 ALOGW("Can't re-init scheduler");
2663 return;
2664 }
2665
Ady Abraham2139f732019-11-13 18:56:40 -08002666 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002667 mRefreshRateConfigs =
2668 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2669 getHwComposer().getConfigs(
2670 primaryDisplayId),
2671 currentConfig);
2672 mRefreshRateStats =
2673 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2674 currentConfig, HWC_POWER_MODE_OFF);
2675 mRefreshRateStats->setConfigMode(currentConfig);
2676
Ady Abraham9e16a482019-12-03 17:19:41 -08002677 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2678
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002679 // start the EventThread
2680 mScheduler =
2681 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002682 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002683 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002684 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002685 impl::EventThread::InterceptVSyncsCallback());
2686 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002687 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002688 [this](nsecs_t timestamp) {
2689 mInterceptor->saveVSyncEvent(timestamp);
2690 });
2691
2692 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2693 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002694 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002695
2696 mRegionSamplingThread =
2697 new RegionSamplingThread(*this, *mScheduler,
2698 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002699 // Dispatch a config change request for the primary display on scheduler
2700 // initialization, so that the EventThreads always contain a reference to a
2701 // prior configuration.
2702 //
2703 // This is a bit hacky, but this avoids a back-pointer into the main SF
2704 // classes from EventThread, and there should be no run-time binder cost
2705 // anyway since there are no connected apps at this point.
2706 const nsecs_t vsyncPeriod =
2707 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2708 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2709 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002710}
2711
Mathias Agopian4fec8732012-06-29 14:12:52 -07002712void SurfaceFlinger::commitTransaction()
2713{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002714 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002715
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002716 mTransactionPending = false;
2717 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002718 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002719}
2720
Lloyd Pique58e24a32019-08-01 15:50:14 -07002721void SurfaceFlinger::commitTransactionLocked() {
2722 if (!mLayersPendingRemoval.isEmpty()) {
2723 // Notify removed layers now that they can't be drawn from
2724 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002725 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002726
2727 // Ensure any buffers set to display on any children are released.
2728 if (l->isRemovedFromCurrentState()) {
2729 l->latchAndReleaseBuffer();
2730 }
2731
2732 // If the layer has been removed and has no parent, then it will not be reachable
2733 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2734 // ensure we can copy its current to drawing state.
2735 if (!l->getParent()) {
2736 mOffscreenLayers.emplace(l.get());
2737 }
2738 }
2739 mLayersPendingRemoval.clear();
2740 }
2741
2742 // If this transaction is part of a window animation then the next frame
2743 // we composite should be considered an animation as well.
2744 mAnimCompositionPending = mAnimTransactionPending;
2745
2746 mDrawingState = mCurrentState;
2747 // clear the "changed" flags in current state
2748 mCurrentState.colorMatrixChanged = false;
2749
2750 mDrawingState.traverseInZOrder([&](Layer* layer) {
2751 layer->commitChildList();
2752
2753 // If the layer can be reached when traversing mDrawingState, then the layer is no
2754 // longer offscreen. Remove the layer from the offscreenLayer set.
2755 if (mOffscreenLayers.count(layer)) {
2756 mOffscreenLayers.erase(layer);
2757 }
2758 });
2759
2760 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002761 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002762}
2763
Nataniel Borges2b796da2019-02-15 13:32:18 -08002764void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2765 if (mTracingEnabledChanged) {
2766 mTracingEnabled = mTracing.isEnabled();
2767 mTracingEnabledChanged = false;
2768 }
2769
2770 // Synchronize with Tracing thread
2771 std::unique_lock<std::mutex> lock;
2772 if (mTracingEnabled) {
2773 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2774 }
2775
2776 lockedOperation();
2777
2778 // Synchronize with Tracing thread
2779 if (mTracingEnabled) {
2780 lock.unlock();
2781 }
2782}
2783
chaviw74d90ad2019-04-26 14:45:26 -07002784void SurfaceFlinger::commitOffscreenLayers() {
2785 for (Layer* offscreenLayer : mOffscreenLayers) {
2786 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2787 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2788 if (!trFlags) return;
2789
2790 layer->doTransaction(0);
2791 layer->commitChildList();
2792 });
2793 }
2794}
2795
Chia-I Wuab0c3192017-08-01 11:29:00 -07002796void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002797 for (const auto& [token, displayDevice] : mDisplays) {
2798 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002799 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002800 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002801 }
2802 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002803}
2804
Dan Stoza6b9454d2014-11-07 16:00:59 -08002805bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002806{
Ady Abraham09bd3922019-04-08 10:44:56 -07002807 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002808 ALOGV("handlePageFlip");
2809
Brian Andersond6927fb2016-07-23 23:37:30 -07002810 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002811
Mathias Agopian4fec8732012-06-29 14:12:52 -07002812 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002813 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002814 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002815
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002816 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2817
Eric Penner51c59cd2014-07-28 19:51:58 -07002818 // Store the set of layers that need updates. This set must not change as
2819 // buffers are being latched, as this could result in a deadlock.
2820 // Example: Two producers share the same command stream and:
2821 // 1.) Layer 0 is latched
2822 // 2.) Layer 0 gets a new frame
2823 // 2.) Layer 1 gets a new frame
2824 // 3.) Layer 1 is latched.
2825 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2826 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002827 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002828 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002829 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002830 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002831 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002832 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002833 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002834 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002835 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002836 } else {
2837 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002838 }
Robert Carr2047fae2016-11-28 14:09:09 -08002839 });
2840
chaviw49a108c2019-08-12 11:23:06 -07002841 // The client can continue submitting buffers for offscreen layers, but they will not
2842 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2843 // layers to ensure dequeueBuffer doesn't block indefinitely.
2844 for (Layer* offscreenLayer : mOffscreenLayers) {
2845 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2846 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2847 }
2848
Lloyd Piquef2c79392018-12-20 16:23:33 -08002849 if (!mLayersWithQueuedFrames.empty()) {
2850 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2851 // writes to Layer current state. See also b/119481871
2852 Mutex::Autolock lock(mStateLock);
2853
2854 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002855 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002856 mLayersPendingRefresh.push_back(layer);
2857 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002858 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002859 if (layer->isBufferLatched()) {
2860 newDataLatched = true;
2861 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002862 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002863 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002864
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002865 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002866
2867 // If we will need to wake up at some time in the future to deal with a
2868 // queued frame that shouldn't be displayed during this vsync period, wake
2869 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002870 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002871 signalLayerUpdate();
2872 }
2873
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002874 // enter boot animation on first buffer latch
2875 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2876 ALOGI("Enter boot animation");
2877 mBootStage = BootStage::BOOTANIMATION;
2878 }
2879
chaviw74b03172019-08-19 11:09:03 -07002880 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2881
Dan Stoza6b9454d2014-11-07 16:00:59 -08002882 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002883 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002884}
2885
Mathias Agopianad456f92011-01-13 17:53:01 -08002886void SurfaceFlinger::invalidateHwcGeometry()
2887{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002888 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002889}
2890
Robert Carrc0df3122019-04-11 13:18:21 -07002891status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2892 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2893 const sp<IBinder>& parentHandle,
2894 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002895 // add this layer to the current state list
2896 {
2897 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002898 sp<Layer> parent;
2899 if (parentHandle != nullptr) {
2900 parent = fromHandle(parentHandle);
2901 if (parent == nullptr) {
2902 return NAME_NOT_FOUND;
2903 }
2904 } else {
2905 parent = parentLayer;
2906 }
2907
Robert Carr1f0a16a2016-10-24 16:27:39 -07002908 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002909 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002910 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002911 return NO_MEMORY;
2912 }
Robert Carrc0df3122019-04-11 13:18:21 -07002913
2914 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2915
Robert Carrb89ea9d2018-12-10 13:01:14 -08002916 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002917 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002918 } else if (parent == nullptr) {
2919 lbc->onRemovedFromCurrentState();
2920 } else if (parent->isRemovedFromCurrentState()) {
2921 parent->addChild(lbc);
2922 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002923 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002924 parent->addChild(lbc);
2925 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002926
Yiwei Zhang243b3782018-05-15 17:40:04 -07002927 if (gbc != nullptr) {
2928 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2929 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2930 mMaxGraphicBufferProducerListSize,
2931 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2932 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002933 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002934 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002935 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002936 }
2937
Mathias Agopian96f08192010-06-02 23:28:45 -07002938 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002939 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002940
Dan Stoza7d89d062015-04-30 13:29:25 -07002941 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002942}
2943
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002944uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002945 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002946}
2947
Mathias Agopian3f844832013-08-07 21:24:32 -07002948uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002949 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002950}
2951
Mathias Agopian3f844832013-08-07 21:24:32 -07002952uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002953 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002954}
2955
2956uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002957 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002958 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002959 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002960 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002961 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002962 }
2963 return old;
2964}
2965
Marissa Wall713b63f2018-10-17 15:42:43 -07002966bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002967 // to prevent onHandleDestroyed from being called while the lock is held,
2968 // we must keep a copy of the transactions (specifically the composer
2969 // states) around outside the scope of the lock
2970 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002971 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002972 {
2973 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002974
Valerie Haufce31b82019-04-30 16:41:14 -07002975 auto it = mTransactionQueues.begin();
2976 while (it != mTransactionQueues.end()) {
2977 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002978
Valerie Haufce31b82019-04-30 16:41:14 -07002979 while (!transactionQueue.empty()) {
2980 const auto& transaction = transactionQueue.front();
2981 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002982 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002983 transaction.states)) {
2984 setTransactionFlags(eTransactionFlushNeeded);
2985 break;
2986 }
2987 transactions.push_back(transaction);
2988 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2989 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002990 transaction.buffer, transaction.postTime,
2991 transaction.privileged, transaction.hasListenerCallbacks,
2992 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002993 transactionQueue.pop();
2994 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002995 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002996
Valerie Haufce31b82019-04-30 16:41:14 -07002997 if (transactionQueue.empty()) {
2998 it = mTransactionQueues.erase(it);
2999 mTransactionCV.broadcast();
3000 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07003001 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07003002 }
Valerie Hauf6016b62019-03-28 10:49:59 -07003003 }
Marissa Wall713b63f2018-10-17 15:42:43 -07003004 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003005 return flushedATransaction;
3006}
3007
3008bool SurfaceFlinger::transactionFlushNeeded() {
3009 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07003010}
3011
chaviwca27f252018-02-06 16:46:39 -08003012
Marissa Wall17b4e452018-12-26 16:32:34 -08003013bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003014 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08003015 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003016 if (!useCachedExpectedPresentTime)
3017 populateExpectedPresentTime();
3018
3019 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003020 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3021 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3022 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3023 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3024 return false;
3025 }
3026
Marissa Wall713b63f2018-10-17 15:42:43 -07003027 for (const ComposerState& state : states) {
3028 const layer_state_t& s = state.state;
3029 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3030 continue;
3031 }
3032 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003033 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003034 }
3035 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003036 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003037}
3038
Valerie Hau9dab9732019-08-20 09:29:25 -07003039void SurfaceFlinger::setTransactionState(
3040 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3041 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3042 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3043 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003044 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003045
Valerie Haubc6ddb12019-03-08 11:10:15 -08003046 const int64_t postTime = systemTime();
3047
Robert Carr14167e02019-02-13 13:50:55 -08003048 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3049
Mathias Agopian698c0872011-06-28 19:09:31 -07003050 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003051
Marissa Wall713b63f2018-10-17 15:42:43 -07003052 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003053 auto itr = mTransactionQueues.find(applyToken);
3054 // if this is an animation frame, wait until prior animation frame has
3055 // been applied by SF
3056 if (flags & eAnimation) {
3057 while (itr != mTransactionQueues.end()) {
3058 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3059 if (CC_UNLIKELY(err != NO_ERROR)) {
3060 ALOGW_IF(err == TIMED_OUT,
3061 "setTransactionState timed out "
3062 "waiting for animation frame to apply");
3063 break;
3064 }
3065 itr = mTransactionQueues.find(applyToken);
3066 }
3067 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003068
3069 // Expected present time is computed and cached on invalidate, so it may be stale.
3070 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3071 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003072 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003073 uncacheBuffer, postTime, privileged,
3074 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003075 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003076 return;
3077 }
3078
Valerie Haubc6ddb12019-03-08 11:10:15 -08003079 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003080 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3081 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003082}
3083
Valerie Hau9dab9732019-08-20 09:29:25 -07003084void SurfaceFlinger::applyTransactionState(
3085 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3086 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3087 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3088 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3089 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003090 uint32_t transactionFlags = 0;
3091
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003092 if (flags & eAnimation) {
3093 // For window updates that are part of an animation we must wait for
3094 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003095 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003096 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003097 if (CC_UNLIKELY(err != NO_ERROR)) {
3098 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003099 // caller after a few seconds.
3100 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3101 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003102 mAnimTransactionPending = false;
3103 break;
3104 }
3105 }
3106 }
3107
chaviwca27f252018-02-06 16:46:39 -08003108 for (const DisplayState& display : displays) {
3109 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003110 }
3111
Valerie Hau9dab9732019-08-20 09:29:25 -07003112 // start and end registration for listeners w/ no surface so they can get their callback. Note
3113 // that listeners with SurfaceControls will start registration during setClientStateLocked
3114 // below.
3115 for (const auto& listener : listenerCallbacks) {
3116 mTransactionCompletedThread.startRegistration(listener);
3117 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003118 }
3119
Valerie Hau9dab9732019-08-20 09:29:25 -07003120 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003121 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003122 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003123 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3124 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003125 }
3126
Valerie Hau9dab9732019-08-20 09:29:25 -07003127 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003128 mTransactionCompletedThread.endRegistration(listenerCallback);
3129 }
3130
Marissa Walle2ffb422018-10-12 11:33:52 -07003131 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003132 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003133 mTransactionCompletedThread.sendCallbacks();
3134 }
3135 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003136
chaviw273171b2018-12-26 11:46:30 -08003137 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3138
Marissa Wall947d34e2019-03-29 14:03:53 -07003139 if (uncacheBuffer.isValid()) {
3140 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003141 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003142 }
3143
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003144 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3145 // anyway. This can be used as a flush mechanism for previous async transactions.
3146 // Empty animation transaction can be used to simulate back-pressure, so also force a
3147 // transaction for empty animation transactions.
3148 if (transactionFlags == 0 &&
3149 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003150 transactionFlags = eTransactionNeeded;
3151 }
3152
Marissa Wall06255332019-03-27 13:48:27 -07003153 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3154 // so we don't have to wake up again next frame to preform an uneeded traversal.
3155 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3156 transactionFlags = transactionFlags & (~eTraversalNeeded);
3157 mTraversalNeededMainThread = true;
3158 }
3159
Mathias Agopian386aa982011-11-07 21:58:03 -08003160 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003161 if (mInterceptor->isEnabled()) {
3162 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003163 }
Irvel468051e2016-06-13 16:44:44 -07003164
Mathias Agopian386aa982011-11-07 21:58:03 -08003165 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003166 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3167 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003168 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003169
3170 // if this is a synchronous transaction, wait for it to take effect
3171 // before returning.
3172 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003173 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003174 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003175 if (flags & eAnimation) {
3176 mAnimTransactionPending = true;
3177 }
chaviw4fe36852019-04-15 16:25:49 -07003178 if (mPendingInputWindowCommands.syncInputWindows) {
3179 mPendingSyncInputWindows = true;
3180 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003181
3182 // applyTransactionState can be called by either the main SF thread or by
3183 // another process through setTransactionState. While a given process may wish
3184 // to wait on synchronous transactions, the main SF thread should never
3185 // be blocked. Therefore, we only wait if isMainThread is false.
3186 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003187 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3188 if (CC_UNLIKELY(err != NO_ERROR)) {
3189 // just in case something goes wrong in SF, return to the
3190 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003191 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3192 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003193 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003194 break;
3195 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003196 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003197 }
3198}
3199
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003200uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3201 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3202 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003203
Mathias Agopiane57f2922012-08-09 16:29:12 -07003204 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003205 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3206
3207 const uint32_t what = s.what;
3208 if (what & DisplayState::eSurfaceChanged) {
3209 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3210 state.surface = s.surface;
3211 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003212 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003213 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003214 if (what & DisplayState::eLayerStackChanged) {
3215 if (state.layerStack != s.layerStack) {
3216 state.layerStack = s.layerStack;
3217 flags |= eDisplayTransactionNeeded;
3218 }
3219 }
3220 if (what & DisplayState::eDisplayProjectionChanged) {
3221 if (state.orientation != s.orientation) {
3222 state.orientation = s.orientation;
3223 flags |= eDisplayTransactionNeeded;
3224 }
3225 if (state.frame != s.frame) {
3226 state.frame = s.frame;
3227 flags |= eDisplayTransactionNeeded;
3228 }
3229 if (state.viewport != s.viewport) {
3230 state.viewport = s.viewport;
3231 flags |= eDisplayTransactionNeeded;
3232 }
3233 }
3234 if (what & DisplayState::eDisplaySizeChanged) {
3235 if (state.width != s.width) {
3236 state.width = s.width;
3237 flags |= eDisplayTransactionNeeded;
3238 }
3239 if (state.height != s.height) {
3240 state.height = s.height;
3241 flags |= eDisplayTransactionNeeded;
3242 }
3243 }
3244
Mathias Agopiane57f2922012-08-09 16:29:12 -07003245 return flags;
3246}
3247
Robert Carr14167e02019-02-13 13:50:55 -08003248bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003249 IPCThreadState* ipc = IPCThreadState::self();
3250 const int pid = ipc->getCallingPid();
3251 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003252 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003253 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003254 return false;
3255 }
3256 return true;
3257}
3258
Marissa Wall3dad52d2019-03-22 14:03:19 -07003259uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003260 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3261 bool privileged,
3262 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003263 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003264
Valerie Hau9dab9732019-08-20 09:29:25 -07003265 for (auto& listener : s.listeners) {
3266 // note that startRegistration will not re-register if the listener has
3267 // already be registered for a prior surface control
3268 mTransactionCompletedThread.startRegistration(listener);
3269 listenerCallbacks.insert(listener);
3270 }
3271
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003272 sp<Layer> layer = nullptr;
3273 if (s.surface) {
3274 layer = fromHandle(s.surface);
3275 } else {
3276 // The client may provide us a null handle. Treat it as if the layer was removed.
3277 ALOGW("Attempt to set client state with a null layer handle");
3278 }
chaviw8b3871a2017-11-01 17:41:01 -07003279 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003280 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003281 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003282 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003283 }
chaviw8b3871a2017-11-01 17:41:01 -07003284 return 0;
3285 }
3286
chaviw8b3871a2017-11-01 17:41:01 -07003287 uint32_t flags = 0;
3288
Garfield Tan8a3083e2018-12-03 13:21:07 -08003289 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003290
3291 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3292 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003293 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003294 layer->pushPendingState();
3295 }
3296
chaviw8b3871a2017-11-01 17:41:01 -07003297 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003298 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003299 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003300 }
chaviw8b3871a2017-11-01 17:41:01 -07003301 }
3302 if (what & layer_state_t::eLayerChanged) {
3303 // NOTE: index needs to be calculated before we update the state
3304 const auto& p = layer->getParent();
3305 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003306 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003307 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003308 mCurrentState.layersSortedByZ.removeAt(idx);
3309 mCurrentState.layersSortedByZ.add(layer);
3310 // we need traversal (state changed)
3311 // AND transaction (list changed)
3312 flags |= eTransactionNeeded|eTraversalNeeded;
3313 }
chaviw8b3871a2017-11-01 17:41:01 -07003314 } else {
3315 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003316 flags |= eTransactionNeeded|eTraversalNeeded;
3317 }
3318 }
chaviw8b3871a2017-11-01 17:41:01 -07003319 }
3320 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003321 // NOTE: index needs to be calculated before we update the state
3322 const auto& p = layer->getParent();
3323 if (p == nullptr) {
3324 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3325 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3326 mCurrentState.layersSortedByZ.removeAt(idx);
3327 mCurrentState.layersSortedByZ.add(layer);
3328 // we need traversal (state changed)
3329 // AND transaction (list changed)
3330 flags |= eTransactionNeeded|eTraversalNeeded;
3331 }
3332 } else {
3333 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3334 flags |= eTransactionNeeded|eTraversalNeeded;
3335 }
chaviw8b3871a2017-11-01 17:41:01 -07003336 }
3337 }
3338 if (what & layer_state_t::eSizeChanged) {
3339 if (layer->setSize(s.w, s.h)) {
3340 flags |= eTraversalNeeded;
3341 }
3342 }
3343 if (what & layer_state_t::eAlphaChanged) {
3344 if (layer->setAlpha(s.alpha))
3345 flags |= eTraversalNeeded;
3346 }
3347 if (what & layer_state_t::eColorChanged) {
3348 if (layer->setColor(s.color))
3349 flags |= eTraversalNeeded;
3350 }
Peiyong Lind3788632018-09-18 16:01:31 -07003351 if (what & layer_state_t::eColorTransformChanged) {
3352 if (layer->setColorTransform(s.colorTransform)) {
3353 flags |= eTraversalNeeded;
3354 }
3355 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003356 if (what & layer_state_t::eBackgroundColorChanged) {
3357 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3358 flags |= eTraversalNeeded;
3359 }
3360 }
chaviw8b3871a2017-11-01 17:41:01 -07003361 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003362 // TODO: b/109894387
3363 //
3364 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3365 // rotation. To see the problem observe that if we have a square parent, and a child
3366 // of the same size, then we rotate the child 45 degrees around it's center, the child
3367 // must now be cropped to a non rectangular 8 sided region.
3368 //
3369 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3370 // private API, and the WindowManager only uses rotation in one case, which is on a top
3371 // level layer in which cropping is not an issue.
3372 //
3373 // However given that abuse of rotation matrices could lead to surfaces extending outside
3374 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3375 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3376 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003377 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003378 flags |= eTraversalNeeded;
3379 }
3380 if (what & layer_state_t::eTransparentRegionChanged) {
3381 if (layer->setTransparentRegionHint(s.transparentRegion))
3382 flags |= eTraversalNeeded;
3383 }
3384 if (what & layer_state_t::eFlagsChanged) {
3385 if (layer->setFlags(s.flags, s.mask))
3386 flags |= eTraversalNeeded;
3387 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003388 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003389 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003390 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003391 if (what & layer_state_t::eCornerRadiusChanged) {
3392 if (layer->setCornerRadius(s.cornerRadius))
3393 flags |= eTraversalNeeded;
3394 }
chaviw8b3871a2017-11-01 17:41:01 -07003395 if (what & layer_state_t::eLayerStackChanged) {
3396 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3397 // We only allow setting layer stacks for top level layers,
3398 // everything else inherits layer stack from its parent.
3399 if (layer->hasParent()) {
3400 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003401 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003402 } else if (idx < 0) {
3403 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003404 "that also does not appear in the top level layer list. Something"
3405 " has gone wrong.",
3406 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003407 } else if (layer->setLayerStack(s.layerStack)) {
3408 mCurrentState.layersSortedByZ.removeAt(idx);
3409 mCurrentState.layersSortedByZ.add(layer);
3410 // we need traversal (state changed)
3411 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003412 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003413 }
3414 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003415 if (what & layer_state_t::eDeferTransaction_legacy) {
3416 if (s.barrierHandle_legacy != nullptr) {
3417 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3418 } else if (s.barrierGbp_legacy != nullptr) {
3419 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003420 if (authenticateSurfaceTextureLocked(gbp)) {
3421 const auto& otherLayer =
3422 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003423 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003424 } else {
3425 ALOGE("Attempt to defer transaction to to an"
3426 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003427 }
3428 }
chaviw8b3871a2017-11-01 17:41:01 -07003429 // We don't trigger a traversal here because if no other state is
3430 // changed, we don't want this to cause any more work
3431 }
chaviw8b3871a2017-11-01 17:41:01 -07003432 if (what & layer_state_t::eReparentChildren) {
3433 if (layer->reparentChildren(s.reparentHandle)) {
3434 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003435 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003436 }
chaviw8b3871a2017-11-01 17:41:01 -07003437 if (what & layer_state_t::eDetachChildren) {
3438 layer->detachChildren();
3439 }
3440 if (what & layer_state_t::eOverrideScalingModeChanged) {
3441 layer->setOverrideScalingMode(s.overrideScalingMode);
3442 // We don't trigger a traversal here because if no other state is
3443 // changed, we don't want this to cause any more work
3444 }
Marissa Wall61c58622018-07-18 10:12:20 -07003445 if (what & layer_state_t::eTransformChanged) {
3446 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3447 }
3448 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3449 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3450 flags |= eTraversalNeeded;
3451 }
3452 if (what & layer_state_t::eCropChanged) {
3453 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3454 }
Marissa Wall861616d2018-10-22 12:52:23 -07003455 if (what & layer_state_t::eFrameChanged) {
3456 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3457 }
Marissa Wall61c58622018-07-18 10:12:20 -07003458 if (what & layer_state_t::eAcquireFenceChanged) {
3459 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3460 }
3461 if (what & layer_state_t::eDataspaceChanged) {
3462 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3463 }
3464 if (what & layer_state_t::eHdrMetadataChanged) {
3465 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3466 }
3467 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3468 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3469 }
3470 if (what & layer_state_t::eApiChanged) {
3471 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3472 }
3473 if (what & layer_state_t::eSidebandStreamChanged) {
3474 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3475 }
Robert Carr720e5062018-07-30 17:45:14 -07003476 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003477 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003478 layer->setInputInfo(s.inputInfo);
3479 flags |= eTraversalNeeded;
3480 } else {
3481 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3482 }
Robert Carr720e5062018-07-30 17:45:14 -07003483 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003484 if (what & layer_state_t::eMetadataChanged) {
3485 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3486 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003487 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3488 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3489 flags |= eTraversalNeeded;
3490 }
3491 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003492 if (what & layer_state_t::eShadowRadiusChanged) {
3493 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3494 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003495 // This has to happen after we reparent children because when we reparent to null we remove
3496 // child layers from current state and remove its relative z. If the children are reparented in
3497 // the same transaction, then we have to make sure we reparent the children first so we do not
3498 // lose its relative z order.
3499 if (what & layer_state_t::eReparent) {
3500 bool hadParent = layer->hasParent();
3501 if (layer->reparent(s.parentHandleForChild)) {
3502 if (!hadParent) {
3503 mCurrentState.layersSortedByZ.remove(layer);
3504 }
3505 flags |= eTransactionNeeded | eTraversalNeeded;
3506 }
3507 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003508 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003509 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3510 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003511 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3512 }
3513 }
Marissa Wall78b72202019-03-15 14:58:34 -07003514 bool bufferChanged = what & layer_state_t::eBufferChanged;
3515 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3516 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003517 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003518 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003519 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3520 if (success) {
3521 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3522 success = ClientCache::getInstance()
3523 .registerErasedRecipient(s.cachedBuffer,
3524 wp<ClientCache::ErasedRecipient>(this));
3525 if (!success) {
3526 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3527 }
3528 }
Marissa Wall78b72202019-03-15 14:58:34 -07003529 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003530 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003531 } else if (bufferChanged) {
3532 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003533 }
Marissa Wall78b72202019-03-15 14:58:34 -07003534 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003535 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003536 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003537 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003538 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003539 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3540 // Do not put anything that updates layer state or modifies flags after
3541 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003542 return flags;
3543}
3544
chaviw273171b2018-12-26 11:46:30 -08003545uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3546 uint32_t flags = 0;
3547 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3548 flags |= eTraversalNeeded;
3549 }
3550
chaviwa911b102019-02-14 10:18:33 -08003551 if (inputWindowCommands.syncInputWindows) {
3552 flags |= eTraversalNeeded;
3553 }
3554
Vishnu Nairec0ab382019-02-13 15:32:56 -08003555 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003556 return flags;
3557}
3558
chaviwfe94a222019-08-21 13:52:59 -07003559status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3560 sp<IBinder>* outHandle) {
3561 if (!mirrorFromHandle) {
3562 return NAME_NOT_FOUND;
3563 }
3564
3565 sp<Layer> mirrorLayer;
3566 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003567 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003568
3569 {
3570 Mutex::Autolock _l(mStateLock);
3571 mirrorFrom = fromHandle(mirrorFromHandle);
3572 if (!mirrorFrom) {
3573 return NAME_NOT_FOUND;
3574 }
3575
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003576 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3577 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003578 if (result != NO_ERROR) {
3579 return result;
3580 }
3581
3582 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3583 }
3584
3585 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3586}
3587
Marissa Wall2d814fb2019-04-09 18:52:57 +00003588status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3589 uint32_t h, PixelFormat format, uint32_t flags,
3590 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003591 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003592 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3593 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003594 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003595 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003596 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003597 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003598 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003599
Robert Carrc0df3122019-04-11 13:18:21 -07003600 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3601 "Expected only one of parentLayer or parentHandle to be non-null. "
3602 "Programmer error?");
3603
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003604 status_t result = NO_ERROR;
3605
3606 sp<Layer> layer;
3607
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003608 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003609
Evan Roskya1f1e152019-01-24 16:17:46 -08003610 bool primaryDisplayOnly = false;
3611
3612 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3613 // TODO b/64227542
3614 if (metadata.has(METADATA_WINDOW_TYPE)) {
3615 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3616 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003617 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003618 primaryDisplayOnly = true;
3619 }
3620 }
3621
Mathias Agopian3165cc22012-08-08 19:42:09 -07003622 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003623 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003624 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3625 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003626
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003627 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003628 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003629 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003630 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003631 break;
chaviw13fdc492017-06-27 12:40:18 -07003632 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003633 // check if buffer size is set for color layer.
3634 if (w > 0 || h > 0) {
3635 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3636 int(w), int(h));
3637 return BAD_VALUE;
3638 }
3639
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003640 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3641 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003642 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003643 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003644 // check if buffer size is set for container layer.
3645 if (w > 0 || h > 0) {
3646 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3647 int(w), int(h));
3648 return BAD_VALUE;
3649 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003650 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3651 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003652 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003653 default:
3654 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003655 break;
3656 }
3657
Dan Stoza7d89d062015-04-30 13:29:25 -07003658 if (result != NO_ERROR) {
3659 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003660 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003661
Evan Roskya1f1e152019-01-24 16:17:46 -08003662 if (primaryDisplayOnly) {
3663 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003664 }
3665
Robert Carrb89ea9d2018-12-10 13:01:14 -08003666 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003667 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3668 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003669 if (result != NO_ERROR) {
3670 return result;
3671 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003672 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003673
3674 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003675 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003676}
3677
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003678std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3679 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003680
3681 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003682 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003683
Dan Stoza436ccf32018-06-21 12:10:12 -07003684 // Grab the state lock since we're accessing mCurrentState
3685 Mutex::Autolock lock(mStateLock);
3686
Cody Northropbc755282017-03-31 12:00:08 -06003687 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003688 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003689 while (matchFound) {
3690 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003691 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003692 if (layer->getName() == uniqueName) {
3693 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003694 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003695 }
3696 });
3697 }
3698
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003699 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003700 return uniqueName;
3701}
3702
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003703status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003704 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003705 LayerMetadata metadata, PixelFormat& format,
3706 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003707 sp<IGraphicBufferProducer>* gbp,
3708 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003709 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003710 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003711 case PIXEL_FORMAT_TRANSPARENT:
3712 case PIXEL_FORMAT_TRANSLUCENT:
3713 format = PIXEL_FORMAT_RGBA_8888;
3714 break;
3715 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003716 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003717 break;
3718 }
3719
chaviwb4c6e582019-08-16 14:35:07 -07003720 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003721 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003722 args.textureName = getNewTexture();
3723 {
3724 // Grab the SF state lock during this since it's the only safe way to access
3725 // RenderEngine when creating a BufferLayerConsumer
3726 // TODO: Check if this lock is still needed here
3727 Mutex::Autolock lock(mStateLock);
3728 layer = getFactory().createBufferQueueLayer(args);
3729 }
3730
Marissa Wallfd668622018-05-10 10:21:13 -07003731 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003732 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003733 *handle = layer->getHandle();
3734 *gbp = layer->getProducer();
3735 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003736 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003737
Marissa Wallfd668622018-05-10 10:21:13 -07003738 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003739 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003740}
3741
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003742status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003743 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003744 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003745 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003746 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003747 args.displayDevice = getDefaultDisplayDevice();
3748 args.textureName = getNewTexture();
3749 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003750 if (outTransformHint) {
3751 *outTransformHint = layer->getTransformHint();
3752 }
Marissa Wall61c58622018-07-18 10:12:20 -07003753 *handle = layer->getHandle();
3754 *outLayer = layer;
3755
3756 return NO_ERROR;
3757}
3758
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003759status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003760 uint32_t h, uint32_t flags, LayerMetadata metadata,
3761 sp<IBinder>* handle, sp<Layer>* outLayer) {
3762 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003763 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003764 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003765 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003766}
3767
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003768status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003769 uint32_t w, uint32_t h, uint32_t flags,
3770 LayerMetadata metadata, sp<IBinder>* handle,
3771 sp<Layer>* outLayer) {
3772 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003773 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003774 *handle = (*outLayer)->getHandle();
3775 return NO_ERROR;
3776}
3777
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003778void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003779 mLayersPendingRemoval.add(layer);
3780 mLayersRemoved = true;
3781 setTransactionFlags(eTransactionNeeded);
3782}
3783
Robert Carr695d5282018-12-18 15:27:58 -08003784void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003785{
Robert Carr2e102c92018-10-23 12:11:15 -07003786 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003787 // If a layer has a parent, we allow it to out-live it's handle
3788 // with the idea that the parent holds a reference and will eventually
3789 // be cleaned up. However no one cleans up the top-level so we do so
3790 // here.
3791 if (layer->getParent() == nullptr) {
3792 mCurrentState.layersSortedByZ.remove(layer);
3793 }
3794 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003795
3796 auto it = mLayersByLocalBinderToken.begin();
3797 while (it != mLayersByLocalBinderToken.end()) {
3798 if (it->second == layer) {
3799 it = mLayersByLocalBinderToken.erase(it);
3800 } else {
3801 it++;
3802 }
3803 }
3804
Robert Carr695d5282018-12-18 15:27:58 -08003805 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003806}
3807
Mathias Agopianb60314a2012-04-10 22:09:54 -07003808// ---------------------------------------------------------------------------
3809
Andy McFadden13a082e2012-08-24 10:16:42 -07003810void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003811 const auto display = getDefaultDisplayDeviceLocked();
3812 if (!display) return;
3813
3814 const sp<IBinder> token = display->getDisplayToken().promote();
3815 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003816
Jesse Hall01e29052013-02-19 16:13:35 -08003817 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003818 Vector<ComposerState> state;
3819 Vector<DisplayState> displays;
3820 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003821 d.what = DisplayState::eDisplayProjectionChanged |
3822 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003823 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003824 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003825 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003826 d.frame.makeInvalid();
3827 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003828 d.width = 0;
3829 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003830 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003831 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3832 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003833
Dominik Laskowskie9774092018-12-11 10:04:24 -08003834 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003835
Dominik Laskowski83b88212018-12-11 13:34:06 -08003836 const nsecs_t vsyncPeriod = getVsyncPeriod();
3837 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003838
Brian Andersond0010582017-03-07 13:20:31 -08003839 // Use phase of 0 since phase is not known.
3840 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003841 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003842 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003843}
3844
3845void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003846 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003847 postMessageAsync(
3848 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003849}
3850
Ady Abraham27c70212019-06-11 10:52:26 -07003851void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3852 if (mHWCVsyncState != enabled) {
3853 getHwComposer().setVsyncEnabled(displayId, enabled);
3854 mHWCVsyncState = enabled;
3855 }
3856}
3857
Dominik Laskowskie9774092018-12-11 10:04:24 -08003858void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003859 if (display->isVirtual()) {
3860 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003861 return;
3862 }
3863
Dominik Laskowski075d3172018-05-24 15:50:06 -07003864 const auto displayId = display->getId();
3865 LOG_ALWAYS_FATAL_IF(!displayId);
3866
Dominik Laskowski34157762018-10-31 13:07:19 -07003867 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003868
3869 int currentMode = display->getPowerMode();
3870 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003871 return;
3872 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003873
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003874 display->setPowerMode(mode);
3875
Lloyd Pique4dccc412018-01-22 17:21:36 -08003876 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003877 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003878 }
3879
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003880 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003881 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003882 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003883 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003884 mScheduler->onScreenAcquired(mAppConnectionHandle);
3885 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003886 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003887
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003888 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003889 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003890 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003891
3892 struct sched_param param = {0};
3893 param.sched_priority = 1;
3894 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3895 ALOGW("Couldn't set SCHED_FIFO on display on");
3896 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003897 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003898 // Turn off the display
3899 struct sched_param param = {0};
3900 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3901 ALOGW("Couldn't set SCHED_OTHER on display off");
3902 }
3903
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003904 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003905 mScheduler->disableHardwareVsync(true);
3906 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003907 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003908
Ady Abraham27c70212019-06-11 10:52:26 -07003909 // Make sure HWVsync is disabled before turning off the display
3910 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3911
Dominik Laskowski075d3172018-05-24 15:50:06 -07003912 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003913 mVisibleRegionsDirty = true;
3914 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003915 } else if (mode == HWC_POWER_MODE_DOZE ||
3916 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003917 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003918 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003919 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003920 mScheduler->onScreenAcquired(mAppConnectionHandle);
3921 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003922 }
3923 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3924 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003925 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003926 mScheduler->disableHardwareVsync(true);
3927 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003928 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003929 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003930 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003931 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003932 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003933 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003934
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003935 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003936 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003937 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003938 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003939 }
3940
Dominik Laskowski34157762018-10-31 13:07:19 -07003941 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003942}
3943
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003944void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003945 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003946 const auto display = getDisplayDevice(displayToken);
3947 if (!display) {
3948 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3949 displayToken.get());
3950 } else if (display->isVirtual()) {
3951 ALOGW("Attempt to set power mode %d for virtual display", mode);
3952 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003953 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003954 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003955 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003956}
3957
3958// ---------------------------------------------------------------------------
3959
Dominik Laskowskic2867142019-01-21 11:33:38 -08003960status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3961 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003962 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003963
Mathias Agopianbd115332013-04-18 16:41:04 -07003964 IPCThreadState* ipc = IPCThreadState::self();
3965 const int pid = ipc->getCallingPid();
3966 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003967
Mathias Agopianbd115332013-04-18 16:41:04 -07003968 if ((uid != AID_SHELL) &&
3969 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003970 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3971 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003972 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003973 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003974 // (this would indicate SF is stuck, but we want to be able to
3975 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003976 status_t err = mStateLock.timedLock(s2ns(1));
3977 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003978 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003979 StringAppendF(&result,
3980 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3981 "(no locks held)\n",
3982 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003983 }
3984
Dominik Laskowskic2867142019-01-21 11:33:38 -08003985 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003986 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003987 {"--dispsync"s,
3988 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003989 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003990 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3991 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3992 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3993 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3994 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3995 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003996 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003997 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3998 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003999
Dominik Laskowskic2867142019-01-21 11:33:38 -08004000 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004001
Dominik Laskowski46470112019-08-02 13:13:11 -07004002 const auto it = dumpers.find(flag);
4003 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08004004 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07004005 } else if (!asProto) {
4006 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08004007 }
4008
Mathias Agopian9795c422009-08-26 16:36:26 -07004009 if (locked) {
4010 mStateLock.unlock();
4011 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004012
Dominik Laskowski46470112019-08-02 13:13:11 -07004013 if (it == dumpers.end()) {
4014 const LayersProto layersProto = dumpProtoFromMainThread();
4015 if (asProto) {
4016 result.append(layersProto.SerializeAsString());
4017 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004018 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004019 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4020 result.append(LayerProtoParser::layerTreeToString(layerTree));
4021 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004022 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004023 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004024 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004025 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004026 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004027 return NO_ERROR;
4028}
4029
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004030status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4031 if (asProto && mTracing.isEnabled()) {
4032 mTracing.writeToFileAsync();
4033 }
4034
4035 return doDump(fd, DumpArgs(), asProto);
4036}
4037
Dominik Laskowskic2867142019-01-21 11:33:38 -08004038void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004039 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004040 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004041}
4042
Dominik Laskowskic2867142019-01-21 11:33:38 -08004043void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004044 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004045
Dominik Laskowskic2867142019-01-21 11:33:38 -08004046 if (args.size() > 1) {
4047 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004048 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004049 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004050 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004051 }
Robert Carr2047fae2016-11-28 14:09:09 -08004052 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004053 } else {
4054 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004055 }
4056}
4057
Dominik Laskowskic2867142019-01-21 11:33:38 -08004058void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004059 const bool clearAll = args.size() < 2;
4060 const auto name = clearAll ? String8() : String8(args[1]);
4061
Robert Carr2047fae2016-11-28 14:09:09 -08004062 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004063 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004064 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004065 }
Robert Carr2047fae2016-11-28 14:09:09 -08004066 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004067
Svetoslavd85084b2014-03-20 10:28:31 -07004068 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004069}
4070
Dominik Laskowskic2867142019-01-21 11:33:38 -08004071void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4072 mTimeStats->parseArgs(asProto, args, result);
4073}
4074
Jamie Gennis6547ff42013-07-16 20:12:42 -07004075// This should only be called from the main thread. Otherwise it would need
4076// the lock and should use mCurrentState rather than mDrawingState.
4077void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004078 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004079 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004080 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004081
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004082 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004083}
4084
Yiwei Zhang5434a782018-12-05 18:06:32 -08004085void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004086 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004087
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004088 if (isLayerTripleBufferingDisabled())
4089 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004090
Yiwei Zhang5434a782018-12-05 18:06:32 -08004091 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4092 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4093 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4094 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4095 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4096 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004097 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004098}
4099
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004100void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004101 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004102
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004103 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004104 result.append("\n");
4105
Ady Abraham9e16a482019-12-03 17:19:41 -08004106 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004107 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004108 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004109 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004110
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004111 HwcConfigIndexType defaultConfig;
4112 float minFps, maxFps;
4113 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004114 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004115 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004116 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004117 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004118 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4119 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004120
Ana Krulecc2870422019-01-29 19:00:58 -08004121 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004122}
4123
Yiwei Zhang5434a782018-12-05 18:06:32 -08004124void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4125 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004126 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4127 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004128 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004129 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004130 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004131 }
David Sodman4a36e932017-11-07 14:29:47 -08004132 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004133 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004134 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004135 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4136 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004137}
4138
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004139void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4140 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004141 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4142 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004143 for (const auto& segment : history) {
4144 if (!segment.usedThirdBuffer) {
4145 stats.twoBufferTime += segment.totalTime;
4146 }
4147 if (segment.occupancyAverage < 1.0f) {
4148 stats.doubleBufferedTime += segment.totalTime;
4149 } else if (segment.occupancyAverage < 2.0f) {
4150 stats.tripleBufferedTime += segment.totalTime;
4151 }
4152 ++stats.numSegments;
4153 stats.totalTime += segment.totalTime;
4154 }
4155}
4156
Yiwei Zhang5434a782018-12-05 18:06:32 -08004157void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4158 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004159
4160 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4161 const size_t count = currentLayers.size();
4162 for (size_t i=0 ; i<count ; i++) {
4163 currentLayers[i]->dumpFrameEvents(result);
4164 }
4165}
4166
Yiwei Zhang5434a782018-12-05 18:06:32 -08004167void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004168 result.append("Buffering stats:\n");
4169 result.append(" [Layer name] <Active time> <Two buffer> "
4170 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004171 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004172 typedef std::tuple<std::string, float, float, float> BufferTuple;
4173 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004174 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004175 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004176 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004177 if (stats.numSegments == 0) {
4178 continue;
4179 }
4180 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4181 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4182 stats.totalTime;
4183 float doubleBufferRatio = static_cast<float>(
4184 stats.doubleBufferedTime) / stats.totalTime;
4185 float tripleBufferRatio = static_cast<float>(
4186 stats.tripleBufferedTime) / stats.totalTime;
4187 sorted.insert({activeTime, {name, twoBufferRatio,
4188 doubleBufferRatio, tripleBufferRatio}});
4189 }
4190 for (const auto& sortedPair : sorted) {
4191 float activeTime = sortedPair.first;
4192 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004193 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4194 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004195 }
4196 result.append("\n");
4197}
4198
Yiwei Zhang5434a782018-12-05 18:06:32 -08004199void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004200 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004201 const auto displayId = display->getId();
4202 if (!displayId) {
4203 continue;
4204 }
4205 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004206 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004207 continue;
4208 }
4209
Yiwei Zhang5434a782018-12-05 18:06:32 -08004210 StringAppendF(&result,
4211 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4212 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004213 uint8_t port;
4214 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004215 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004216 result.append("no identification data\n");
4217 continue;
4218 }
4219
4220 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004221 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004222 continue;
4223 }
4224
4225 const auto edid = parseEdid(data);
4226 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004227 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004228 continue;
4229 }
4230
Yiwei Zhang5434a782018-12-05 18:06:32 -08004231 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004232 result.append(edid->displayName.data(), edid->displayName.length());
4233 result.append("\"\n");
4234 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004235}
4236
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004237void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4238 std::string& result) const {
4239 hwc2_display_t hwcDisplayId;
4240 uint8_t port;
4241 DisplayIdentificationData data;
4242
4243 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4244 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4245 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4246 }
4247}
4248
Yiwei Zhang5434a782018-12-05 18:06:32 -08004249void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004250 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004251 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4252 StringAppendF(&result, "DisplayColorSetting: %s\n",
4253 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004254
4255 // TODO: print out if wide-color mode is active or not
4256
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004257 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004258 const auto displayId = display->getId();
4259 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004260 continue;
4261 }
4262
Yiwei Zhang5434a782018-12-05 18:06:32 -08004263 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004264 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004265 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004266 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004267 }
4268
Lloyd Pique32cbe282018-10-19 13:09:22 -07004269 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004270 StringAppendF(&result, " Current color mode: %s (%d)\n",
4271 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004272 }
4273 result.append("\n");
4274}
4275
Vishnu Nair8406fd72019-07-30 11:29:31 -07004276LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004277 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004278 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004279 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004280 layer->writeToProtoDrawingState(layerProto, traceFlags);
4281 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004282 });
4283
4284 return layersProto;
4285}
4286
Vishnu Nair0f085c62019-08-30 08:49:12 -07004287void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4288 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4289 // it.
4290 LayerProto* rootProto = layersProto.add_layers();
4291 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4292 rootProto->set_id(offscreenRootLayerId);
4293 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004294 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004295
4296 for (Layer* offscreenLayer : mOffscreenLayers) {
4297 // Add layer as child of the fake root
4298 rootProto->add_children(offscreenLayer->sequence);
4299
4300 // Add layer
4301 LayerProto* layerProto = layersProto.add_layers();
4302 offscreenLayer->writeToProtoDrawingState(layerProto, traceFlags);
4303 offscreenLayer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing,
4304 traceFlags);
4305 layerProto->set_parent(offscreenRootLayerId);
4306
4307 // Add children
4308 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4309 if (layer == offscreenLayer) {
4310 return;
4311 }
4312 LayerProto* childProto = layersProto.add_layers();
4313 layer->writeToProtoDrawingState(childProto, traceFlags);
4314 layer->writeToProtoCommonState(childProto, LayerVector::StateSet::Drawing, traceFlags);
4315 });
4316 }
4317}
4318
Vishnu Nair8406fd72019-07-30 11:29:31 -07004319LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4320 LayersProto layersProto;
4321 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4322 return layersProto;
4323}
4324
Vishnu Nair0f085c62019-08-30 08:49:12 -07004325void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4326 result.append("Offscreen Layers:\n");
4327 postMessageSync(new LambdaMessage([&]() {
4328 for (Layer* offscreenLayer : mOffscreenLayers) {
4329 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4330 layer->dumpCallingUidPid(result);
4331 });
4332 }
4333 }));
4334}
4335
Dominik Laskowskic2867142019-01-21 11:33:38 -08004336void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4337 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004338 Colorizer colorizer(colorize);
4339
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004340 // figure out if we're stuck somewhere
4341 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004342 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004343 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4344
4345 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004346 * Dump library configuration.
4347 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004348
4349 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004350 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004351 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004352 appendSfConfigString(result);
4353 appendUiConfigString(result);
4354 appendGuiConfigString(result);
4355 result.append("\n");
4356
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004357 result.append("\nDisplay identification data:\n");
4358 dumpDisplayIdentificationData(result);
4359
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004360 result.append("\nWide-Color information:\n");
4361 dumpWideColorInfo(result);
4362
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004363 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004364 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004365 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004366 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004367 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004368
Andy McFadden41d67d72014-04-25 16:58:34 -07004369 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004370 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004371 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004372 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004373 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004374
Dan Stozab90cf072015-03-05 11:05:59 -08004375 dumpStaticScreenStats(result);
4376 result.append("\n");
4377
Alec Mouri40189b02019-03-05 15:07:54 -08004378 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4379 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4380 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004381
Dan Stozae77c7662016-05-13 11:37:28 -07004382 dumpBufferingStats(result);
4383
Andy McFadden4803b742012-09-24 19:07:20 -07004384 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004385 * Dump the visible layer list
4386 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004387 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004388 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004389 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4390 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004391 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004392
Chia-I Wu2f884132018-09-13 15:17:58 -07004393 {
Lloyd Pique207def92019-02-28 16:09:52 -08004394 StringAppendF(&result, "Composition layers\n");
4395 mDrawingState.traverseInZOrder([&](Layer* layer) {
4396 auto compositionLayer = layer->getCompositionLayer();
4397 if (compositionLayer) compositionLayer->dump(result);
4398 });
4399 }
4400
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004401 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004402 * Dump Display state
4403 */
4404
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004405 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004406 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004407 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004408 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004409 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004410 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004411 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004412
4413 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004414 * Dump CompositionEngine state
4415 */
4416
4417 mCompositionEngine->dump(result);
4418
4419 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004420 * Dump SurfaceFlinger global state
4421 */
4422
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004423 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004424 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004425 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004426
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004427 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004428
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004429 DebugEGLImageTracker::getInstance()->dump(result);
4430
Dominik Laskowski075d3172018-05-24 15:50:06 -07004431 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004432 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4433 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004434 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4435 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004436 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004437 StringAppendF(&result,
4438 " transaction-flags : %08x\n"
4439 " gpu_to_cpu_unsupported : %d\n",
4440 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004441
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004442 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004443 displayId && getHwComposer().isConnected(*displayId)) {
4444 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004445 StringAppendF(&result,
4446 " refresh-rate : %f fps\n"
4447 " x-dpi : %f\n"
4448 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004449 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4450 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004451 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004452
Yiwei Zhang5434a782018-12-05 18:06:32 -08004453 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004454
Dan Stozae22aec72016-08-01 13:20:59 -07004455 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004456 * Tracing state
4457 */
4458 mTracing.dump(result);
4459 result.append("\n");
4460
4461 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004462 * HWC layer minidump
4463 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004464 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004465 const auto displayId = display->getId();
4466 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004467 continue;
4468 }
4469
Yiwei Zhang5434a782018-12-05 18:06:32 -08004470 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004471 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004472 const sp<DisplayDevice> displayDevice = display;
4473 mCurrentState.traverseInZOrder(
4474 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004475 result.append("\n");
4476 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004477
4478 /*
4479 * Dump HWComposer state
4480 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004481 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004482 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004483 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004484 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004485 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004486 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004487
4488 /*
4489 * Dump gralloc state
4490 */
4491 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4492 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004493
4494 /*
4495 * Dump VrFlinger state if in use.
4496 */
4497 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4498 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004499 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004500 result.append("\n");
4501 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004502
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004503 result.append(mTimeStats->miniDump());
4504 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004505}
4506
Chia-I Wu28f320b2018-05-03 11:02:56 -07004507void SurfaceFlinger::updateColorMatrixLocked() {
4508 mat4 colorMatrix;
4509 if (mGlobalSaturationFactor != 1.0f) {
4510 // Rec.709 luma coefficients
4511 float3 luminance{0.213f, 0.715f, 0.072f};
4512 luminance *= 1.0f - mGlobalSaturationFactor;
4513 mat4 saturationMatrix = mat4(
4514 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4515 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4516 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4517 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4518 );
4519 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4520 } else {
4521 colorMatrix = mClientColorMatrix * mDaltonizer();
4522 }
4523
4524 if (mCurrentState.colorMatrix != colorMatrix) {
4525 mCurrentState.colorMatrix = colorMatrix;
4526 mCurrentState.colorMatrixChanged = true;
4527 setTransactionFlags(eTransactionNeeded);
4528 }
4529}
4530
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004531status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004532#pragma clang diagnostic push
4533#pragma clang diagnostic error "-Wswitch-enum"
4534 switch (static_cast<ISurfaceComposerTag>(code)) {
4535 // These methods should at minimum make sure that the client requested
4536 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004537 case BOOT_FINISHED:
4538 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004539 case CREATE_DISPLAY:
4540 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004541 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004542 case GET_ANIMATION_FRAME_STATS:
4543 case GET_HDR_CAPABILITIES:
4544 case SET_ACTIVE_CONFIG:
Ana Krulec0782b882019-10-15 17:34:54 -07004545 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004546 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004547 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004548 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4549 case SET_AUTO_LOW_LATENCY_MODE:
4550 case GET_GAME_CONTENT_TYPE_SUPPORT:
4551 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004552 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004553 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004554 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004555 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004556 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004557 case NOTIFY_POWER_HINT:
4558 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004559 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4560 IPCThreadState* ipc = IPCThreadState::self();
4561 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4562 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004563 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004564 }
Robert Carr1db73f62016-12-21 12:58:51 -08004565 return OK;
4566 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004567 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004568 IPCThreadState* ipc = IPCThreadState::self();
4569 const int pid = ipc->getCallingPid();
4570 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004571 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4572 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004573 return PERMISSION_DENIED;
4574 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004575 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004576 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004577 // Used by apps to hook Choreographer to SurfaceFlinger.
4578 case CREATE_DISPLAY_EVENT_CONNECTION:
4579 // The following calls are currently used by clients that do not
4580 // request necessary permissions. However, they do not expose any secret
4581 // information, so it is OK to pass them.
4582 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004583 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004584 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004585 case GET_PHYSICAL_DISPLAY_IDS:
4586 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004587 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004588 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004589 case GET_DISPLAY_CONFIGS:
4590 case GET_DISPLAY_STATS:
4591 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4592 // Calling setTransactionState is safe, because you need to have been
4593 // granted a reference to Client* and Handle* to do anything with it.
4594 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004595 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004596 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004597 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004598 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004599 case IS_WIDE_COLOR_DISPLAY:
4600 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4601 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004602 return OK;
4603 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004604 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004605 case CAPTURE_SCREEN:
4606 case ADD_REGION_SAMPLING_LISTENER:
4607 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004608 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004609 IPCThreadState* ipc = IPCThreadState::self();
4610 const int pid = ipc->getCallingPid();
4611 const int uid = ipc->getCallingUid();
4612 if ((uid != AID_GRAPHICS) &&
4613 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4614 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4615 return PERMISSION_DENIED;
4616 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004617 return OK;
4618 }
4619 // The following codes are deprecated and should never be allowed to access SF.
4620 case CONNECT_DISPLAY_UNUSED:
4621 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4622 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4623 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004624 }
chaviw93df2ea2019-04-30 16:45:12 -07004625 case CAPTURE_SCREEN_BY_ID: {
4626 IPCThreadState* ipc = IPCThreadState::self();
4627 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004628 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004629 return OK;
4630 }
4631 return PERMISSION_DENIED;
4632 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004633 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004634
4635 // These codes are used for the IBinder protocol to either interrogate the recipient
4636 // side of the transaction for its canonical interface descriptor or to dump its state.
4637 // We let them pass by default.
4638 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4639 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4640 code == IBinder::SYSPROPS_TRANSACTION) {
4641 return OK;
4642 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004643 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004644 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004645 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004646 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4647 return OK;
4648 }
4649 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4650 return PERMISSION_DENIED;
4651#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004652}
4653
Ana Krulec13be8ad2018-08-21 02:43:56 +00004654status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4655 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004656 status_t credentialCheck = CheckTransactCodeCredentials(code);
4657 if (credentialCheck != OK) {
4658 return credentialCheck;
4659 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004660
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004661 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4662 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004663 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004664 IPCThreadState* ipc = IPCThreadState::self();
4665 const int uid = ipc->getCallingUid();
4666 if (CC_UNLIKELY(uid != AID_SYSTEM
4667 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004668 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004669 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004670 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004671 return PERMISSION_DENIED;
4672 }
4673 int n;
4674 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004675 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004676 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004677 return NO_ERROR;
4678 case 1002: // SHOW_UPDATES
4679 n = data.readInt32();
4680 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004681 invalidateHwcGeometry();
4682 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004683 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004684 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004685 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004686 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004687 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004688 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004689 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004690 setTransactionFlags(
4691 eTransactionNeeded|
4692 eDisplayTransactionNeeded|
4693 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004694 return NO_ERROR;
4695 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004696 case 1006:{ // send empty update
4697 signalRefresh();
4698 return NO_ERROR;
4699 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004700 case 1008: // toggle use of hw composer
4701 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004702 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004703 invalidateHwcGeometry();
4704 repaintEverything();
4705 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004706 case 1009: // toggle use of transform hint
4707 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004708 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004709 invalidateHwcGeometry();
4710 repaintEverything();
4711 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004712 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004713 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004714 reply->writeInt32(0);
4715 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004716 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004717 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004718 return NO_ERROR;
4719 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004720 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004721 if (!display) {
4722 return NAME_NOT_FOUND;
4723 }
4724
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004725 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004726 return NO_ERROR;
4727 }
4728 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004729 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004730 // daltonize
4731 n = data.readInt32();
4732 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004733 case 1:
4734 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4735 break;
4736 case 2:
4737 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4738 break;
4739 case 3:
4740 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4741 break;
4742 default:
4743 mDaltonizer.setType(ColorBlindnessType::None);
4744 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004745 }
4746 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004747 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004748 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004749 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004750 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004751
4752 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004753 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004754 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004755 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004756 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004757 // apply a color matrix
4758 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004759 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004760 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004761 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004762 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004763 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004764 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004765 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004766 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004767 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004768 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004769
4770 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4771 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004772 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004773 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4774 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4775 }
4776
Chia-I Wu28f320b2018-05-03 11:02:56 -07004777 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004778 return NO_ERROR;
4779 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004780 case 1016: { // Unused.
4781 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004782 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004783 case 1017: {
4784 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004785 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004786 return NO_ERROR;
4787 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004788 case 1018: { // Modify Choreographer's phase offset
4789 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004790 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004791 return NO_ERROR;
4792 }
4793 case 1019: { // Modify SurfaceFlinger's phase offset
4794 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004795 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004796 return NO_ERROR;
4797 }
Irvel468051e2016-06-13 16:44:44 -07004798 case 1020: { // Layer updates interceptor
4799 n = data.readInt32();
4800 if (n) {
4801 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004802 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004803 }
4804 else{
4805 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004806 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004807 }
4808 return NO_ERROR;
4809 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004810 case 1021: { // Disable HWC virtual displays
4811 n = data.readInt32();
4812 mUseHwcVirtualDisplays = !n;
4813 return NO_ERROR;
4814 }
Romain Guy0147a172017-06-01 13:53:56 -07004815 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004816 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004817 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004818
Chia-I Wu28f320b2018-05-03 11:02:56 -07004819 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004820 return NO_ERROR;
4821 }
Romain Guy54f154a2017-10-24 21:40:32 +01004822 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004823 int32_t colorMode;
4824
Chia-I Wu0d711262018-05-21 15:19:35 -07004825 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004826 if (data.readInt32(&colorMode) == NO_ERROR) {
4827 mForceColorMode = static_cast<ColorMode>(colorMode);
4828 }
Romain Guy54f154a2017-10-24 21:40:32 +01004829 invalidateHwcGeometry();
4830 repaintEverything();
4831 return NO_ERROR;
4832 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004833 // Deprecate, use 1030 to check whether the device is color managed.
4834 case 1024: {
4835 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004836 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004837 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004838 n = data.readInt32();
4839 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004840 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004841 Mutex::Autolock lock(mStateLock);
4842 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004843 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004844 reply->writeInt32(NO_ERROR);
4845 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004846 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004847 bool writeFile = false;
4848 {
4849 Mutex::Autolock lock(mStateLock);
4850 mTracingEnabledChanged = true;
4851 writeFile = mTracing.disable();
4852 }
4853
4854 if (writeFile) {
4855 reply->writeInt32(mTracing.writeToFile());
4856 } else {
4857 reply->writeInt32(NO_ERROR);
4858 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004859 }
4860 return NO_ERROR;
4861 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004862 case 1026: { // Get layer tracing status
4863 reply->writeBool(mTracing.isEnabled());
4864 return NO_ERROR;
4865 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004866 // Is a DisplayColorSetting supported?
4867 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004868 const auto display = getDefaultDisplayDevice();
4869 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004870 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004871 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004872
4873 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4874 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004875 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004876 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004877 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004878 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004879 reply->writeBool(true);
4880 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004881 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004882 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004883 break;
4884 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004885 reply->writeBool(
4886 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004887 break;
4888 }
4889 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004890 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004891 // Is VrFlinger active?
4892 case 1028: {
4893 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004894 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004895 return NO_ERROR;
4896 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004897 // Set buffer size for SF tracing (value in KB)
4898 case 1029: {
4899 n = data.readInt32();
4900 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4901 ALOGW("Invalid buffer size: %d KB", n);
4902 reply->writeInt32(BAD_VALUE);
4903 return BAD_VALUE;
4904 }
4905
4906 ALOGD("Updating trace buffer to %d KB", n);
4907 mTracing.setBufferSize(n * 1024);
4908 reply->writeInt32(NO_ERROR);
4909 return NO_ERROR;
4910 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004911 // Is device color managed?
4912 case 1030: {
4913 reply->writeBool(useColorManagement);
4914 return NO_ERROR;
4915 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004916 // Override default composition data space
4917 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4918 // && adb shell stop zygote && adb shell start zygote
4919 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4920 // adb shell stop zygote && adb shell start zygote
4921 case 1031: {
4922 Mutex::Autolock _l(mStateLock);
4923 n = data.readInt32();
4924 if (n) {
4925 n = data.readInt32();
4926 if (n) {
4927 Dataspace dataspace = static_cast<Dataspace>(n);
4928 if (!validateCompositionDataspace(dataspace)) {
4929 return BAD_VALUE;
4930 }
4931 mDefaultCompositionDataspace = dataspace;
4932 }
4933 n = data.readInt32();
4934 if (n) {
4935 Dataspace dataspace = static_cast<Dataspace>(n);
4936 if (!validateCompositionDataspace(dataspace)) {
4937 return BAD_VALUE;
4938 }
4939 mWideColorGamutCompositionDataspace = dataspace;
4940 }
4941 } else {
4942 // restore composition data space.
4943 mDefaultCompositionDataspace = defaultCompositionDataspace;
4944 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4945 }
4946 return NO_ERROR;
4947 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004948 // Set trace flags
4949 case 1033: {
4950 n = data.readUint32();
4951 ALOGD("Updating trace flags to 0x%x", n);
4952 mTracing.setTraceFlags(n);
4953 reply->writeInt32(NO_ERROR);
4954 return NO_ERROR;
4955 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004956 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004957 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004958 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004959 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08004960 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
4961 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08004962 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004963 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004964 } else {
4965 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004966 }
4967 return NO_ERROR;
4968 }
Ady Abraham34392f72019-04-10 11:29:27 -07004969 case 1035: {
4970 n = data.readInt32();
4971 mDebugDisplayConfigSetByBackdoor = false;
4972 if (n >= 0) {
4973 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004974 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07004975 if (result != NO_ERROR) {
4976 return result;
4977 }
4978 mDebugDisplayConfigSetByBackdoor = true;
4979 }
4980 return NO_ERROR;
4981 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004982 }
4983 }
4984 return err;
4985}
4986
Steven Thomas6d8110b2017-08-31 18:24:21 -07004987void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004988 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004989 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004990}
4991
Ana Krulec7d1d6832018-12-27 11:10:09 -08004992void SurfaceFlinger::repaintEverythingForHWC() {
4993 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004994 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004995}
4996
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004997// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4998class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004999public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005000 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
5001 ~WindowDisconnector() {
5002 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005003 }
5004
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005005private:
5006 ANativeWindow* mWindow;
5007 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07005008};
5009
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005010status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07005011 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
5012 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005013 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07005014 uint32_t reqWidth, uint32_t reqHeight,
5015 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08005016 ISurfaceComposer::Rotation rotation,
5017 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005018 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005019
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005020 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07005021
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005022 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
5023
Chia-I Wu20261cb2018-08-23 12:55:44 -07005024 sp<DisplayDevice> display;
5025 {
5026 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005027
Chia-I Wu20261cb2018-08-23 12:55:44 -07005028 display = getDisplayDeviceLocked(displayToken);
5029 if (!display) return BAD_VALUE;
5030
Chia-I Wucb023152018-08-28 12:57:23 -07005031 // set the requested width/height to the logical display viewport size
5032 // by default
5033 if (reqWidth == 0 || reqHeight == 0) {
5034 reqWidth = uint32_t(display->getViewport().width());
5035 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005036 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005037 }
5038
Peiyong Lin0e003c92018-09-17 11:09:51 -07005039 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005040 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005041
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005042 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5043 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005044 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005045 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005046}
5047
chaviw93df2ea2019-04-30 16:45:12 -07005048static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5049 switch (colorMode) {
5050 case ColorMode::DISPLAY_P3:
5051 case ColorMode::BT2100_PQ:
5052 case ColorMode::BT2100_HLG:
5053 case ColorMode::DISPLAY_BT2020:
5054 return Dataspace::DISPLAY_P3;
5055 default:
5056 return Dataspace::V0_SRGB;
5057 }
5058}
5059
5060const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5061 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5062 if (displayToken) {
5063 return getDisplayDeviceLocked(displayToken);
5064 }
5065 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5066 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005067 return getDisplayByLayerStack(displayOrLayerStack);
5068}
5069
5070const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005071 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005072 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005073 return display;
5074 }
5075 }
5076 return nullptr;
5077}
5078
5079status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5080 sp<GraphicBuffer>* outBuffer) {
5081 sp<DisplayDevice> display;
5082 uint32_t width;
5083 uint32_t height;
5084 ui::Transform::orientation_flags captureOrientation;
5085 {
5086 Mutex::Autolock _l(mStateLock);
5087 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5088 if (!display) {
5089 return BAD_VALUE;
5090 }
5091
5092 width = uint32_t(display->getViewport().width());
5093 height = uint32_t(display->getViewport().height());
5094
5095 captureOrientation = fromSurfaceComposerRotation(
5096 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07005097 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
5098 captureOrientation = ui::Transform::orientation_flags::ROT_270;
5099 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
5100 captureOrientation = ui::Transform::orientation_flags::ROT_90;
5101 }
chaviw93df2ea2019-04-30 16:45:12 -07005102 *outDataspace =
5103 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5104 }
5105
5106 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5107 false /* captureSecureLayers */);
5108
5109 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5110 std::placeholders::_1);
5111 bool ignored = false;
5112 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5113 false /* useIdentityTransform */,
5114 ignored /* outCapturedSecureLayers */);
5115}
5116
Robert Carr866455f2019-04-02 16:28:26 -07005117status_t SurfaceFlinger::captureLayers(
5118 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5119 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5120 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5121 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005122 ATRACE_CALL();
5123
5124 class LayerRenderArea : public RenderArea {
5125 public:
Robert Carr578038f2018-03-09 12:25:24 -08005126 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005127 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005128 bool childrenOnly, const Rect& displayViewport)
5129 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005130 mLayer(layer),
5131 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005132 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005133 mFlinger(flinger),
5134 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005135 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005136 Rect getBounds() const override {
5137 const Layer::State& layerState(mLayer->getDrawingState());
5138 return mLayer->getBufferSize(layerState);
5139 }
Marissa Wall61c58622018-07-18 10:12:20 -07005140 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005141 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005142 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005143 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005144 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005145 }
chaviwa76b2712017-09-20 12:02:26 -07005146 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005147 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08005148 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005149 Rect getSourceCrop() const override {
5150 if (mCrop.isEmpty()) {
5151 return getBounds();
5152 } else {
5153 return mCrop;
5154 }
5155 }
Robert Carr578038f2018-03-09 12:25:24 -08005156 class ReparentForDrawing {
5157 public:
5158 const sp<Layer>& oldParent;
5159 const sp<Layer>& newParent;
5160
Vishnu Nair4351ad52019-02-11 14:13:02 -08005161 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5162 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005163 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005164 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005165 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5166 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005167 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005168 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005169 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005170 };
5171
5172 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005173 const Rect sourceCrop = getSourceCrop();
5174 // no need to check rotation because there is none
5175 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5176 sourceCrop.height() != getReqHeight();
5177
Robert Carr578038f2018-03-09 12:25:24 -08005178 if (!mChildrenOnly) {
5179 mTransform = mLayer->getTransform().inverse();
5180 drawLayers();
5181 } else {
5182 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005183 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5184 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005185 // In the "childrenOnly" case we reparent the children to a screenshot
5186 // layer which has no properties set and which does not draw.
5187 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005188 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5189 "Screenshot Parent"s, w, h, 0,
5190 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005191
Vishnu Nair4351ad52019-02-11 14:13:02 -08005192 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005193 drawLayers();
5194 }
5195 }
chaviwa76b2712017-09-20 12:02:26 -07005196
chaviwa76b2712017-09-20 12:02:26 -07005197 private:
chaviw7206d492017-11-10 16:16:12 -08005198 const sp<Layer> mLayer;
5199 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005200
Peiyong Linefefaac2018-08-17 12:27:51 -07005201 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005202 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005203
5204 SurfaceFlinger* mFlinger;
5205 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005206 };
5207
Robert Carrc0df3122019-04-11 13:18:21 -07005208 int reqWidth = 0;
5209 int reqHeight = 0;
5210 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005211 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005212 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005213 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005214 {
5215 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005216
Robert Carrc0df3122019-04-11 13:18:21 -07005217 parent = fromHandle(layerHandleBinder);
5218 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5219 ALOGE("captureLayers called with an invalid or removed parent");
5220 return NAME_NOT_FOUND;
5221 }
5222
5223 const int uid = IPCThreadState::self()->getCallingUid();
5224 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5225 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5226 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5227 return PERMISSION_DENIED;
5228 }
5229
Vishnu Nairefc42e22019-12-03 17:36:12 -08005230 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005231 if (sourceCrop.width() <= 0) {
5232 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005233 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005234 }
5235
5236 if (sourceCrop.height() <= 0) {
5237 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005238 crop.bottom = parentSourceBounds.getHeight();
5239 }
5240
5241 if (crop.isEmpty() || frameScale <= 0.0f) {
5242 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5243 // crop was not specified, or an invalid frame scale was provided.
5244 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005245 }
5246 reqWidth = crop.width() * frameScale;
5247 reqHeight = crop.height() * frameScale;
5248
5249 for (const auto& handle : excludeHandles) {
5250 sp<Layer> excludeLayer = fromHandle(handle);
5251 if (excludeLayer != nullptr) {
5252 excludeLayers.emplace(excludeLayer);
5253 } else {
5254 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5255 return NAME_NOT_FOUND;
5256 }
5257 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005258
5259 auto display = getDisplayByLayerStack(parent->getLayerStack());
5260 if (!display) {
5261 return BAD_VALUE;
5262 }
5263
5264 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005265 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005266
Chia-I Wu20261cb2018-08-23 12:55:44 -07005267 // really small crop or frameScale
5268 if (reqWidth <= 0) {
5269 reqWidth = 1;
5270 }
5271 if (reqHeight <= 0) {
5272 reqHeight = 1;
5273 }
5274
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005275 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5276 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005277 auto traverseLayers = [parent, childrenOnly,
5278 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005279 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5280 if (!layer->isVisible()) {
5281 return;
Robert Carr578038f2018-03-09 12:25:24 -08005282 } else if (childrenOnly && layer == parent.get()) {
5283 return;
chaviwa76b2712017-09-20 12:02:26 -07005284 }
Robert Carr866455f2019-04-02 16:28:26 -07005285
5286 sp<Layer> p = layer;
5287 while (p != nullptr) {
5288 if (excludeLayers.count(p) != 0) {
5289 return;
5290 }
5291 p = p->getParent();
5292 }
5293
chaviwa76b2712017-09-20 12:02:26 -07005294 visitor(layer);
5295 });
5296 };
Robert Carr108b2c72019-04-02 16:32:58 -07005297
5298 bool outCapturedSecureLayers = false;
5299 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5300 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005301}
5302
5303status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5304 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005305 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005306 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005307 bool useIdentityTransform,
5308 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005309 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005310
Peiyong Lin0e003c92018-09-17 11:09:51 -07005311 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005312 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5313 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005314 *outBuffer =
5315 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5316 static_cast<android_pixel_format>(reqPixelFormat), 1,
5317 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005318
Robert Carr108b2c72019-04-02 16:32:58 -07005319 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5320 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005321}
5322
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005323status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5324 TraverseLayersFunction traverseLayers,
5325 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005326 bool useIdentityTransform,
5327 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005328 // This mutex protects syncFd and captureResult for communication of the return values from the
5329 // main thread back to this Binder thread
5330 std::mutex captureMutex;
5331 std::condition_variable captureCondition;
5332 std::unique_lock<std::mutex> captureLock(captureMutex);
5333 int syncFd = -1;
5334 std::optional<status_t> captureResult;
5335
Robert Carr03480e22018-01-04 16:02:06 -08005336 const int uid = IPCThreadState::self()->getCallingUid();
5337 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5338
Dominik Laskowski8c001672018-05-30 16:52:06 -07005339 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005340 // If there is a refresh pending, bug out early and tell the binder thread to try again
5341 // after the refresh.
5342 if (mRefreshPending) {
5343 ATRACE_NAME("Skipping screenshot for now");
5344 std::unique_lock<std::mutex> captureLock(captureMutex);
5345 captureResult = std::make_optional<status_t>(EAGAIN);
5346 captureCondition.notify_one();
5347 return;
5348 }
5349
5350 status_t result = NO_ERROR;
5351 int fd = -1;
5352 {
5353 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005354 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005355 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005356 useIdentityTransform, forSystem, &fd,
5357 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005358 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005359 }
5360
5361 {
5362 std::unique_lock<std::mutex> captureLock(captureMutex);
5363 syncFd = fd;
5364 captureResult = std::make_optional<status_t>(result);
5365 captureCondition.notify_one();
5366 }
5367 });
5368
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005369 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005370 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005371 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005372 while (*captureResult == EAGAIN) {
5373 captureResult.reset();
5374 result = postMessageAsync(message);
5375 if (result != NO_ERROR) {
5376 return result;
5377 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005378 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005379 }
5380 result = *captureResult;
5381 }
5382
5383 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005384 sync_wait(syncFd, -1);
5385 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005386 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005387
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005388 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005389}
5390
chaviwa76b2712017-09-20 12:02:26 -07005391void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005392 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005393 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5394 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005395 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005396
chaviwa76b2712017-09-20 12:02:26 -07005397 const auto reqWidth = renderArea.getReqWidth();
5398 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005399 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005400 const auto transform = renderArea.getTransform();
5401 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005402 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005403
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005404 renderengine::DisplaySettings clientCompositionDisplay;
5405 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005406
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005407 // assume that bounds are never offset, and that they are the same as the
5408 // buffer bounds.
5409 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005410 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005411 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005412
5413 // Now take into account the rotation flag. We append a transform that
5414 // rotates the layer stack about the origin, then translate by buffer
5415 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005416 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005417 int displacementX = 0;
5418 int displacementY = 0;
5419 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5420 switch (rotation) {
5421 case ui::Transform::ROT_90:
5422 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005423 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005424 break;
5425 case ui::Transform::ROT_180:
5426 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005427 displacementY = renderArea.getBounds().getWidth();
5428 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005429 break;
5430 case ui::Transform::ROT_270:
5431 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005432 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005433 break;
5434 default:
5435 break;
5436 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005437
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005438 // We need to transform the clipping window into the right spot.
5439 // First, rotate the clipping rectangle by the rotation hint to get the
5440 // right orientation
5441 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5442 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5443 const vec4 rotClipTL = rotMatrix * clipTL;
5444 const vec4 rotClipBR = rotMatrix * clipBR;
5445 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5446 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5447 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5448 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5449
5450 // Now reposition the clipping rectangle with the displacement vector
5451 // computed above.
5452 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005453 clientCompositionDisplay.clip =
5454 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5455 newClipRight + displacementX, newClipBottom + displacementY);
5456
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005457 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005458 clientCompositionDisplay.globalTransform =
5459 clipTransform * clientCompositionDisplay.globalTransform;
5460
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005461 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5462 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005463
chaviw50da5042018-04-09 13:49:37 -07005464 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005465
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005466 renderengine::LayerSettings fillLayer;
5467 fillLayer.source.buffer.buffer = nullptr;
5468 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5469 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5470 fillLayer.alpha = half(alpha);
5471 clientCompositionLayers.push_back(fillLayer);
5472
5473 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005474 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005475 const bool supportProtectedContent = false;
5476 Region clip(renderArea.getBounds());
5477 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5478 clip,
5479 useIdentityTransform,
5480 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5481 renderArea.isSecure(),
5482 supportProtectedContent,
5483 clearRegion,
5484 };
5485 auto result = layer->prepareClientComposition(targetSettings);
5486 if (result) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005487 std::optional<renderengine::LayerSettings> shadowLayer =
5488 layer->prepareShadowClientComposition(*result, displayViewport,
5489 clientCompositionDisplay.outputDataspace);
5490 if (shadowLayer) {
5491 clientCompositionLayers.push_back(*shadowLayer);
5492 }
Lloyd Piquef16688f2019-02-19 17:47:57 -08005493 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005494 }
chaviwa76b2712017-09-20 12:02:26 -07005495 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005496
5497 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005498 // Use an empty fence for the buffer fence, since we just created the buffer so
5499 // there is no need for synchronization with the GPU.
5500 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005501 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005502 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005503 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005504 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005505
5506 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005507}
5508
chaviwa76b2712017-09-20 12:02:26 -07005509status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5510 TraverseLayersFunction traverseLayers,
5511 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005512 bool useIdentityTransform, bool forSystem,
5513 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005514 ATRACE_CALL();
5515
chaviwa76b2712017-09-20 12:02:26 -07005516 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005517 outCapturedSecureLayers =
5518 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005519 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005520
Robert Carr03480e22018-01-04 16:02:06 -08005521 // We allow the system server to take screenshots of secure layers for
5522 // use in situations like the Screen-rotation animation and place
5523 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005524 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005525 ALOGW("FB is protected: PERMISSION_DENIED");
5526 return PERMISSION_DENIED;
5527 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005528 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005529 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005530}
5531
chaviw95ef3c42019-02-14 10:55:09 -08005532void SurfaceFlinger::setInputWindowsFinished() {
5533 Mutex::Autolock _l(mStateLock);
5534
5535 mPendingSyncInputWindows = false;
5536 mTransactionCV.broadcast();
5537}
chaviw5f21a5e2019-02-14 10:00:34 -08005538
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005539// ---------------------------------------------------------------------------
5540
Dan Stoza412903f2017-04-27 13:42:17 -07005541void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5542 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005543}
5544
Dan Stoza412903f2017-04-27 13:42:17 -07005545void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5546 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005547}
5548
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005549void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005550 const LayerVector::Visitor& visitor) {
5551 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005552 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005553 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005554 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005555 continue;
5556 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005557 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005558 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005559 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005560 return;
5561 }
chaviwa76b2712017-09-20 12:02:26 -07005562 if (!layer->isVisible()) {
5563 return;
5564 }
5565 visitor(layer);
5566 });
5567 }
5568}
5569
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005570status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5571 HwcConfigIndexType defaultConfig,
5572 float minRefreshRate,
5573 float maxRefreshRate) {
5574 Mutex::Autolock lock(mStateLock);
5575
Dominik Laskowski22488f62019-03-28 09:53:04 -07005576 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005577 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5578 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5579 // it should go thru setDesiredActiveConfig, similar to primary display.
5580 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5581 const auto displayId = display->getId();
5582 LOG_ALWAYS_FATAL_IF(!displayId);
5583
5584 HWC2::VsyncPeriodChangeConstraints constraints;
5585 constraints.desiredTimeNanos = systemTime();
5586 constraints.seamlessRequired = false;
5587
5588 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005589 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5590 constraints, &timeline) < 0) {
5591 return BAD_VALUE;
5592 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005593 if (timeline.refreshRequired) {
5594 repaintEverythingForHWC();
5595 }
5596
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005597 auto configId = HwcConfigIndexType(defaultConfig);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005598 display->setActiveConfig(configId);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005599 const nsecs_t vsyncPeriod =
5600 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).vsyncPeriod;
5601 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, configId,
5602 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005603 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005604 }
5605
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005606 if (mDebugDisplayConfigSetByBackdoor) {
5607 // ignore this request as config is overridden by backdoor
5608 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005609 }
5610
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005611 bool policyChanged;
5612 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5613 &policyChanged) < 0) {
5614 return BAD_VALUE;
5615 }
5616 if (!policyChanged) {
5617 return NO_ERROR;
5618 }
5619
5620 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5621 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005622
5623 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5624 // that listeners that care about a change in allowed configs can get the notification.
5625 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005626 const nsecs_t vsyncPeriod =
5627 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005628 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005629 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005630
Ady Abraham2139f732019-11-13 18:56:40 -08005631 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5632 auto configId = mScheduler->getPreferredConfigId();
5633 auto preferredRefreshRate = configId
5634 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5635 : mRefreshRateConfigs->getMinRefreshRateByPolicy();
5636 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5637 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5638 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5639 ALOGV("switching to Scheduler preferred config %d",
5640 preferredRefreshRate.configId.value());
5641 setDesiredActiveConfig(
5642 {preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
5643 } else {
5644 // Set the highest allowed config
5645 setDesiredActiveConfig({mRefreshRateConfigs->getMaxRefreshRateByPolicy().configId,
5646 Scheduler::ConfigEvent::Changed});
5647 }
5648 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005649 ALOGV("switching to config %d", defaultConfig.value());
5650 setDesiredActiveConfig({defaultConfig, Scheduler::ConfigEvent::Changed});
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005651 }
5652
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005653 return NO_ERROR;
5654}
5655
Ana Krulec0782b882019-10-15 17:34:54 -07005656status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005657 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005658 float maxRefreshRate) {
5659 ATRACE_CALL();
5660
5661 if (!displayToken) {
5662 return BAD_VALUE;
5663 }
5664
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005665 status_t result = NO_ERROR;
5666
Ana Krulec234bb162019-11-10 22:55:55 +01005667 postMessageSync(new LambdaMessage([&]() {
5668 const auto display = getDisplayDeviceLocked(displayToken);
5669 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005670 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005671 ALOGE("Attempt to set desired display configs for invalid display token %p",
5672 displayToken.get());
5673 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005674 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005675 ALOGW("Attempt to set desired display configs for virtual display");
5676 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005677 result =
5678 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5679 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005680 }
5681 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005682
5683 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005684}
5685
5686status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005687 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005688 float* outMinRefreshRate,
5689 float* outMaxRefreshRate) {
5690 ATRACE_CALL();
5691
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005692 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005693 return BAD_VALUE;
5694 }
5695
5696 Mutex::Autolock lock(mStateLock);
5697 const auto display = getDisplayDeviceLocked(displayToken);
5698 if (!display) {
5699 return NAME_NOT_FOUND;
5700 }
5701
5702 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005703 HwcConfigIndexType defaultConfig;
5704 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5705 *outDefaultConfig = defaultConfig.value();
5706 return NO_ERROR;
5707 } else if (display->isVirtual()) {
5708 return BAD_VALUE;
5709 } else {
5710 const auto displayId = display->getId();
5711 if (!displayId) {
5712 return BAD_VALUE;
5713 }
5714 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5715 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5716 *outMinRefreshRate = 1e9f / vsyncPeriod;
5717 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5718 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005719 }
Ana Krulec0782b882019-10-15 17:34:54 -07005720}
5721
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005722void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005723 mFlinger->setInputWindowsFinished();
5724}
5725
Robert Carrc0df3122019-04-11 13:18:21 -07005726sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005727 BBinder* b = nullptr;
5728 if (handle) {
5729 b = handle->localBinder();
5730 }
Robert Carrc0df3122019-04-11 13:18:21 -07005731 if (b == nullptr) {
5732 return nullptr;
5733 }
5734 auto it = mLayersByLocalBinderToken.find(b);
5735 if (it != mLayersByLocalBinderToken.end()) {
5736 return it->second.promote();
5737 }
5738 return nullptr;
5739}
5740
Dominik Laskowski75848362019-11-11 17:57:20 -08005741void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005742 mNumLayers++;
5743 mScheduler->registerLayer(layer);
5744}
5745
5746void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5747 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005748 removeFromOffscreenLayers(layer);
5749}
5750
5751// WARNING: ONLY CALL THIS FROM LAYER DTOR
5752// Here we add children in the current state to offscreen layers and remove the
5753// layer itself from the offscreen layer list. Since
5754// this is the dtor, it is safe to access the current state. This keeps us
5755// from dangling children layers such that they are not reachable from the
5756// Drawing state nor the offscreen layer list
5757// See b/141111965
5758void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5759 for (auto& child : layer->getCurrentChildren()) {
5760 mOffscreenLayers.emplace(child.get());
5761 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005762 mOffscreenLayers.erase(layer);
5763}
5764
Alec Mouri4545a8a2019-08-08 20:05:32 -07005765void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5766 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5767}
5768
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005769status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5770 float lightPosY, float lightPosZ,
5771 float lightRadius) {
5772 Mutex::Autolock _l(mStateLock);
5773 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5774 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5775 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5776 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5777 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5778
5779 // these values are overridden when calculating the shadow settings for a layer.
5780 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5781 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005782 return NO_ERROR;
5783}
5784
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005785} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005786
Mathias Agopian3f844832013-08-07 21:24:32 -07005787#if defined(__gl_h_)
5788#error "don't include gl/gl.h in this file"
5789#endif
5790
5791#if defined(__gl2_h_)
5792#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005793#endif