blob: 4f042db3765f7ee58c153c50ed80c0cad3867dcc [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
166#pragma clang diagnostic pop
167
Steven Thomasb02664d2017-07-26 18:48:28 -0700168class ConditionalLock {
169public:
170 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
171 if (lock) {
172 mMutex.lock();
173 }
174 }
175 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
176private:
177 Mutex& mMutex;
178 bool mLocked;
179};
Peiyong Linfca547f2018-07-09 13:03:33 -0700180
Peiyong Lin9d846a52018-11-05 13:18:20 -0800181// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
182bool validateCompositionDataspace(Dataspace dataspace) {
183 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
184}
185
Steven Thomasb02664d2017-07-26 18:48:28 -0700186} // namespace anonymous
187
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800188// ---------------------------------------------------------------------------
189
Mathias Agopian99b49842011-06-27 16:05:52 -0700190const String16 sHardwareTest("android.permission.HARDWARE_TEST");
191const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
192const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
193const String16 sDump("android.permission.DUMP");
194
195// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700196int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700197bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800198uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800199bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800200bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800201int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600202bool SurfaceFlinger::hasWideColorDisplay;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800203ui::Rotation SurfaceFlinger::internalDisplayOrientation = ui::ROTATION_0;
Peiyong Lin13effd12018-07-24 17:01:47 -0700204bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700205bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700206Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
207ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
208Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
209ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700210
Kalle Raitaa099a242017-01-11 11:17:29 -0800211std::string getHwcServiceName() {
212 char value[PROPERTY_VALUE_MAX] = {};
213 property_get("debug.sf.hwc_service_name", value, "default");
214 ALOGI("Using HWComposer service: '%s'", value);
215 return std::string(value);
216}
217
218bool useTrebleTestingOverride() {
219 char value[PROPERTY_VALUE_MAX] = {};
220 property_get("debug.sf.treble_testing_override", value, "false");
221 ALOGI("Treble testing override: '%s'", value);
222 return std::string(value) == "true";
223}
224
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800225std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
226 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800227 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700228 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800229 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700230 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800231 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700232 return std::string("Enhanced");
233 default:
234 return std::string("Unknown ") +
235 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800236 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800237}
238
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700239SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800240
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700241SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
242 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700243 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700244 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700245 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700246 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700247 mCompositionEngine(mFactory.createCompositionEngine()),
Valerie Haud251afb2019-03-29 14:19:02 -0700248 mPendingSyncInputWindows(false) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800249
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700250SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800251 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800252
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900253 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800254
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900255 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700256
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900257 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700258
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900259 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800260
Steven Thomas050b2c82017-03-06 11:45:16 -0800261 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900262 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800263
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900264 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800265
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900266 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700267
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900268 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600269
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900270 mDefaultCompositionDataspace =
271 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700272 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
273 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900274 defaultCompositionDataspace = mDefaultCompositionDataspace;
275 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
276 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
277 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
278 wideColorGamutCompositionPixelFormat =
279 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700280
Yichi Chenda901bf2019-06-28 14:58:27 +0800281 mColorSpaceAgnosticDataspace =
282 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800285
Dominik Laskowski718f9602019-11-09 20:01:35 -0800286 using Values = SurfaceFlingerProperties::primary_display_orientation_values;
287 switch (primary_display_orientation(Values::ORIENTATION_0)) {
288 case Values::ORIENTATION_0:
Iris Chang7501ed62018-04-30 14:45:42 +0800289 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800290 case Values::ORIENTATION_90:
291 internalDisplayOrientation = ui::ROTATION_90;
Iris Chang7501ed62018-04-30 14:45:42 +0800292 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800293 case Values::ORIENTATION_180:
294 internalDisplayOrientation = ui::ROTATION_180;
Iris Chang7501ed62018-04-30 14:45:42 +0800295 break;
Dominik Laskowski718f9602019-11-09 20:01:35 -0800296 case Values::ORIENTATION_270:
297 internalDisplayOrientation = ui::ROTATION_270;
Iris Chang7501ed62018-04-30 14:45:42 +0800298 break;
299 }
Dominik Laskowski718f9602019-11-09 20:01:35 -0800300 ALOGV("Internal Display Orientation: %s", toCString(internalDisplayOrientation));
Iris Chang7501ed62018-04-30 14:45:42 +0800301
Sundong Ahn85131bd2019-02-18 15:51:53 +0900302 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800303
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800304 // debugging stuff...
305 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700306
Mathias Agopianb4b17302013-03-20 18:36:41 -0700307 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700308 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700309
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800310 property_get("debug.sf.showupdates", value, "0");
311 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700312
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700313 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000314
315 // DDMS debugging deprecated (b/120782499)
316 property_get("debug.sf.ddms", value, "0");
317 int debugDdms = atoi(value);
318 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700319
320 property_get("debug.sf.disable_backpressure", value, "0");
321 mPropagateBackpressure = !atoi(value);
322 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700323
Ady Abrahamadb9a992019-09-19 21:21:55 +0000324 property_get("debug.sf.enable_gl_backpressure", value, "0");
325 mPropagateBackpressureClientComposition = atoi(value);
326 ALOGI_IF(mPropagateBackpressureClientComposition,
327 "Enabling backpressure propagation for Client Composition");
328
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800329 property_get("debug.sf.enable_hwc_vds", value, "0");
330 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800331 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800332
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800333 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800334 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800335 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700336
Yiwei Zhang243b3782018-05-15 17:40:04 -0700337 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700338 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
339 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
340
Dan Stozaec460082018-12-17 15:35:09 -0800341 property_get("debug.sf.luma_sampling", value, "1");
342 mLumaSampling = atoi(value);
343
Romain Guy11d63f42017-07-20 12:47:14 -0700344 // We should be reading 'persist.sys.sf.color_saturation' here
345 // but since /data may be encrypted, we need to wait until after vold
346 // comes online to attempt to read the property. The property is
347 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800348
349 if (useTrebleTestingOverride()) {
350 // Without the override SurfaceFlinger cannot connect to HIDL
351 // services that are not listed in the manifests. Considered
352 // deriving the setting from the set service name, but it
353 // would be brittle if the name that's not 'default' is used
354 // for production purposes later on.
355 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
356 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800357}
358
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800359void SurfaceFlinger::onFirstRef()
360{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800361 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800362}
363
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700364SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800365
Dan Stozac7014012014-02-14 15:03:43 -0800366void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800367{
368 // the window manager died on us. prepare its eulogy.
369
Andy McFadden13a082e2012-08-24 10:16:42 -0700370 // restore initial conditions (default device unblank, etc)
371 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800372
373 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700374 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800375}
376
Robert Carr1db73f62016-12-21 12:58:51 -0800377static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700378 status_t err = client->initCheck();
379 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800380 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800381 }
Robert Carr1db73f62016-12-21 12:58:51 -0800382 return nullptr;
383}
384
385sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
386 return initClient(new Client(this));
387}
388
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700389sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
390 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700391{
392 class DisplayToken : public BBinder {
393 sp<SurfaceFlinger> flinger;
394 virtual ~DisplayToken() {
395 // no more references, this display must be terminated
396 Mutex::Autolock _l(flinger->mStateLock);
397 flinger->mCurrentState.displays.removeItem(this);
398 flinger->setTransactionFlags(eDisplayTransactionNeeded);
399 }
400 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700401 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700402 : flinger(flinger) {
403 }
404 };
405
406 sp<BBinder> token = new DisplayToken(this);
407
408 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700409 // Display ID is assigned when virtual display is allocated by HWC.
410 DisplayDeviceState state;
411 state.isSecure = secure;
412 state.displayName = displayName;
413 mCurrentState.displays.add(token, state);
414 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700415 return token;
416}
417
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700418void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700419 Mutex::Autolock _l(mStateLock);
420
Dominik Laskowski075d3172018-05-24 15:50:06 -0700421 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
422 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700423 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700424 return;
425 }
426
Dominik Laskowski075d3172018-05-24 15:50:06 -0700427 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
428 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700429 ALOGE("destroyDisplay called for non-virtual display");
430 return;
431 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700432 mInterceptor->saveDisplayDeletion(state.sequenceId);
433 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700434 setTransactionFlags(eDisplayTransactionNeeded);
435}
436
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800437std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
438 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700439
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800440 const auto internalDisplayId = getInternalDisplayIdLocked();
441 if (!internalDisplayId) {
442 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700443 }
444
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800445 std::vector<PhysicalDisplayId> displayIds;
446 displayIds.reserve(mPhysicalDisplayTokens.size());
447 displayIds.push_back(internalDisplayId->value);
448
449 for (const auto& [id, token] : mPhysicalDisplayTokens) {
450 if (id != *internalDisplayId) {
451 displayIds.push_back(id.value);
452 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700453 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700454
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800455 return displayIds;
456}
457
458sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
459 Mutex::Autolock lock(mStateLock);
460 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700461}
462
Ady Abraham37965d42018-11-01 13:43:32 -0700463status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
464 if (!outGetColorManagement) {
465 return BAD_VALUE;
466 }
467 *outGetColorManagement = useColorManagement;
468 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700469}
470
Lloyd Pique441d5042018-10-18 16:49:51 -0700471HWComposer& SurfaceFlinger::getHwComposer() const {
472 return mCompositionEngine->getHwComposer();
473}
474
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700475renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
476 return mCompositionEngine->getRenderEngine();
477}
478
Lloyd Pique70d91362018-10-18 16:02:55 -0700479compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
480 return *mCompositionEngine.get();
481}
482
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800483void SurfaceFlinger::bootFinished()
484{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700485 if (mStartPropertySetThread->join() != NO_ERROR) {
486 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800487 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800488 const nsecs_t now = systemTime();
489 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000490 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700491
Mikael Pessa90092f42019-08-26 17:22:04 -0700492 mFrameTracer->initialize();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700493
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700494 // wait patiently for the window manager death
495 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700496 mWindowManager = defaultServiceManager()->getService(name);
497 if (mWindowManager != 0) {
498 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700499 }
Robert Carr720e5062018-07-30 17:45:14 -0700500 sp<IBinder> input(defaultServiceManager()->getService(
501 String16("inputflinger")));
502 if (input == nullptr) {
503 ALOGE("Failed to link to input service");
504 } else {
505 mInputFlinger = interface_cast<IInputFlinger>(input);
506 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700507
Steven Thomas050b2c82017-03-06 11:45:16 -0800508 if (mVrFlinger) {
509 mVrFlinger->OnBootFinished();
510 }
511
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700512 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700513 // formerly we would just kill the process, but we now ask it to exit so it
514 // can choose where to stop the animation.
515 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700516
517 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
518 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
519 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700520
Ana Krulecbd6654b2019-02-15 15:18:15 -0800521 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800522 readPersistentProperties();
523 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800524
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700525 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
526 // set the refresh rate according to the policy
Ady Abraham2139f732019-11-13 18:56:40 -0800527 const auto& performanceRefreshRate = mRefreshRateConfigs->getMaxRefreshRateByPolicy();
528 changeRefreshRateLocked(performanceRefreshRate, Scheduler::ConfigEvent::None);
Ana Krulecbd6654b2019-02-15 15:18:15 -0800529 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800530 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800531}
532
Dan Stoza436ccf32018-06-21 12:10:12 -0700533uint32_t SurfaceFlinger::getNewTexture() {
534 {
535 std::lock_guard lock(mTexturePoolMutex);
536 if (!mTexturePool.empty()) {
537 uint32_t name = mTexturePool.back();
538 mTexturePool.pop_back();
539 ATRACE_INT("TexturePoolSize", mTexturePool.size());
540 return name;
541 }
542
543 // The pool was too small, so increase it for the future
544 ++mTexturePoolSize;
545 }
546
547 // The pool was empty, so we need to get a new texture name directly using a
548 // blocking call to the main thread
549 uint32_t name = 0;
550 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
551 return name;
552}
553
Mathias Agopian3f844832013-08-07 21:24:32 -0700554void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700555 std::lock_guard lock(mTexturePoolMutex);
556 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
557 // to actually delete this or not based on mTexturePoolSize
558 mTexturePool.push_back(texture);
559 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700560}
561
Wei Wangf9b05ee2017-07-19 20:59:39 -0700562// Do not call property_set on main thread which will be blocked by init
563// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700564void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700565 ALOGI( "SurfaceFlinger's main thread ready to run. "
566 "Initializing graphics H/W...");
Steven Thomasb02664d2017-07-26 18:48:28 -0700567 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800568
Steven Thomasb02664d2017-07-26 18:48:28 -0700569 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700570 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800571 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700572 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
573 renderengine::RenderEngineCreationArgs::Builder()
574 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
575 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
576 .setUseColorManagerment(useColorManagement)
577 .setEnableProtectedContext(enable_protected_contents(false))
578 .setPrecacheToneMapperShaderOnly(false)
579 .setContextPriority(useContextPriority
580 ? renderengine::RenderEngine::ContextPriority::HIGH
581 : renderengine::RenderEngine::ContextPriority::MEDIUM)
582 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800583 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700584
585 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
586 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700587 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
588 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800589 // Process any initial hotplug and resulting display changes.
590 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700591 const auto display = getDefaultDisplayDeviceLocked();
592 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700593 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700594 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800595
Steven Thomas050b2c82017-03-06 11:45:16 -0800596 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700597 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700598 // This callback is called from the vr flinger dispatch thread. We
599 // need to call signalTransaction(), which requires holding
600 // mStateLock when we're not on the main thread. Acquiring
601 // mStateLock from the vr flinger dispatch thread might trigger a
602 // deadlock in surface flinger (see b/66916578), so post a message
603 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700604 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700605 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
606 mVrFlingerRequestsDisplay = requestDisplay;
607 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700608 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800609 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700610 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
611 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700612 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700613 .value_or(0),
614 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800615 if (!mVrFlinger) {
616 ALOGE("Failed to start vrflinger");
617 }
618 }
619
Mathias Agopian92a979a2012-08-02 18:32:23 -0700620 // initialize our drawing state
621 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700622
Andy McFadden13a082e2012-08-24 10:16:42 -0700623 // set initial conditions (e.g. unblank default device)
624 initializeDisplays();
625
Steven Thomas137d4bc2019-07-25 16:55:14 -0700626 char primeShaderCache[PROPERTY_VALUE_MAX];
627 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
628 if (atoi(primeShaderCache)) {
629 getRenderEngine().primeCache();
630 }
Dan Stoza4e637772016-07-28 13:31:51 -0700631
Wei Wangf9b05ee2017-07-19 20:59:39 -0700632 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700633
634 const bool presentFenceReliable =
635 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
636 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700637
638 if (mStartPropertySetThread->Start() != NO_ERROR) {
639 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800640 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800641
Dan Stoza9e56aa02015-11-02 13:00:03 -0800642 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700643}
644
Romain Guy11d63f42017-07-20 12:47:14 -0700645void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700646 Mutex::Autolock _l(mStateLock);
647
Romain Guy11d63f42017-07-20 12:47:14 -0700648 char value[PROPERTY_VALUE_MAX];
649
650 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800651 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700652 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800653 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100654
655 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700656 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800657
658 property_get("persist.sys.sf.color_mode", value, "0");
659 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700660}
661
Mathias Agopiana67e4182012-06-19 17:26:12 -0700662void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800663 // Start boot animation service by setting a property mailbox
664 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700665 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800666 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700667 if (mStartPropertySetThread->join() != NO_ERROR) {
668 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800669 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700670}
671
Mathias Agopian875d8e12013-06-07 15:35:48 -0700672size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700673 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700674}
675
Mathias Agopian875d8e12013-06-07 15:35:48 -0700676size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700677 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700678}
679
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800680// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800681
Jamie Gennis582270d2011-08-17 18:19:00 -0700682bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800683 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800684 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800685 return authenticateSurfaceTextureLocked(bufferProducer);
686}
687
688bool SurfaceFlinger::authenticateSurfaceTextureLocked(
689 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800690 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800691 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800692}
693
Brian Anderson6b376712017-04-04 10:51:39 -0700694status_t SurfaceFlinger::getSupportedFrameTimestamps(
695 std::vector<FrameEvent>* outSupported) const {
696 *outSupported = {
697 FrameEvent::REQUESTED_PRESENT,
698 FrameEvent::ACQUIRE,
699 FrameEvent::LATCH,
700 FrameEvent::FIRST_REFRESH_START,
701 FrameEvent::LAST_REFRESH_START,
702 FrameEvent::GPU_COMPOSITION_DONE,
703 FrameEvent::DEQUEUE_READY,
704 FrameEvent::RELEASE,
705 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700706 ConditionalLock _l(mStateLock,
707 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700708 if (!getHwComposer().hasCapability(
709 HWC2::Capability::PresentFenceIsNotReliable)) {
710 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
711 }
712 return NO_ERROR;
713}
714
Dominik Laskowski22488f62019-03-28 09:53:04 -0700715status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
716 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700717 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700718 return BAD_VALUE;
719 }
720
Dominik Laskowski22488f62019-03-28 09:53:04 -0700721 Mutex::Autolock lock(mStateLock);
722
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800723 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700724 if (!displayId) {
725 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700726 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700727
Mathias Agopian8b736f12012-08-13 17:54:26 -0700728 // TODO: Not sure if display density should handled by SF any longer
729 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700730 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700731 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700732 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800733 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700734 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700735 }
736 return density;
737 }
738 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700739 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700740 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700741 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700742 return getDensityFromProperty("ro.sf.lcd_density"); }
743 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700744
Dan Stoza7f7da322014-05-02 15:26:25 -0700745 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700746
Dominik Laskowski075d3172018-05-24 15:50:06 -0700747 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700748 DisplayInfo info = DisplayInfo();
749
Dan Stoza9e56aa02015-11-02 13:00:03 -0800750 float xdpi = hwConfig->getDpiX();
751 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700752
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700753 info.w = hwConfig->getWidth();
754 info.h = hwConfig->getHeight();
755 // Default display viewport to display width and height
756 info.viewportW = info.w;
757 info.viewportH = info.h;
758
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800759 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700760 // The density of the device is provided by a build property
761 float density = Density::getBuildDensity() / 160.0f;
762 if (density == 0) {
763 // the build doesn't provide a density -- this is wrong!
764 // use xdpi instead
765 ALOGE("ro.sf.lcd_density must be defined as a build property");
766 density = xdpi / 160.0f;
767 }
768 if (Density::getEmuDensity()) {
769 // if "qemu.sf.lcd_density" is specified, it overrides everything
770 xdpi = ydpi = density = Density::getEmuDensity();
771 density /= 160.0f;
772 }
773 info.density = density;
774
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700775 const auto display = getDefaultDisplayDeviceLocked();
Dominik Laskowski718f9602019-11-09 20:01:35 -0800776 info.orientation = display->getOrientation();
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700777
778 // This is for screenrecord
779 const Rect viewport = display->getViewport();
780 if (viewport.isValid()) {
781 info.viewportW = uint32_t(viewport.getWidth());
782 info.viewportH = uint32_t(viewport.getHeight());
783 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700784 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700785 } else {
786 // TODO: where should this value come from?
787 static const int TV_DENSITY = 213;
788 info.density = TV_DENSITY / 160.0f;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700789
790 const auto display = getDisplayDeviceLocked(displayToken);
791 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700792 }
793
Dan Stoza7f7da322014-05-02 15:26:25 -0700794 info.xdpi = xdpi;
795 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800796 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Ady Abraham2139f732019-11-13 18:56:40 -0800797
Ady Abraham9e16a482019-12-03 17:19:41 -0800798 const auto offset = mPhaseConfiguration->getOffsetsForRefreshRate(info.fps);
Ady Abraham796beb02019-04-11 15:23:07 -0700799 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800800
Andy McFadden91b2ca82014-06-13 14:04:23 -0700801 // This is how far in advance a buffer must be queued for
802 // presentation at a given time. If you want a buffer to appear
803 // on the screen at time N, you must submit the buffer before
804 // (N - presentationDeadline).
805 //
806 // Normally it's one full refresh period (to give SF a chance to
807 // latch the buffer), but this can be reduced by configuring a
808 // DispSync offset. Any additional delays introduced by the hardware
809 // composer or panel must be accounted for here.
810 //
811 // We add an additional 1ms to allow for processing time and
812 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700813 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700814
815 // All non-virtual displays are currently considered secure.
816 info.secure = true;
817
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800818 if (displayId == getInternalDisplayIdLocked() &&
Dominik Laskowski718f9602019-11-09 20:01:35 -0800819 (internalDisplayOrientation == ui::ROTATION_90 ||
820 internalDisplayOrientation == ui::ROTATION_270)) {
Iris Chang7501ed62018-04-30 14:45:42 +0800821 std::swap(info.w, info.h);
822 }
823
Michael Wright28f24d02016-07-12 13:30:53 -0700824 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700825 }
826
Dan Stoza7f7da322014-05-02 15:26:25 -0700827 return NO_ERROR;
828}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700829
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700830status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
831 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700832 return BAD_VALUE;
833 }
834
Ana Krulecc2870422019-01-29 19:00:58 -0800835 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700836 return NO_ERROR;
837}
838
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700839int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
840 const auto display = getDisplayDevice(displayToken);
841 if (!display) {
842 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800843 return BAD_VALUE;
844 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700845
Steven Thomasc9098452019-09-30 17:15:05 -0700846 if (display->isPrimary()) {
847 std::lock_guard<std::mutex> lock(mActiveConfigLock);
848 if (mDesiredActiveConfigChanged) {
Ady Abraham2139f732019-11-13 18:56:40 -0800849 return mDesiredActiveConfig.configId.value();
Steven Thomasc9098452019-09-30 17:15:05 -0700850 }
Steven Thomasc9098452019-09-30 17:15:05 -0700851 }
Ady Abraham2139f732019-11-13 18:56:40 -0800852
853 return display->getActiveConfig().value();
Dan Stoza7f7da322014-05-02 15:26:25 -0700854}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700855
Ady Abraham03b02dd2019-03-21 15:40:11 -0700856void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800857 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800858 auto refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(info.configId);
859 ALOGV("setDesiredActiveConfig(%s)", refreshRate.name.c_str());
Ana Krulec7d1d6832018-12-27 11:10:09 -0800860
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800861 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800862 // config twice. However event generation config might have changed so we need to update it
863 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800864 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700865 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
866 mDesiredActiveConfig = info;
867 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800868
869 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800870 // This will trigger HWC refresh without resetting the idle timer.
871 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700872 // Start receiving vsync samples now, so that we can detect a period
873 // switch.
874 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700875 // As we called to set period, we will call to onRefreshRateChangeCompleted once
876 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700877 mVSyncModulator->onRefreshRateChangeInitiated();
Ady Abraham2139f732019-11-13 18:56:40 -0800878
Ady Abraham9e16a482019-12-03 17:19:41 -0800879 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
880 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800881 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800882 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700883
884 if (mRefreshRateOverlay) {
Ady Abraham2139f732019-11-13 18:56:40 -0800885 mRefreshRateOverlay->changeRefreshRate(refreshRate);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700886 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800887}
888
889status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
890 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800891
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100892 if (!displayToken) {
893 return BAD_VALUE;
894 }
Ady Abraham838de062019-02-04 10:24:03 -0800895
Ana Kruleced3a8cc2019-11-14 00:55:07 +0100896 status_t result = NO_ERROR;
897
898 postMessageSync(new LambdaMessage([&]() {
899 const auto display = getDisplayDeviceLocked(displayToken);
900 if (!display) {
901 ALOGE("Attempt to set allowed display configs for invalid display token %p",
902 displayToken.get());
903 result = BAD_VALUE;
904 } else if (display->isVirtual()) {
905 ALOGW("Attempt to set allowed display configs for virtual display");
906 result = BAD_VALUE;
907 } else {
908 HwcConfigIndexType config(mode);
909 const auto& refreshRate = mRefreshRateConfigs->getRefreshRateFromConfigId(config);
910 result = setDesiredDisplayConfigSpecsInternal(display, config, refreshRate.fps,
911 refreshRate.fps);
912 }
913 }));
914
915 return result;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800916}
917
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800918void SurfaceFlinger::setActiveConfigInternal() {
919 ATRACE_CALL();
920
Dominik Laskowski22488f62019-03-28 09:53:04 -0700921 const auto display = getDefaultDisplayDeviceLocked();
922 if (!display) {
923 return;
924 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800925
Dominik Laskowski22488f62019-03-28 09:53:04 -0700926 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham2139f732019-11-13 18:56:40 -0800927 mRefreshRateConfigs->setCurrentConfigId(mUpcomingActiveConfig.configId);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700928 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800929 display->setActiveConfig(mUpcomingActiveConfig.configId);
930
Ady Abraham2139f732019-11-13 18:56:40 -0800931 auto refreshRate =
932 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800933 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
934 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham2139f732019-11-13 18:56:40 -0800935 ATRACE_INT("ActiveConfigFPS", refreshRate.fps);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700936
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800937 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Alec Mouri60aee1c2019-10-28 16:18:59 -0700938 const nsecs_t vsyncPeriod =
939 mRefreshRateConfigs->getRefreshRateFromConfigId(mUpcomingActiveConfig.configId)
940 .vsyncPeriod;
Ady Abraham447052e2019-02-13 16:07:27 -0800941 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -0700942 mUpcomingActiveConfig.configId, vsyncPeriod);
Ady Abraham447052e2019-02-13 16:07:27 -0800943 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800944}
945
Ady Abraham53852a52019-05-28 18:07:44 -0700946void SurfaceFlinger::desiredActiveConfigChangeDone() {
947 std::lock_guard<std::mutex> lock(mActiveConfigLock);
948 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
949 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700950
951 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham2139f732019-11-13 18:56:40 -0800952 auto refreshRate =
953 mRefreshRateConfigs->getRefreshRateFromConfigId(mDesiredActiveConfig.configId);
Ady Abraham9e16a482019-12-03 17:19:41 -0800954 mPhaseConfiguration->setRefreshRateFps(refreshRate.fps);
955 mVSyncModulator->setPhaseOffsets(mPhaseConfiguration->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700956}
957
Dominik Laskowski22488f62019-03-28 09:53:04 -0700958bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800959 ATRACE_CALL();
Ady Abraham2139f732019-11-13 18:56:40 -0800960 ALOGV("performSetActiveConfig");
Ady Abrahamb838aed2019-02-12 15:30:16 -0800961 if (mCheckPendingFence) {
Ady Abrahambe0f9482019-04-24 15:41:53 -0700962 if (previousFrameMissed()) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800963 // fence has not signaled yet. wait for the next invalidate
Ady Abraham8532d012019-05-08 14:50:56 -0700964 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800965 return true;
966 }
967
968 // We received the present fence from the HWC, so we assume it successfully updated
969 // the config, hence we update SF.
970 mCheckPendingFence = false;
971 setActiveConfigInternal();
972 }
973
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800974 // Store the local variable to release the lock.
975 ActiveConfigInfo desiredActiveConfig;
976 {
977 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abrahamb838aed2019-02-12 15:30:16 -0800978 if (!mDesiredActiveConfigChanged) {
979 return false;
980 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800981 desiredActiveConfig = mDesiredActiveConfig;
982 }
983
Ady Abraham2139f732019-11-13 18:56:40 -0800984 auto refreshRate =
985 mRefreshRateConfigs->getRefreshRateFromConfigId(desiredActiveConfig.configId);
986 ALOGV("performSetActiveConfig changing active config to %d(%s)", refreshRate.configId.value(),
987 refreshRate.name.c_str());
Dominik Laskowski22488f62019-03-28 09:53:04 -0700988 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800989 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
990 // display is not valid or we are already in the requested mode
991 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -0700992 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800993 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800994 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800995
Ady Abraham838de062019-02-04 10:24:03 -0800996 // Desired active config was set, it is different than the config currently in use, however
997 // allowed configs might have change by the time we process the refresh.
998 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -0700999 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -07001000 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -08001001 return false;
1002 }
Alec Mouri7f015182019-07-11 13:56:22 -07001003
Ady Abrahamb838aed2019-02-12 15:30:16 -08001004 mUpcomingActiveConfig = desiredActiveConfig;
1005 const auto displayId = display->getId();
1006 LOG_ALWAYS_FATAL_IF(!displayId);
1007
Ady Abraham2139f732019-11-13 18:56:40 -08001008 ATRACE_INT("ActiveConfigFPS_HWC", refreshRate.fps);
Ady Abrahamb838aed2019-02-12 15:30:16 -08001009
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001010 // TODO(b/142753666) use constrains
1011 HWC2::VsyncPeriodChangeConstraints constraints;
1012 constraints.desiredTimeNanos = systemTime();
1013 constraints.seamlessRequired = false;
1014
1015 HWC2::VsyncPeriodChangeTimeline outTimeline;
1016 auto status =
1017 getHwComposer().setActiveConfigWithConstraints(*displayId,
1018 mUpcomingActiveConfig.configId.value(),
1019 constraints, &outTimeline);
1020 if (status != NO_ERROR) {
1021 LOG_ALWAYS_FATAL("setActiveConfigWithConstraints failed: %d", status);
1022 return false;
1023 }
1024
1025 mScheduler->onNewVsyncPeriodChangeTimeline(outTimeline);
1026 // Scheduler will submit an empty frame to HWC if needed.
Ady Abrahamb838aed2019-02-12 15:30:16 -08001027 mCheckPendingFence = true;
Ady Abrahamb838aed2019-02-12 15:30:16 -08001028 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001029}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001030
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001031status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1032 Vector<ColorMode>* outColorModes) {
1033 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001034 return BAD_VALUE;
1035 }
1036
Peiyong Lina52f0292018-03-14 17:26:31 -07001037 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001038 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001039 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001040 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1041
1042 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1043 if (!displayId) {
1044 return NAME_NOT_FOUND;
1045 }
1046
Dominik Laskowski075d3172018-05-24 15:50:06 -07001047 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001048 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001049 }
Michael Wright28f24d02016-07-12 13:30:53 -07001050 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001051
1052 // If it's built-in display and the configuration claims it's not wide color capable,
1053 // filter out all wide color modes. The typical reason why this happens is that the
1054 // hardware is not good enough to support GPU composition of wide color, and thus the
1055 // OEMs choose to disable this capability.
1056 if (isInternalDisplay && !hasWideColorDisplay) {
1057 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1058 isWideColorMode);
1059 } else {
1060 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1061 }
Michael Wright28f24d02016-07-12 13:30:53 -07001062
1063 return NO_ERROR;
1064}
1065
Daniel Solomon42d04562019-01-20 21:03:19 -08001066status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1067 ui::DisplayPrimaries &primaries) {
1068 if (!displayToken) {
1069 return BAD_VALUE;
1070 }
1071
1072 // Currently we only support this API for a single internal display.
1073 if (getInternalDisplayToken() != displayToken) {
1074 return BAD_VALUE;
1075 }
1076
1077 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1078 return NO_ERROR;
1079}
1080
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001081ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1082 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001083 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001084 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001085 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001086}
1087
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001088status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001089 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001090 Vector<ColorMode> modes;
1091 getDisplayColorModes(displayToken, &modes);
1092 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1093 if (mode < ColorMode::NATIVE || !exists) {
1094 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1095 decodeColorMode(mode).c_str(), mode, displayToken.get());
1096 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001097 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001098 const auto display = getDisplayDevice(displayToken);
1099 if (!display) {
1100 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1101 decodeColorMode(mode).c_str(), mode, displayToken.get());
1102 } else if (display->isVirtual()) {
1103 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1104 decodeColorMode(mode).c_str(), mode);
1105 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001106 display->getCompositionDisplay()->setColorProfile(
1107 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1108 RenderIntent::COLORIMETRIC,
1109 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001110 }
1111 }));
1112
Michael Wright28f24d02016-07-12 13:30:53 -07001113 return NO_ERROR;
1114}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001115
Galia Peycheva5492cb52019-10-30 14:13:16 +01001116status_t SurfaceFlinger::getAutoLowLatencyModeSupport(const sp<IBinder>& displayToken,
1117 bool* outSupport) const {
1118 Mutex::Autolock _l(mStateLock);
1119
1120 if (!displayToken) {
1121 ALOGE("getAutoLowLatencyModeSupport() failed. Missing display token.");
1122 return BAD_VALUE;
1123 }
1124 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1125 if (!displayId) {
1126 ALOGE("getAutoLowLatencyModeSupport() failed. Display id for display token %p not found.",
1127 displayToken.get());
1128 return NAME_NOT_FOUND;
1129 }
1130 *outSupport = getHwComposer().hasDisplayCapability(displayId,
1131 HWC2::DisplayCapability::AutoLowLatencyMode);
1132 return NO_ERROR;
1133}
1134
1135void SurfaceFlinger::setAutoLowLatencyMode(const sp<IBinder>& displayToken, bool on) {
1136 postMessageAsync(new LambdaMessage([=] { setAutoLowLatencyModeInternal(displayToken, on); }));
1137}
1138
1139void SurfaceFlinger::setAutoLowLatencyModeInternal(const sp<IBinder>& displayToken, bool on) {
1140 if (!displayToken) {
1141 ALOGE("setAutoLowLatencyMode() failed. Missing display token.");
1142 return;
1143 }
1144 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1145 if (!displayId) {
1146 ALOGE("setAutoLowLatencyMode() failed. Display id for display token %p not found.",
1147 displayToken.get());
1148 return;
1149 }
1150
1151 getHwComposer().setAutoLowLatencyMode(*displayId, on);
1152}
1153
1154status_t SurfaceFlinger::getGameContentTypeSupport(const sp<IBinder>& displayToken,
1155 bool* outSupport) const {
1156 Mutex::Autolock _l(mStateLock);
1157
1158 if (!displayToken) {
1159 ALOGE("getGameContentTypeSupport() failed. Missing display token.");
1160 return BAD_VALUE;
1161 }
1162 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1163 if (!displayId) {
1164 ALOGE("getGameContentTypeSupport() failed. Display id for display token %p not found.",
1165 displayToken.get());
1166 return NAME_NOT_FOUND;
1167 }
1168
1169 std::vector<HWC2::ContentType> outSupportedContentTypes;
1170 getHwComposer().getSupportedContentTypes(*displayId, &outSupportedContentTypes);
1171 *outSupport = std::find(outSupportedContentTypes.begin(), outSupportedContentTypes.end(),
1172 HWC2::ContentType::Game) != outSupportedContentTypes.end();
1173 return NO_ERROR;
1174}
1175
1176void SurfaceFlinger::setGameContentType(const sp<IBinder>& displayToken, bool on) {
1177 postMessageAsync(new LambdaMessage([=] { setGameContentTypeInternal(displayToken, on); }));
1178}
1179
1180void SurfaceFlinger::setGameContentTypeInternal(const sp<IBinder>& displayToken, bool on) {
1181 if (!displayToken) {
1182 ALOGE("setGameContentType() failed. Missing display token.");
1183 return;
1184 }
1185 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1186 if (!displayId) {
1187 ALOGE("setGameContentType() failed. Display id for display token %p not found.",
1188 displayToken.get());
1189 return;
1190 }
1191
1192 const HWC2::ContentType type = on ? HWC2::ContentType::Game : HWC2::ContentType::None;
1193 getHwComposer().setContentType(*displayId, type);
1194}
1195
Svetoslavd85084b2014-03-20 10:28:31 -07001196status_t SurfaceFlinger::clearAnimationFrameStats() {
1197 Mutex::Autolock _l(mStateLock);
1198 mAnimFrameTracker.clearStats();
1199 return NO_ERROR;
1200}
1201
1202status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1203 Mutex::Autolock _l(mStateLock);
1204 mAnimFrameTracker.getStats(outStats);
1205 return NO_ERROR;
1206}
1207
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001208status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1209 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001210 Mutex::Autolock _l(mStateLock);
1211
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001212 const auto display = getDisplayDeviceLocked(displayToken);
1213 if (!display) {
1214 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001215 return BAD_VALUE;
1216 }
1217
Peiyong Linfb069302018-04-25 14:34:31 -07001218 // At this point the DisplayDeivce should already be set up,
1219 // meaning the luminance information is already queried from
1220 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001221 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001222 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1223 capabilities.getDesiredMaxLuminance(),
1224 capabilities.getDesiredMaxAverageLuminance(),
1225 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001226
1227 return NO_ERROR;
1228}
1229
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001230status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1231 ui::PixelFormat* outFormat,
1232 ui::Dataspace* outDataspace,
1233 uint8_t* outComponentMask) const {
1234 if (!outFormat || !outDataspace || !outComponentMask) {
1235 return BAD_VALUE;
1236 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001237 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001238 if (!display || !display->getId()) {
1239 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1240 return BAD_VALUE;
1241 }
1242 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1243 outDataspace, outComponentMask);
1244}
1245
Kevin DuBois74e53772018-11-19 10:52:38 -08001246status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1247 bool enable, uint8_t componentMask,
1248 uint64_t maxFrames) const {
1249 const auto display = getDisplayDevice(displayToken);
1250 if (!display || !display->getId()) {
1251 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1252 return BAD_VALUE;
1253 }
1254
1255 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1256 componentMask, maxFrames);
1257}
1258
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001259status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1260 uint64_t maxFrames, uint64_t timestamp,
1261 DisplayedFrameStats* outStats) const {
1262 const auto display = getDisplayDevice(displayToken);
1263 if (!display || !display->getId()) {
1264 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1265 return BAD_VALUE;
1266 }
1267
1268 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1269 outStats);
1270}
1271
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001272status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1273 if (!outSupported) {
1274 return BAD_VALUE;
1275 }
1276 *outSupported = getRenderEngine().supportsProtectedContent();
1277 return NO_ERROR;
1278}
1279
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001280status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1281 bool* outIsWideColorDisplay) const {
1282 if (!displayToken || !outIsWideColorDisplay) {
1283 return BAD_VALUE;
1284 }
1285 Mutex::Autolock _l(mStateLock);
1286 const auto display = getDisplayDeviceLocked(displayToken);
1287 if (!display) {
1288 return BAD_VALUE;
1289 }
Peiyong Linff84a152019-05-17 18:36:19 -07001290
1291 // Use hasWideColorDisplay to override built-in display.
1292 const auto displayId = display->getId();
1293 if (displayId && displayId == getInternalDisplayIdLocked()) {
1294 *outIsWideColorDisplay = hasWideColorDisplay;
1295 return NO_ERROR;
1296 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001297 *outIsWideColorDisplay = display->hasWideColorGamut();
1298 return NO_ERROR;
1299}
1300
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001301status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001302 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001303 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001304
Dominik Laskowski6505f792019-09-18 11:10:05 -07001305 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1306 mEventQueue->setEventConnection(
1307 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001308 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001309 }));
1310
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001311 return NO_ERROR;
1312}
1313
1314status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001315 Mutex::Autolock lock(mStateLock);
1316 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001317}
1318
Lloyd Pique755e3192018-01-31 16:46:15 -08001319status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1320 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001321 // Try to acquire a lock for 1s, fail gracefully
1322 const status_t err = mStateLock.timedLock(s2ns(1));
1323 const bool locked = (err == NO_ERROR);
1324 if (!locked) {
1325 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1326 return TIMED_OUT;
1327 }
1328
1329 outLayers->clear();
1330 mCurrentState.traverseInZOrder([&](Layer* layer) {
1331 outLayers->push_back(layer->getLayerDebugInfo());
1332 });
1333
1334 mStateLock.unlock();
1335 return NO_ERROR;
1336}
1337
Peiyong Linc6780972018-10-28 15:24:08 -07001338status_t SurfaceFlinger::getCompositionPreference(
1339 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1340 Dataspace* outWideColorGamutDataspace,
1341 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001342 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001343 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001344 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001345 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001346 return NO_ERROR;
1347}
1348
Dan Stozaec460082018-12-17 15:35:09 -08001349status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1350 const sp<IBinder>& stopLayerHandle,
1351 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001352 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001353 return BAD_VALUE;
1354 }
1355 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001356 return NO_ERROR;
1357}
1358
Dan Stozaec460082018-12-17 15:35:09 -08001359status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001360 if (!listener) {
1361 return BAD_VALUE;
1362 }
Dan Stozaec460082018-12-17 15:35:09 -08001363 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001364 return NO_ERROR;
1365}
Dan Gittik57e63c52019-01-18 16:37:54 +00001366
1367status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1368 bool* outSupport) const {
1369 if (!displayToken || !outSupport) {
1370 return BAD_VALUE;
1371 }
1372 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1373 if (!displayId) {
1374 return NAME_NOT_FOUND;
1375 }
1376 *outSupport =
1377 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1378 return NO_ERROR;
1379}
1380
1381status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1382 float brightness) const {
1383 if (!displayToken) {
1384 return BAD_VALUE;
1385 }
1386 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1387 if (!displayId) {
1388 return NAME_NOT_FOUND;
1389 }
1390 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1391}
1392
Ady Abraham8532d012019-05-08 14:50:56 -07001393status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1394 PowerHint powerHint = static_cast<PowerHint>(hintId);
1395
1396 if (powerHint == PowerHint::INTERACTION) {
1397 mScheduler->notifyTouchEvent();
1398 }
1399
1400 return NO_ERROR;
1401}
1402
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001403// ----------------------------------------------------------------------------
1404
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001405sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001406 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001407 const auto& handle =
1408 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001409
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001410 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001411}
1412
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001413// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001414
1415void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001416 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001417}
1418
1419void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001420 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001421 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001422}
1423
1424void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001425 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001426 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001427}
1428
1429void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001430 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001431 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001432}
1433
1434status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001435 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001436 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001437}
1438
1439status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001440 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001441 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001442 if (res == NO_ERROR) {
1443 msg->wait();
1444 }
1445 return res;
1446}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001447
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001448void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001449 do {
1450 waitForEvent();
1451 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001452}
1453
Dominik Laskowski83b88212018-12-11 13:34:06 -08001454nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001455 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001456 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1457 return 0;
1458 }
1459
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001460 return getHwComposer().getDisplayVsyncPeriod(*displayId);
Dominik Laskowski83b88212018-12-11 13:34:06 -08001461}
1462
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001463void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Ady Abraham7159f572019-10-11 11:10:18 -07001464 int64_t timestamp,
1465 std::optional<hwc2_vsync_period_t> /*vsyncPeriod*/) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001466 ATRACE_NAME("SF onVsync");
1467
Ady Abraham7159f572019-10-11 11:10:18 -07001468 // TODO(b/140201379): use vsyncPeriod in the new DispSync
1469
Steven Thomas3cfac282017-02-06 12:29:30 -08001470 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001471 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001472 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001473 return;
1474 }
1475
Dominik Laskowski075d3172018-05-24 15:50:06 -07001476 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001477 return;
1478 }
1479
Dominik Laskowski075d3172018-05-24 15:50:06 -07001480 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001481 // For now, we don't do anything with external display vsyncs.
1482 return;
1483 }
1484
Alec Mourif8e689c2019-05-20 18:32:22 -07001485 bool periodFlushed = false;
1486 mScheduler->addResyncSample(timestamp, &periodFlushed);
1487 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001488 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001489 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001490}
1491
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001492void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001493 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1494 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001495}
1496
Ady Abraham2139f732019-11-13 18:56:40 -08001497bool SurfaceFlinger::isDisplayConfigAllowed(HwcConfigIndexType configId) const {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01001498 return mRefreshRateConfigs->isConfigAllowed(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001499}
1500
Ady Abraham2139f732019-11-13 18:56:40 -08001501void SurfaceFlinger::changeRefreshRateLocked(const RefreshRate& refreshRate,
1502 Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001503 const auto display = getDefaultDisplayDeviceLocked();
1504 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001505 return;
1506 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001507 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001508
Ana Krulec7d1d6832018-12-27 11:10:09 -08001509 // Don't do any updating if the current fps is the same as the new one.
Ady Abraham2139f732019-11-13 18:56:40 -08001510 if (!isDisplayConfigAllowed(refreshRate.configId)) {
1511 ALOGV("Skipping config %d as it is not part of allowed configs",
1512 refreshRate.configId.value());
Ady Abraham1902d072019-03-01 17:18:59 -08001513 return;
1514 }
1515
Ady Abraham2139f732019-11-13 18:56:40 -08001516 setDesiredActiveConfig({refreshRate.configId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001517}
1518
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001519void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001520 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001521 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001522 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001523
Lloyd Piqueba04e622017-12-14 17:11:26 -08001524 // Ignore events that do not have the right sequenceId.
1525 if (sequenceId != getBE().mComposerSequenceId) {
1526 return;
1527 }
1528
Steven Thomasb02664d2017-07-26 18:48:28 -07001529 // Only lock if we're not on the main thread. This function is normally
1530 // called on a hwbinder thread, but for the primary display it's called on
1531 // the main thread with the state lock already held, so don't attempt to
1532 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001533 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001534
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001535 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001536
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001537 if (std::this_thread::get_id() == mMainThreadId) {
1538 // Process all pending hot plug events immediately if we are on the main thread.
1539 processDisplayHotplugEventsLocked();
1540 }
1541
Lloyd Piqueba04e622017-12-14 17:11:26 -08001542 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001543}
1544
Ady Abraham7159f572019-10-11 11:10:18 -07001545void SurfaceFlinger::onVsyncPeriodTimingChangedReceived(
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001546 int32_t sequenceId, hwc2_display_t /*display*/,
1547 const hwc_vsync_period_change_timeline_t& updatedTimeline) {
1548 Mutex::Autolock lock(mStateLock);
1549 if (sequenceId != getBE().mComposerSequenceId) {
1550 return;
1551 }
1552 mScheduler->onNewVsyncPeriodChangeTimeline(updatedTimeline);
Ady Abraham7159f572019-10-11 11:10:18 -07001553}
1554
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001555void SurfaceFlinger::onSeamlessPossible(int32_t /*sequenceId*/, hwc2_display_t /*display*/) {
1556 // TODO(b/142753666): use constraints when calling to setActiveConfigWithConstrains and
1557 // use this callback to know when to retry in case of SEAMLESS_NOT_POSSIBLE.
1558}
1559
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001560void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001561 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001562 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001563 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001564 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001565 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001566}
1567
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001568void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001569 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001570
1571 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1572 // display power state.
1573 postMessageAsync(new LambdaMessage(
1574 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1575}
1576
1577void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1578 ATRACE_CALL();
1579
Ady Abraham27c70212019-06-11 10:52:26 -07001580 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1581
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001582 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001583 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1584 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001585 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001586 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001587 }
Mathias Agopian86303202012-07-24 22:46:10 -07001588}
1589
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001590// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001591void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001592 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001593 // Clear the drawing state so that the logic inside of
1594 // handleTransactionLocked will fire. It will determine the delta between
1595 // mCurrentState and mDrawingState and re-apply all changes when we make the
1596 // transition.
1597 mDrawingState.displays.clear();
1598 mDisplays.clear();
1599}
1600
Steven Thomas050b2c82017-03-06 11:45:16 -08001601void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001602 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001603 if (!mVrFlinger)
1604 return;
1605 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001606 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001607 return;
1608 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001609
Lloyd Pique441d5042018-10-18 16:49:51 -07001610 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001611 ALOGE("Vr flinger is only supported for remote hardware composer"
1612 " service connections. Ignoring request to transition to vr"
1613 " flinger.");
1614 mVrFlingerRequestsDisplay = false;
1615 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001616 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001617
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001618 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001619
Steven Thomas0123ac62018-07-12 11:32:34 -07001620 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001621 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001622
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001623 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001624
1625 // Clear out all the output layers from the composition engine for all
1626 // displays before destroying the hardware composer interface. This ensures
1627 // any HWC layers are destroyed through that interface before it becomes
1628 // invalid.
1629 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001630 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001631 }
1632
Steven Thomas0123ac62018-07-12 11:32:34 -07001633 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1634 // called below. Clear the reference now so we don't accidentally use it
1635 // later.
1636 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001637
Steven Thomasb02664d2017-07-26 18:48:28 -07001638 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001639 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001640 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001641
Steven Thomasb02664d2017-07-26 18:48:28 -07001642 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001643 // Delete the current instance before creating the new one
1644 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1645 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1646 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1647 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001648
Lloyd Pique441d5042018-10-18 16:49:51 -07001649 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001650 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001651
1652 if (vrFlingerRequestsDisplay) {
1653 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001654 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001655
1656 mVisibleRegionsDirty = true;
1657 invalidateHwcGeometry();
1658
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001659 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001660 display = getDefaultDisplayDeviceLocked();
1661 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001662 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001663
Steven Thomasb02664d2017-07-26 18:48:28 -07001664 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001665 const nsecs_t vsyncPeriod = getVsyncPeriod();
1666 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001667
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001668 // The present fences returned from vr_hwc are not an accurate
1669 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001670 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001671
Steven Thomasb02664d2017-07-26 18:48:28 -07001672 // Use phase of 0 since phase is not known.
1673 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001674 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001675 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001676
Ana Krulecc2870422019-01-29 19:00:58 -08001677 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001678
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001679 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001680 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001681}
1682
Ady Abraham11579302019-09-19 12:35:58 -07001683bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1684 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001685 // We are storing the last 2 present fences. If sf's phase offset is to be
1686 // woken up before the actual vsync but targeting the next vsync, we need to check
1687 // fence N-2
Ady Abraham9e16a482019-12-03 17:19:41 -08001688 const sp<Fence>& fence = mVSyncModulator->getOffsets().sf > 0 ? mPreviousPresentFences[0]
1689 : mPreviousPresentFences[1];
Ady Abrahambe0f9482019-04-24 15:41:53 -07001690
Ady Abraham11579302019-09-19 12:35:58 -07001691 if (fence == Fence::NO_FENCE) {
1692 return false;
1693 }
1694
1695 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1696 fence->wait(graceTimeMs);
1697 }
1698
1699 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001700}
1701
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001702void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001703 DisplayStatInfo stats;
1704 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001705 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001706 // Inflate the expected present time if we're targetting the next vsync.
Ady Abraham9e16a482019-12-03 17:19:41 -08001707 mExpectedPresentTime.store(
1708 mVSyncModulator->getOffsets().sf > 0 ? presentTime : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001709}
1710
Dominik Laskowski22488f62019-03-28 09:53:04 -07001711void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001712 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001713 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001714 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001715 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001716 // calculate the expected present time once and use the cached
1717 // value throughout this frame to make sure all layers are
1718 // seeing this same value.
1719 populateExpectedPresentTime();
1720
Ady Abraham11579302019-09-19 12:35:58 -07001721 // When Backpressure propagation is enabled we want to give a small grace period
1722 // for the present fence to fire instead of just giving up on this frame to handle cases
1723 // where present fence is just about to get signaled.
1724 const int graceTimeForPresentFenceMs =
1725 (mPropagateBackpressure &&
1726 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1727 ? 1
1728 : 0;
1729 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1730 previousFrameMissed(
1731 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001732 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1733 mHadDeviceComposition && frameMissed};
1734 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1735 mHadClientComposition && frameMissed};
1736
Alec Mouricc0fc602019-02-26 21:45:19 -08001737 if (frameMissed) {
1738 mFrameMissedCount++;
1739 mTimeStats->incrementMissedFrames();
1740 }
1741
Alec Mouri40189b02019-03-05 15:07:54 -08001742 if (hwcFrameMissed) {
1743 mHwcFrameMissedCount++;
1744 }
1745
1746 if (gpuFrameMissed) {
1747 mGpuFrameMissedCount++;
1748 }
1749
Ady Abrahamadb9a992019-09-19 21:21:55 +00001750 if (frameMissed && mPropagateBackpressure) {
1751 if ((hwcFrameMissed && !gpuFrameMissed) ||
1752 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001753 signalLayerUpdate();
1754 break;
1755 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001756 }
Dan Stoza50182882016-07-08 12:02:20 -07001757
Steven Thomas050b2c82017-03-06 11:45:16 -08001758 // Now that we're going to make it to the handleMessageTransaction()
1759 // call below it's safe to call updateVrFlinger(), which will
1760 // potentially trigger a display handoff.
1761 updateVrFlinger();
1762
Dan Stoza6b9454d2014-11-07 16:00:59 -08001763 bool refreshNeeded = handleMessageTransaction();
1764 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001765
Ana Krulecc84d09b2019-11-02 23:10:29 +01001766 // Layers need to get updated (in the previous line) before we can use them for
1767 // choosing the refresh rate.
1768 mScheduler->chooseRefreshRateForContent();
1769 if (performSetActiveConfig()) {
1770 break;
1771 }
1772
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001773 updateCursorAsync();
1774 updateInputFlinger();
1775
Dan Stoza58784442014-12-02 16:58:17 -08001776 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001777 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001778 // Signal a refresh if a transaction modified the window state,
1779 // a new buffer was latched, or if HWC has requested a full
1780 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001781 if (mFrameStartTime <= 0) {
1782 // We should only use the time of the first invalidate
1783 // message that signals a refresh as the beginning of the
1784 // frame. Otherwise the real frame time will be
1785 // underestimated.
1786 mFrameStartTime = frameStart;
1787 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001788 signalRefresh();
1789 }
1790 break;
1791 }
1792 case MessageQueue::REFRESH: {
1793 handleMessageRefresh();
1794 break;
1795 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001796 }
1797}
1798
Dan Stoza6b9454d2014-11-07 16:00:59 -08001799bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001800 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001801 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001802
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001803 bool flushedATransaction = flushTransactionQueues();
1804
1805 bool runHandleTransaction = transactionFlags &&
1806 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1807
1808 if (runHandleTransaction) {
1809 handleTransaction(eTransactionMask);
1810 } else {
1811 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001812 }
1813
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001814 if (transactionFlushNeeded()) {
1815 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001816 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001817
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001818 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001819}
1820
Mathias Agopian4fec8732012-06-29 14:12:52 -07001821void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001822 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001823
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001824 mRefreshPending = false;
1825
Lloyd Piqueab039b52019-02-13 14:22:42 -08001826 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001827 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001828 for (const auto& [_, display] : mDisplays) {
1829 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1830 }
1831 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1832 auto compositionLayer = layer->getCompositionLayer();
1833 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1834 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001835 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1836 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1837 auto compositionLayer = layer->getCompositionLayer();
Adithya Srinivasan87c1b80e2019-11-21 11:43:06 -08001838 if (compositionLayer) refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001839 }
1840
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001841 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001842 refreshArgs.outputColorSetting = useColorManagement
1843 ? mDisplayColorSetting
1844 : compositionengine::OutputColorSetting::kUnmanaged;
1845 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1846 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001847
1848 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1849 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001850
1851 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1852 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1853 mDrawingState.colorMatrixChanged = false;
1854 }
1855
1856 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1857
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001858 if (mDebugRegion != 0) {
1859 refreshArgs.devOptFlashDirtyRegionsDelay =
1860 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1861 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001862
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001863 mGeometryInvalid = false;
1864
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001865 // Store the present time just before calling to the composition engine so we could notify
1866 // the scheduler.
1867 const auto presentTime = systemTime();
1868
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001869 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001870 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1871 // Reset the frame start time now that we've recorded this frame.
1872 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001873
Ady Abraham3a77a7b2019-12-02 18:46:59 -08001874 mScheduler->onDisplayRefreshed(presentTime);
1875
David Sodmanfa9b2af2017-12-24 13:28:59 -08001876 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001877 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001878
Lloyd Pique66d68602019-02-13 14:23:31 -08001879 mHadClientComposition =
1880 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1881 auto& displayDevice = tokenDisplayPair.second;
1882 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1883 });
1884 mHadDeviceComposition =
1885 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1886 auto& displayDevice = tokenDisplayPair.second;
1887 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1888 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001889
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001890 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001891
David Sodman7e4ae112018-02-09 15:02:28 -08001892 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001893 if (mVisibleRegionsDirty) {
1894 mVisibleRegionsDirty = false;
1895 if (mTracingEnabled) {
1896 mTracing.notify("visibleRegionsDirty");
1897 }
1898 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001899
1900 if (mCompositionEngine->needsAnotherUpdate()) {
1901 signalLayerUpdate();
1902 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001903}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001904
David Sodmanfa9b2af2017-12-24 13:28:59 -08001905
1906bool SurfaceFlinger::handleMessageInvalidate() {
1907 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001908 bool refreshNeeded = handlePageFlip();
1909
Vishnu Nair4351ad52019-02-11 14:13:02 -08001910 if (mVisibleRegionsDirty) {
1911 computeLayerBounds();
1912 }
1913
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001914 for (auto& layer : mLayersPendingRefresh) {
1915 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001916 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001917 invalidateLayerStack(layer, visibleReg);
1918 }
1919 mLayersPendingRefresh.clear();
1920 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001921}
1922
Ana Krulece588e312018-09-18 12:32:24 -07001923void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1924 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001925 // Update queue of past composite+present times and determine the
1926 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001927 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001928 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001929 while (!getBE().mCompositePresentTimes.empty()) {
1930 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001931 // Cached values should have been updated before calling this method,
1932 // which helps avoid duplicate syscalls.
1933 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1934 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1935 break;
1936 }
1937 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001938 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001939 }
1940
1941 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001942 while (getBE().mCompositePresentTimes.size() > 16) {
1943 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001944 }
1945
Ana Krulece588e312018-09-18 12:32:24 -07001946 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001947}
1948
Ana Krulece588e312018-09-18 12:32:24 -07001949void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1950 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001951 // Integer division and modulo round toward 0 not -inf, so we need to
1952 // treat negative and positive offsets differently.
Ady Abraham9e16a482019-12-03 17:19:41 -08001953 nsecs_t idealLatency = (mPhaseConfiguration->getCurrentOffsets().late.sf > 0)
1954 ? (stats.vsyncPeriod -
1955 (mPhaseConfiguration->getCurrentOffsets().late.sf % stats.vsyncPeriod))
1956 : ((-mPhaseConfiguration->getCurrentOffsets().late.sf) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001957
Ady Abraham9e16a482019-12-03 17:19:41 -08001958 // Just in case mPhaseConfiguration->getCurrentOffsets().late.sf == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001959 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001960 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001961 }
1962
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001963 // Snap the latency to a value that removes scheduling jitter from the
1964 // composition and present times, which often have >1ms of jitter.
1965 // Reducing jitter is important if an app attempts to extrapolate
1966 // something (such as user input) to an accurate diasplay time.
Ady Abraham9e16a482019-12-03 17:19:41 -08001967 // Snapping also allows an app to precisely calculate
1968 // mPhaseConfiguration->getCurrentOffsets().late.sf with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001969 nsecs_t bias = stats.vsyncPeriod / 2;
1970 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1971 nsecs_t snappedCompositeToPresentLatency =
1972 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001973
David Sodman99974d22017-11-28 12:04:33 -08001974 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001975 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1976 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001977 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001978}
1979
David Sodman2b406362017-12-15 13:33:47 -08001980void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001981{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001982 ATRACE_CALL();
1983 ALOGV("postComposition");
1984
Brian Anderson3546a3f2016-07-14 11:51:14 -07001985 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001986 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001987 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001988 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001989 }
1990
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001991 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001992 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001993
David Sodman73beded2017-11-15 11:56:06 -08001994 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001995 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08001996 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001997 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001998 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1999 ->getRenderSurface()
2000 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08002001 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002002 } else {
2003 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
2004 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07002005
David Sodman73beded2017-11-15 11:56:06 -08002006 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07002007 mPreviousPresentFences[1] = mPreviousPresentFences[0];
2008 mPreviousPresentFences[0] = displayDevice
2009 ? getHwComposer().getPresentFence(*displayDevice->getId())
2010 : Fence::NO_FENCE;
2011 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08002012 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07002013
Ana Krulece588e312018-09-18 12:32:24 -07002014 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08002015 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002016
Lloyd Piqueab039b52019-02-13 14:22:42 -08002017 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
2018 // be sampled a little later than when we started doing work for this frame,
2019 // but that should be okay since updateCompositorTiming has snapping logic.
2020 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
2021 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08002022 CompositorTiming compositorTiming;
2023 {
David Sodman99974d22017-11-28 12:04:33 -08002024 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
2025 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08002026 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08002027
Robert Carr2047fae2016-11-28 14:09:09 -08002028 mDrawingState.traverseInZOrder([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08002029 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
2030 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07002031 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002032 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07002033 }
Robert Carr2047fae2016-11-28 14:09:09 -08002034 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002035
Brian Andersonfbc80ae2017-05-26 16:23:54 -07002036 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002037 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002038 }
2039
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08002040 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002041 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2042 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08002043 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07002044 }
2045 }
2046
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002047 if (mAnimCompositionPending) {
2048 mAnimCompositionPending = false;
2049
Brian Anderson4e606e32017-03-16 15:34:57 -07002050 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07002051 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07002052 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07002053 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002054 // The HWC doesn't support present fences, so use the refresh
2055 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07002056 const nsecs_t presentTime =
2057 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08002058 mAnimFrameTracker.setActualPresentTime(presentTime);
2059 }
2060 mAnimFrameTracker.advanceFrame();
2061 }
Dan Stozab90cf072015-03-05 11:05:59 -08002062
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002063 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002064 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002065 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07002066 }
2067
Yiwei Zhang7e666a52018-11-15 13:33:42 -08002068 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07002069
Lloyd Pique32cbe282018-10-19 13:09:22 -07002070 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
2071 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08002072 return;
2073 }
2074
2075 nsecs_t currentTime = systemTime();
2076 if (mHasPoweredOff) {
2077 mHasPoweredOff = false;
2078 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002079 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07002080 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08002081 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
2082 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002083 } else {
David Sodman4a36e932017-11-07 14:29:47 -08002084 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002085 }
David Sodman4a36e932017-11-07 14:29:47 -08002086 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08002087 }
David Sodman4a36e932017-11-07 14:29:47 -08002088 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07002089
2090 {
2091 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07002092 if (mTexturePool.size() < mTexturePoolSize) {
2093 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07002094 const size_t offset = mTexturePool.size();
2095 mTexturePool.resize(mTexturePoolSize);
2096 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
2097 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07002098 } else if (mTexturePool.size() > mTexturePoolSize) {
2099 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
2100 const size_t offset = mTexturePoolSize;
2101 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
2102 mTexturePool.resize(mTexturePoolSize);
2103 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07002104 }
2105 }
Marissa Walle2ffb422018-10-12 11:33:52 -07002106
Ady Abrahambe0f9482019-04-24 15:41:53 -07002107 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07002108 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08002109
Kevin DuBois413287f2019-02-25 08:46:47 -08002110 if (mLumaSampling && mRegionSamplingThread) {
2111 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08002112 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002113
2114 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2115 // side-effect of getTotalSize(), so we check that again here
2116 if (ATRACE_ENABLED()) {
Marissa Wall22b2de12019-12-02 18:11:43 -08002117 // getTotalSize returns the total number of buffers that were allocated by SurfaceFlinger
Dan Stoza45de5ba2019-04-25 14:12:09 -07002118 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2119 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002120}
2121
Vishnu Nair4351ad52019-02-11 14:13:02 -08002122void SurfaceFlinger::computeLayerBounds() {
2123 for (const auto& pair : mDisplays) {
2124 const auto& displayDevice = pair.second;
2125 const auto display = displayDevice->getCompositionDisplay();
2126 for (const auto& layer : mDrawingState.layersSortedByZ) {
2127 // only consider the layers on the given layer stack
2128 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002129 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002130 }
2131
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002132 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2133 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002134 }
2135 }
2136}
2137
David Sodmanfa9b2af2017-12-24 13:28:59 -08002138void SurfaceFlinger::postFrame()
2139{
2140 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002141 const auto display = getDefaultDisplayDeviceLocked();
2142 if (display && getHwComposer().isConnected(*display->getId())) {
2143 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002144 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2145 logFrameStats();
2146 }
2147 }
2148}
2149
Mathias Agopian87baae12012-07-31 12:38:26 -07002150void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002151{
Mathias Agopian841cde52012-03-01 15:44:37 -08002152 ATRACE_CALL();
2153
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002154 // here we keep a copy of the drawing state (that is the state that's
2155 // going to be overwritten by handleTransactionLocked()) outside of
2156 // mStateLock so that the side-effects of the State assignment
2157 // don't happen with mStateLock held (which can cause deadlocks).
2158 State drawingState(mDrawingState);
2159
Mathias Agopianca4d3602011-05-19 15:38:14 -07002160 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002161 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002162
Mathias Agopianca4d3602011-05-19 15:38:14 -07002163 // Here we're guaranteed that some transaction flags are set
2164 // so we can call handleTransactionLocked() unconditionally.
2165 // We call getTransactionFlags(), which will also clear the flags,
2166 // with mStateLock held to guarantee that mCurrentState won't change
2167 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002168
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002169 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002170 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002171 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002172
Mathias Agopianca4d3602011-05-19 15:38:14 -07002173 mDebugInTransaction = 0;
2174 invalidateHwcGeometry();
2175 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002176}
2177
Lloyd Piqueba04e622017-12-14 17:11:26 -08002178void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2179 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002180 const std::optional<DisplayIdentificationInfo> info =
2181 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002182
Dominik Laskowski075d3172018-05-24 15:50:06 -07002183 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002184 continue;
2185 }
2186
Lloyd Piqueba04e622017-12-14 17:11:26 -08002187 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002188 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002189 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002190 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2191 initScheduler(info->id);
2192 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002193 mPhysicalDisplayTokens[info->id] = new BBinder();
2194 DisplayDeviceState state;
2195 state.displayId = info->id;
2196 state.isSecure = true; // All physical displays are currently considered secure.
2197 state.displayName = info->name;
2198 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2199 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002200 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002201 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002202 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002203
Dominik Laskowski075d3172018-05-24 15:50:06 -07002204 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2205 if (index >= 0) {
2206 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2207 mInterceptor->saveDisplayDeletion(state.sequenceId);
2208 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002209 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002210 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002211 }
2212
2213 processDisplayChangesLocked();
2214 }
2215
2216 mPendingHotplugEvents.clear();
2217}
2218
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002219void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002220 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2221 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002222}
2223
Lloyd Pique99d3da52018-01-22 17:48:03 -08002224sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002225 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002226 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002227 const sp<IGraphicBufferProducer>& producer) {
2228 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002229 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002230 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002231 creationArgs.isSecure = state.isSecure;
2232 creationArgs.displaySurface = dispSurface;
2233 creationArgs.hasWideColorGamut = false;
2234 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002235 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002236
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002237 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002238 creationArgs.isPrimary = isInternalDisplay;
2239
2240 if (useColorManagement && displayId) {
2241 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002242 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002243 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002244 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002245 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002246
Dominik Laskowski7e045462018-05-30 13:02:02 -07002247 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002248 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002249 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002250 }
tangrobin6753a022018-08-10 10:58:54 +08002251 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002252
Dominik Laskowski075d3172018-05-24 15:50:06 -07002253 if (displayId) {
2254 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002255 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002256 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002257 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002258
Lloyd Pique90c115d2018-09-18 21:39:42 -07002259 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002260 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002261 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002262
Lloyd Pique99d3da52018-01-22 17:48:03 -08002263 // Make sure that composition can never be stalled by a virtual display
2264 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002265 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002266 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002267 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2268 }
2269
Dominik Laskowski718f9602019-11-09 20:01:35 -08002270 creationArgs.physicalOrientation =
2271 isInternalDisplay ? internalDisplayOrientation : ui::ROTATION_0;
Chia-I Wua02871c2018-08-27 14:38:23 -07002272
Lloyd Pique99d3da52018-01-22 17:48:03 -08002273 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002274 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002275
Lloyd Pique90c115d2018-09-18 21:39:42 -07002276 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002277
2278 if (maxFrameBufferAcquiredBuffers >= 3) {
2279 nativeWindowSurface->preallocateBuffers();
2280 }
2281
2282 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002283 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002284 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002285 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002286 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002287 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002288 display->getCompositionDisplay()->setColorProfile(
2289 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2290 RenderIntent::COLORIMETRIC,
2291 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002292 if (!state.isVirtual()) {
2293 LOG_ALWAYS_FATAL_IF(!displayId);
Ady Abraham2139f732019-11-13 18:56:40 -08002294 auto activeConfigId = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(*displayId));
2295 display->setActiveConfig(activeConfigId);
Lloyd Pique3c085a02018-05-09 19:38:32 -07002296 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002297
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002298 display->setLayerStack(state.layerStack);
2299 display->setProjection(state.orientation, state.viewport, state.frame);
2300 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002301
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002302 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002303}
2304
Lloyd Pique347200f2017-12-14 17:00:15 -08002305void SurfaceFlinger::processDisplayChangesLocked() {
2306 // here we take advantage of Vector's copy-on-write semantics to
2307 // improve performance by skipping the transaction entirely when
2308 // know that the lists are identical
2309 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2310 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2311 if (!curr.isIdenticalTo(draw)) {
2312 mVisibleRegionsDirty = true;
2313 const size_t cc = curr.size();
2314 size_t dc = draw.size();
2315
2316 // find the displays that were removed
2317 // (ie: in drawing state but not in current state)
2318 // also handle displays that changed
2319 // (ie: displays that are in both lists)
2320 for (size_t i = 0; i < dc;) {
2321 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2322 if (j < 0) {
2323 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002324 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002325 // Save display ID before disconnecting.
2326 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002327 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002328
2329 if (!display->isVirtual()) {
2330 LOG_ALWAYS_FATAL_IF(!displayId);
2331 dispatchDisplayHotplugEvent(displayId->value, false);
2332 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002333 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002334
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002335 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002336 } else {
2337 // this display is in both lists. see if something changed.
2338 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002339 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002340 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2341 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2342 if (state_binder != draw_binder) {
2343 // changing the surface is like destroying and
2344 // recreating the DisplayDevice, so we just remove it
2345 // from the drawing state, so that it get re-added
2346 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002347 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002348 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002349 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002350 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002351 mDrawingState.displays.removeItemsAt(i);
2352 dc--;
2353 // at this point we must loop to the next item
2354 continue;
2355 }
2356
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002357 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002358 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002359 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002360 }
2361 if ((state.orientation != draw[i].orientation) ||
2362 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002363 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002364 }
2365 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002366 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002367 }
2368 }
2369 }
2370 ++i;
2371 }
2372
2373 // find displays that were added
2374 // (ie: in current state but not in drawing state)
2375 for (size_t i = 0; i < cc; i++) {
2376 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2377 const DisplayDeviceState& state(curr[i]);
2378
Lloyd Pique542307f2018-10-19 13:24:08 -07002379 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002380 sp<IGraphicBufferProducer> producer;
2381 sp<IGraphicBufferProducer> bqProducer;
2382 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002383 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002384
Dominik Laskowski075d3172018-05-24 15:50:06 -07002385 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002386 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002387 // Virtual displays without a surface are dormant:
2388 // they have external state (layer stack, projection,
2389 // etc.) but no internal state (i.e. a DisplayDevice).
2390 if (state.surface != nullptr) {
2391 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002392 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002393 int width = 0;
2394 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2395 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2396 int height = 0;
2397 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2398 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2399 int intFormat = 0;
2400 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2401 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002402 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002403
Dominik Laskowski075d3172018-05-24 15:50:06 -07002404 displayId =
2405 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002406 }
2407
2408 // TODO: Plumb requested format back up to consumer
2409
2410 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002411 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002412 bqProducer, bqConsumer,
2413 state.displayName);
2414
2415 dispSurface = vds;
2416 producer = vds;
2417 }
2418 } else {
2419 ALOGE_IF(state.surface != nullptr,
2420 "adding a supported display, but rendering "
2421 "surface is provided (%p), ignoring it",
2422 state.surface.get());
2423
Dominik Laskowski075d3172018-05-24 15:50:06 -07002424 displayId = state.displayId;
2425 LOG_ALWAYS_FATAL_IF(!displayId);
2426 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002427 producer = bqProducer;
2428 }
2429
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002430 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002431 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002432 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002433 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002434 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002435 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002436 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002437 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002438 }
2439 }
2440 }
2441 }
2442 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002443
2444 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002445}
2446
Mathias Agopian87baae12012-07-31 12:38:26 -07002447void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002448{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002449 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2450
Dan Stoza7dde5992015-05-22 09:51:44 -07002451 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002452 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2453 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002454 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002455
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002456 /*
2457 * Traversal of the children
2458 * (perform the transaction for each of them if needed)
2459 */
2460
Marissa Wall06255332019-03-27 13:48:27 -07002461 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002462 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002464 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002465
2466 const uint32_t flags = layer->doTransaction(0);
2467 if (flags & Layer::eVisibleRegion)
2468 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002469
2470 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002471 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002472 }
Robert Carr2047fae2016-11-28 14:09:09 -08002473 });
Marissa Wall06255332019-03-27 13:48:27 -07002474 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002475 }
2476
2477 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002478 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002479 */
2480
Mathias Agopiane57f2922012-08-09 16:29:12 -07002481 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002482 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002483 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002484 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002485
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002486 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002487 // The transform hint might have changed for some layers
2488 // (either because a display has changed, or because a layer
2489 // as changed).
2490 //
2491 // Walk through all the layers in currentLayers,
2492 // and update their transform hint.
2493 //
2494 // If a layer is visible only on a single display, then that
2495 // display is used to calculate the hint, otherwise we use the
2496 // default display.
2497 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002498 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002499 // the hint is set before we acquire a buffer from the surface texture.
2500 //
2501 // NOTE: layer transactions have taken place already, so we use their
2502 // drawing state. However, SurfaceFlinger's own transaction has not
2503 // happened yet, so we must use the current state layer list
2504 // (soon to become the drawing state list).
2505 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002506 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002507 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002508 bool first = true;
2509 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002510 // NOTE: we rely on the fact that layers are sorted by
2511 // layerStack first (so we don't have to traverse the list
2512 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002513 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002514 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002515 currentlayerStack = layerStack;
2516 // figure out if this layerstack is mirrored
2517 // (more than one display) if so, pick the default display,
2518 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002519 hintDisplay = nullptr;
2520 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002521 if (display->getCompositionDisplay()
2522 ->belongsInOutput(layer->getLayerStack(),
2523 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002524 if (hintDisplay) {
2525 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002526 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002527 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002528 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002529 }
2530 }
2531 }
2532 }
Chet Haase91d25932013-04-11 15:24:55 -07002533
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002534 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002535 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2536 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002537
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002538 // could be null when this layer is using a layerStack
2539 // that is not visible on any display. Also can occur at
2540 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002541 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002542 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002543
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002544 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002545 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002546 if (hintDisplay) {
2547 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002548 }
Robert Carr2047fae2016-11-28 14:09:09 -08002549
2550 first = false;
2551 });
Mathias Agopian84300952012-11-21 16:02:13 -08002552 }
2553
2554
Mathias Agopian3559b072012-08-15 13:46:03 -07002555 /*
2556 * Perform our own transaction if needed
2557 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002558
2559 if (mLayersAdded) {
2560 mLayersAdded = false;
2561 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002562 mVisibleRegionsDirty = true;
2563 }
2564
2565 // some layers might have been removed, so
2566 // we need to update the regions they're exposing.
2567 if (mLayersRemoved) {
2568 mLayersRemoved = false;
2569 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002570 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002571 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002572 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002573 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002574 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002575 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002576 }
Robert Carr2047fae2016-11-28 14:09:09 -08002577 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002578 }
2579
Vishnu Nairec0ab382019-02-13 15:32:56 -08002580 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002581 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002582}
2583
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002584void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002585 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002586 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002587 return;
2588 }
2589
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002590 if (mVisibleRegionsDirty || mInputInfoChanged) {
2591 mInputInfoChanged = false;
2592 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002593 } else if (mInputWindowCommands.syncInputWindows) {
2594 // If the caller requested to sync input windows, but there are no
2595 // changes to input windows, notify immediately.
2596 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002597 }
2598
Arthur Hung6cbb9752019-09-05 16:38:18 +08002599 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002600}
2601
2602void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002603 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002604
2605 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2606 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002607 // When calculating the screen bounds we ignore the transparent region since it may
2608 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002609 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002610 }
2611 });
chaviw291d88a2019-02-14 10:33:58 -08002612
2613 mInputFlinger->setInputWindows(inputHandles,
2614 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2615 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002616}
2617
Vishnu Nairec0ab382019-02-13 15:32:56 -08002618void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002619 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002620 mPendingInputWindowCommands.clear();
2621}
2622
Riley Andrews03414a12014-07-01 14:22:59 -07002623void SurfaceFlinger::updateCursorAsync()
2624{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002625 compositionengine::CompositionRefreshArgs refreshArgs;
2626 for (const auto& [_, display] : mDisplays) {
2627 if (display->getId()) {
2628 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002629 }
2630 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002631
2632 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002633}
2634
Ady Abraham2139f732019-11-13 18:56:40 -08002635void SurfaceFlinger::changeRefreshRate(const RefreshRate& refreshRate,
2636 Scheduler::ConfigEvent event) {
2637 Mutex::Autolock lock(mStateLock);
2638 changeRefreshRateLocked(refreshRate, event);
2639}
2640
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002641void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2642 if (mScheduler) {
2643 // In practice it's not allowed to hotplug in/out the primary display once it's been
2644 // connected during startup, but some tests do it, so just warn and return.
2645 ALOGW("Can't re-init scheduler");
2646 return;
2647 }
2648
Ady Abraham2139f732019-11-13 18:56:40 -08002649 auto currentConfig = HwcConfigIndexType(getHwComposer().getActiveConfigIndex(primaryDisplayId));
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002650 mRefreshRateConfigs =
2651 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2652 getHwComposer().getConfigs(
2653 primaryDisplayId),
2654 currentConfig);
2655 mRefreshRateStats =
2656 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2657 currentConfig, HWC_POWER_MODE_OFF);
2658 mRefreshRateStats->setConfigMode(currentConfig);
2659
Ady Abraham9e16a482019-12-03 17:19:41 -08002660 mPhaseConfiguration = getFactory().createPhaseConfiguration(*mRefreshRateConfigs);
2661
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002662 // start the EventThread
2663 mScheduler =
2664 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
Ady Abraham3a77a7b2019-12-02 18:46:59 -08002665 *mRefreshRateConfigs, *this);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002666 mAppConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002667 mScheduler->createConnection("app", mPhaseConfiguration->getCurrentOffsets().late.app,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002668 impl::EventThread::InterceptVSyncsCallback());
2669 mSfConnectionHandle =
Ady Abraham9e16a482019-12-03 17:19:41 -08002670 mScheduler->createConnection("sf", mPhaseConfiguration->getCurrentOffsets().late.sf,
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002671 [this](nsecs_t timestamp) {
2672 mInterceptor->saveVSyncEvent(timestamp);
2673 });
2674
2675 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2676 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
Ady Abraham9e16a482019-12-03 17:19:41 -08002677 mPhaseConfiguration->getCurrentOffsets());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002678
2679 mRegionSamplingThread =
2680 new RegionSamplingThread(*this, *mScheduler,
2681 RegionSamplingThread::EnvironmentTimingTunables());
Alec Mouri60aee1c2019-10-28 16:18:59 -07002682 // Dispatch a config change request for the primary display on scheduler
2683 // initialization, so that the EventThreads always contain a reference to a
2684 // prior configuration.
2685 //
2686 // This is a bit hacky, but this avoids a back-pointer into the main SF
2687 // classes from EventThread, and there should be no run-time binder cost
2688 // anyway since there are no connected apps at this point.
2689 const nsecs_t vsyncPeriod =
2690 mRefreshRateConfigs->getRefreshRateFromConfigId(currentConfig).vsyncPeriod;
2691 mScheduler->onConfigChanged(mAppConnectionHandle, primaryDisplayId.value, currentConfig,
2692 vsyncPeriod);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002693}
2694
Mathias Agopian4fec8732012-06-29 14:12:52 -07002695void SurfaceFlinger::commitTransaction()
2696{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002697 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002698
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002699 mTransactionPending = false;
2700 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002701 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002702}
2703
Lloyd Pique58e24a32019-08-01 15:50:14 -07002704void SurfaceFlinger::commitTransactionLocked() {
2705 if (!mLayersPendingRemoval.isEmpty()) {
2706 // Notify removed layers now that they can't be drawn from
2707 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002708 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002709
2710 // Ensure any buffers set to display on any children are released.
2711 if (l->isRemovedFromCurrentState()) {
2712 l->latchAndReleaseBuffer();
2713 }
2714
2715 // If the layer has been removed and has no parent, then it will not be reachable
2716 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2717 // ensure we can copy its current to drawing state.
2718 if (!l->getParent()) {
2719 mOffscreenLayers.emplace(l.get());
2720 }
2721 }
2722 mLayersPendingRemoval.clear();
2723 }
2724
2725 // If this transaction is part of a window animation then the next frame
2726 // we composite should be considered an animation as well.
2727 mAnimCompositionPending = mAnimTransactionPending;
2728
2729 mDrawingState = mCurrentState;
2730 // clear the "changed" flags in current state
2731 mCurrentState.colorMatrixChanged = false;
2732
2733 mDrawingState.traverseInZOrder([&](Layer* layer) {
2734 layer->commitChildList();
2735
2736 // If the layer can be reached when traversing mDrawingState, then the layer is no
2737 // longer offscreen. Remove the layer from the offscreenLayer set.
2738 if (mOffscreenLayers.count(layer)) {
2739 mOffscreenLayers.erase(layer);
2740 }
2741 });
2742
2743 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002744 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002745}
2746
Nataniel Borges2b796da2019-02-15 13:32:18 -08002747void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2748 if (mTracingEnabledChanged) {
2749 mTracingEnabled = mTracing.isEnabled();
2750 mTracingEnabledChanged = false;
2751 }
2752
2753 // Synchronize with Tracing thread
2754 std::unique_lock<std::mutex> lock;
2755 if (mTracingEnabled) {
2756 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2757 }
2758
2759 lockedOperation();
2760
2761 // Synchronize with Tracing thread
2762 if (mTracingEnabled) {
2763 lock.unlock();
2764 }
2765}
2766
chaviw74d90ad2019-04-26 14:45:26 -07002767void SurfaceFlinger::commitOffscreenLayers() {
2768 for (Layer* offscreenLayer : mOffscreenLayers) {
2769 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2770 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2771 if (!trFlags) return;
2772
2773 layer->doTransaction(0);
2774 layer->commitChildList();
2775 });
2776 }
2777}
2778
Chia-I Wuab0c3192017-08-01 11:29:00 -07002779void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002780 for (const auto& [token, displayDevice] : mDisplays) {
2781 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002782 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002783 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002784 }
2785 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002786}
2787
Dan Stoza6b9454d2014-11-07 16:00:59 -08002788bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002789{
Ady Abraham09bd3922019-04-08 10:44:56 -07002790 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002791 ALOGV("handlePageFlip");
2792
Brian Andersond6927fb2016-07-23 23:37:30 -07002793 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002794
Mathias Agopian4fec8732012-06-29 14:12:52 -07002795 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002796 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002797 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002798
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002799 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2800
Eric Penner51c59cd2014-07-28 19:51:58 -07002801 // Store the set of layers that need updates. This set must not change as
2802 // buffers are being latched, as this could result in a deadlock.
2803 // Example: Two producers share the same command stream and:
2804 // 1.) Layer 0 is latched
2805 // 2.) Layer 0 gets a new frame
2806 // 2.) Layer 1 gets a new frame
2807 // 3.) Layer 1 is latched.
2808 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2809 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002810 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002811 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002812 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002813 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002814 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002815 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002816 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002817 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002818 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002819 } else {
2820 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002821 }
Robert Carr2047fae2016-11-28 14:09:09 -08002822 });
2823
chaviw49a108c2019-08-12 11:23:06 -07002824 // The client can continue submitting buffers for offscreen layers, but they will not
2825 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2826 // layers to ensure dequeueBuffer doesn't block indefinitely.
2827 for (Layer* offscreenLayer : mOffscreenLayers) {
2828 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2829 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2830 }
2831
Lloyd Piquef2c79392018-12-20 16:23:33 -08002832 if (!mLayersWithQueuedFrames.empty()) {
2833 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2834 // writes to Layer current state. See also b/119481871
2835 Mutex::Autolock lock(mStateLock);
2836
2837 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002838 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002839 mLayersPendingRefresh.push_back(layer);
2840 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002841 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002842 if (layer->isBufferLatched()) {
2843 newDataLatched = true;
2844 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002845 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002846 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002847
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002848 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002849
2850 // If we will need to wake up at some time in the future to deal with a
2851 // queued frame that shouldn't be displayed during this vsync period, wake
2852 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002853 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002854 signalLayerUpdate();
2855 }
2856
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002857 // enter boot animation on first buffer latch
2858 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2859 ALOGI("Enter boot animation");
2860 mBootStage = BootStage::BOOTANIMATION;
2861 }
2862
chaviw74b03172019-08-19 11:09:03 -07002863 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2864
Dan Stoza6b9454d2014-11-07 16:00:59 -08002865 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002866 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002867}
2868
Mathias Agopianad456f92011-01-13 17:53:01 -08002869void SurfaceFlinger::invalidateHwcGeometry()
2870{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002871 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002872}
2873
Robert Carrc0df3122019-04-11 13:18:21 -07002874status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2875 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2876 const sp<IBinder>& parentHandle,
2877 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002878 // add this layer to the current state list
2879 {
2880 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002881 sp<Layer> parent;
2882 if (parentHandle != nullptr) {
2883 parent = fromHandle(parentHandle);
2884 if (parent == nullptr) {
2885 return NAME_NOT_FOUND;
2886 }
2887 } else {
2888 parent = parentLayer;
2889 }
2890
Robert Carr1f0a16a2016-10-24 16:27:39 -07002891 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002892 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002893 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002894 return NO_MEMORY;
2895 }
Robert Carrc0df3122019-04-11 13:18:21 -07002896
2897 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2898
Robert Carrb89ea9d2018-12-10 13:01:14 -08002899 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002900 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002901 } else if (parent == nullptr) {
2902 lbc->onRemovedFromCurrentState();
2903 } else if (parent->isRemovedFromCurrentState()) {
2904 parent->addChild(lbc);
2905 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002906 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002907 parent->addChild(lbc);
2908 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002909
Yiwei Zhang243b3782018-05-15 17:40:04 -07002910 if (gbc != nullptr) {
2911 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2912 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2913 mMaxGraphicBufferProducerListSize,
2914 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2915 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002916 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002917 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002918 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002919 }
2920
Mathias Agopian96f08192010-06-02 23:28:45 -07002921 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002922 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002923
Dan Stoza7d89d062015-04-30 13:29:25 -07002924 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002925}
2926
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002927uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002928 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002929}
2930
Mathias Agopian3f844832013-08-07 21:24:32 -07002931uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002932 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002933}
2934
Mathias Agopian3f844832013-08-07 21:24:32 -07002935uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002936 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002937}
2938
2939uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002940 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002941 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002942 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002943 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002944 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002945 }
2946 return old;
2947}
2948
Marissa Wall713b63f2018-10-17 15:42:43 -07002949bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002950 // to prevent onHandleDestroyed from being called while the lock is held,
2951 // we must keep a copy of the transactions (specifically the composer
2952 // states) around outside the scope of the lock
2953 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002954 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002955 {
2956 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002957
Valerie Haufce31b82019-04-30 16:41:14 -07002958 auto it = mTransactionQueues.begin();
2959 while (it != mTransactionQueues.end()) {
2960 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002961
Valerie Haufce31b82019-04-30 16:41:14 -07002962 while (!transactionQueue.empty()) {
2963 const auto& transaction = transactionQueue.front();
2964 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002965 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002966 transaction.states)) {
2967 setTransactionFlags(eTransactionFlushNeeded);
2968 break;
2969 }
2970 transactions.push_back(transaction);
2971 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2972 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002973 transaction.buffer, transaction.postTime,
2974 transaction.privileged, transaction.hasListenerCallbacks,
2975 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002976 transactionQueue.pop();
2977 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002978 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002979
Valerie Haufce31b82019-04-30 16:41:14 -07002980 if (transactionQueue.empty()) {
2981 it = mTransactionQueues.erase(it);
2982 mTransactionCV.broadcast();
2983 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002984 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002985 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002986 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002987 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002988 return flushedATransaction;
2989}
2990
2991bool SurfaceFlinger::transactionFlushNeeded() {
2992 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07002993}
2994
chaviwca27f252018-02-06 16:46:39 -08002995
Marissa Wall17b4e452018-12-26 16:32:34 -08002996bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002997 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08002998 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002999 if (!useCachedExpectedPresentTime)
3000 populateExpectedPresentTime();
3001
3002 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08003003 // Do not present if the desiredPresentTime has not passed unless it is more than one second
3004 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
3005 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
3006 desiredPresentTime < expectedPresentTime + s2ns(1)) {
3007 return false;
3008 }
3009
Marissa Wall713b63f2018-10-17 15:42:43 -07003010 for (const ComposerState& state : states) {
3011 const layer_state_t& s = state.state;
3012 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
3013 continue;
3014 }
3015 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08003016 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07003017 }
3018 }
Marissa Wall17b4e452018-12-26 16:32:34 -08003019 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07003020}
3021
Valerie Hau9dab9732019-08-20 09:29:25 -07003022void SurfaceFlinger::setTransactionState(
3023 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3024 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
3025 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
3026 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003027 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08003028
Valerie Haubc6ddb12019-03-08 11:10:15 -08003029 const int64_t postTime = systemTime();
3030
Robert Carr14167e02019-02-13 13:50:55 -08003031 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
3032
Mathias Agopian698c0872011-06-28 19:09:31 -07003033 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07003034
Marissa Wall713b63f2018-10-17 15:42:43 -07003035 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07003036 auto itr = mTransactionQueues.find(applyToken);
3037 // if this is an animation frame, wait until prior animation frame has
3038 // been applied by SF
3039 if (flags & eAnimation) {
3040 while (itr != mTransactionQueues.end()) {
3041 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3042 if (CC_UNLIKELY(err != NO_ERROR)) {
3043 ALOGW_IF(err == TIMED_OUT,
3044 "setTransactionState timed out "
3045 "waiting for animation frame to apply");
3046 break;
3047 }
3048 itr = mTransactionQueues.find(applyToken);
3049 }
3050 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07003051
3052 // Expected present time is computed and cached on invalidate, so it may be stale.
3053 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
3054 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08003055 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003056 uncacheBuffer, postTime, privileged,
3057 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07003058 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07003059 return;
3060 }
3061
Valerie Haubc6ddb12019-03-08 11:10:15 -08003062 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07003063 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
3064 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07003065}
3066
Valerie Hau9dab9732019-08-20 09:29:25 -07003067void SurfaceFlinger::applyTransactionState(
3068 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
3069 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
3070 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
3071 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
3072 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07003073 uint32_t transactionFlags = 0;
3074
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003075 if (flags & eAnimation) {
3076 // For window updates that are part of an animation we must wait for
3077 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07003078 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003079 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003080 if (CC_UNLIKELY(err != NO_ERROR)) {
3081 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07003082 // caller after a few seconds.
3083 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
3084 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003085 mAnimTransactionPending = false;
3086 break;
3087 }
3088 }
3089 }
3090
chaviwca27f252018-02-06 16:46:39 -08003091 for (const DisplayState& display : displays) {
3092 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07003093 }
3094
Valerie Hau9dab9732019-08-20 09:29:25 -07003095 // start and end registration for listeners w/ no surface so they can get their callback. Note
3096 // that listeners with SurfaceControls will start registration during setClientStateLocked
3097 // below.
3098 for (const auto& listener : listenerCallbacks) {
3099 mTransactionCompletedThread.startRegistration(listener);
3100 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07003101 }
3102
Valerie Hau9dab9732019-08-20 09:29:25 -07003103 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07003104 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08003105 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003106 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
3107 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07003108 }
3109
Valerie Hau9dab9732019-08-20 09:29:25 -07003110 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003111 mTransactionCompletedThread.endRegistration(listenerCallback);
3112 }
3113
Marissa Walle2ffb422018-10-12 11:33:52 -07003114 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07003115 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003116 mTransactionCompletedThread.sendCallbacks();
3117 }
3118 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08003119
chaviw273171b2018-12-26 11:46:30 -08003120 transactionFlags |= addInputWindowCommands(inputWindowCommands);
3121
Marissa Wall947d34e2019-03-29 14:03:53 -07003122 if (uncacheBuffer.isValid()) {
3123 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07003124 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07003125 }
3126
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003127 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3128 // anyway. This can be used as a flush mechanism for previous async transactions.
3129 // Empty animation transaction can be used to simulate back-pressure, so also force a
3130 // transaction for empty animation transactions.
3131 if (transactionFlags == 0 &&
3132 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003133 transactionFlags = eTransactionNeeded;
3134 }
3135
Marissa Wall06255332019-03-27 13:48:27 -07003136 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3137 // so we don't have to wake up again next frame to preform an uneeded traversal.
3138 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3139 transactionFlags = transactionFlags & (~eTraversalNeeded);
3140 mTraversalNeededMainThread = true;
3141 }
3142
Mathias Agopian386aa982011-11-07 21:58:03 -08003143 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003144 if (mInterceptor->isEnabled()) {
3145 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003146 }
Irvel468051e2016-06-13 16:44:44 -07003147
Mathias Agopian386aa982011-11-07 21:58:03 -08003148 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003149 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3150 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003151 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003152
3153 // if this is a synchronous transaction, wait for it to take effect
3154 // before returning.
3155 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003156 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003157 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003158 if (flags & eAnimation) {
3159 mAnimTransactionPending = true;
3160 }
chaviw4fe36852019-04-15 16:25:49 -07003161 if (mPendingInputWindowCommands.syncInputWindows) {
3162 mPendingSyncInputWindows = true;
3163 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003164
3165 // applyTransactionState can be called by either the main SF thread or by
3166 // another process through setTransactionState. While a given process may wish
3167 // to wait on synchronous transactions, the main SF thread should never
3168 // be blocked. Therefore, we only wait if isMainThread is false.
3169 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003170 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3171 if (CC_UNLIKELY(err != NO_ERROR)) {
3172 // just in case something goes wrong in SF, return to the
3173 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003174 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3175 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003176 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003177 break;
3178 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003179 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003180 }
3181}
3182
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003183uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3184 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3185 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003186
Mathias Agopiane57f2922012-08-09 16:29:12 -07003187 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003188 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3189
3190 const uint32_t what = s.what;
3191 if (what & DisplayState::eSurfaceChanged) {
3192 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3193 state.surface = s.surface;
3194 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003195 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003196 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003197 if (what & DisplayState::eLayerStackChanged) {
3198 if (state.layerStack != s.layerStack) {
3199 state.layerStack = s.layerStack;
3200 flags |= eDisplayTransactionNeeded;
3201 }
3202 }
3203 if (what & DisplayState::eDisplayProjectionChanged) {
3204 if (state.orientation != s.orientation) {
3205 state.orientation = s.orientation;
3206 flags |= eDisplayTransactionNeeded;
3207 }
3208 if (state.frame != s.frame) {
3209 state.frame = s.frame;
3210 flags |= eDisplayTransactionNeeded;
3211 }
3212 if (state.viewport != s.viewport) {
3213 state.viewport = s.viewport;
3214 flags |= eDisplayTransactionNeeded;
3215 }
3216 }
3217 if (what & DisplayState::eDisplaySizeChanged) {
3218 if (state.width != s.width) {
3219 state.width = s.width;
3220 flags |= eDisplayTransactionNeeded;
3221 }
3222 if (state.height != s.height) {
3223 state.height = s.height;
3224 flags |= eDisplayTransactionNeeded;
3225 }
3226 }
3227
Mathias Agopiane57f2922012-08-09 16:29:12 -07003228 return flags;
3229}
3230
Robert Carr14167e02019-02-13 13:50:55 -08003231bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003232 IPCThreadState* ipc = IPCThreadState::self();
3233 const int pid = ipc->getCallingPid();
3234 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003235 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003236 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003237 return false;
3238 }
3239 return true;
3240}
3241
Marissa Wall3dad52d2019-03-22 14:03:19 -07003242uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003243 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3244 bool privileged,
3245 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003246 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003247
Valerie Hau9dab9732019-08-20 09:29:25 -07003248 for (auto& listener : s.listeners) {
3249 // note that startRegistration will not re-register if the listener has
3250 // already be registered for a prior surface control
3251 mTransactionCompletedThread.startRegistration(listener);
3252 listenerCallbacks.insert(listener);
3253 }
3254
Vishnu Nairdc6f5b92019-12-03 07:33:37 -08003255 sp<Layer> layer = nullptr;
3256 if (s.surface) {
3257 layer = fromHandle(s.surface);
3258 } else {
3259 // The client may provide us a null handle. Treat it as if the layer was removed.
3260 ALOGW("Attempt to set client state with a null layer handle");
3261 }
chaviw8b3871a2017-11-01 17:41:01 -07003262 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003263 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003264 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003265 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003266 }
chaviw8b3871a2017-11-01 17:41:01 -07003267 return 0;
3268 }
3269
chaviw8b3871a2017-11-01 17:41:01 -07003270 uint32_t flags = 0;
3271
Garfield Tan8a3083e2018-12-03 13:21:07 -08003272 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003273
3274 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3275 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003276 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003277 layer->pushPendingState();
3278 }
3279
chaviw8b3871a2017-11-01 17:41:01 -07003280 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003281 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003282 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003283 }
chaviw8b3871a2017-11-01 17:41:01 -07003284 }
3285 if (what & layer_state_t::eLayerChanged) {
3286 // NOTE: index needs to be calculated before we update the state
3287 const auto& p = layer->getParent();
3288 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003289 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003290 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003291 mCurrentState.layersSortedByZ.removeAt(idx);
3292 mCurrentState.layersSortedByZ.add(layer);
3293 // we need traversal (state changed)
3294 // AND transaction (list changed)
3295 flags |= eTransactionNeeded|eTraversalNeeded;
3296 }
chaviw8b3871a2017-11-01 17:41:01 -07003297 } else {
3298 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003299 flags |= eTransactionNeeded|eTraversalNeeded;
3300 }
3301 }
chaviw8b3871a2017-11-01 17:41:01 -07003302 }
3303 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003304 // NOTE: index needs to be calculated before we update the state
3305 const auto& p = layer->getParent();
3306 if (p == nullptr) {
3307 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3308 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3309 mCurrentState.layersSortedByZ.removeAt(idx);
3310 mCurrentState.layersSortedByZ.add(layer);
3311 // we need traversal (state changed)
3312 // AND transaction (list changed)
3313 flags |= eTransactionNeeded|eTraversalNeeded;
3314 }
3315 } else {
3316 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3317 flags |= eTransactionNeeded|eTraversalNeeded;
3318 }
chaviw8b3871a2017-11-01 17:41:01 -07003319 }
3320 }
3321 if (what & layer_state_t::eSizeChanged) {
3322 if (layer->setSize(s.w, s.h)) {
3323 flags |= eTraversalNeeded;
3324 }
3325 }
3326 if (what & layer_state_t::eAlphaChanged) {
3327 if (layer->setAlpha(s.alpha))
3328 flags |= eTraversalNeeded;
3329 }
3330 if (what & layer_state_t::eColorChanged) {
3331 if (layer->setColor(s.color))
3332 flags |= eTraversalNeeded;
3333 }
Peiyong Lind3788632018-09-18 16:01:31 -07003334 if (what & layer_state_t::eColorTransformChanged) {
3335 if (layer->setColorTransform(s.colorTransform)) {
3336 flags |= eTraversalNeeded;
3337 }
3338 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003339 if (what & layer_state_t::eBackgroundColorChanged) {
3340 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3341 flags |= eTraversalNeeded;
3342 }
3343 }
chaviw8b3871a2017-11-01 17:41:01 -07003344 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003345 // TODO: b/109894387
3346 //
3347 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3348 // rotation. To see the problem observe that if we have a square parent, and a child
3349 // of the same size, then we rotate the child 45 degrees around it's center, the child
3350 // must now be cropped to a non rectangular 8 sided region.
3351 //
3352 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3353 // private API, and the WindowManager only uses rotation in one case, which is on a top
3354 // level layer in which cropping is not an issue.
3355 //
3356 // However given that abuse of rotation matrices could lead to surfaces extending outside
3357 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3358 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3359 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003360 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003361 flags |= eTraversalNeeded;
3362 }
3363 if (what & layer_state_t::eTransparentRegionChanged) {
3364 if (layer->setTransparentRegionHint(s.transparentRegion))
3365 flags |= eTraversalNeeded;
3366 }
3367 if (what & layer_state_t::eFlagsChanged) {
3368 if (layer->setFlags(s.flags, s.mask))
3369 flags |= eTraversalNeeded;
3370 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003371 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003372 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003373 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003374 if (what & layer_state_t::eCornerRadiusChanged) {
3375 if (layer->setCornerRadius(s.cornerRadius))
3376 flags |= eTraversalNeeded;
3377 }
chaviw8b3871a2017-11-01 17:41:01 -07003378 if (what & layer_state_t::eLayerStackChanged) {
3379 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3380 // We only allow setting layer stacks for top level layers,
3381 // everything else inherits layer stack from its parent.
3382 if (layer->hasParent()) {
3383 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003384 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003385 } else if (idx < 0) {
3386 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003387 "that also does not appear in the top level layer list. Something"
3388 " has gone wrong.",
3389 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003390 } else if (layer->setLayerStack(s.layerStack)) {
3391 mCurrentState.layersSortedByZ.removeAt(idx);
3392 mCurrentState.layersSortedByZ.add(layer);
3393 // we need traversal (state changed)
3394 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003395 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003396 }
3397 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003398 if (what & layer_state_t::eDeferTransaction_legacy) {
3399 if (s.barrierHandle_legacy != nullptr) {
3400 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3401 } else if (s.barrierGbp_legacy != nullptr) {
3402 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003403 if (authenticateSurfaceTextureLocked(gbp)) {
3404 const auto& otherLayer =
3405 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003406 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003407 } else {
3408 ALOGE("Attempt to defer transaction to to an"
3409 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003410 }
3411 }
chaviw8b3871a2017-11-01 17:41:01 -07003412 // We don't trigger a traversal here because if no other state is
3413 // changed, we don't want this to cause any more work
3414 }
chaviw8b3871a2017-11-01 17:41:01 -07003415 if (what & layer_state_t::eReparentChildren) {
3416 if (layer->reparentChildren(s.reparentHandle)) {
3417 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003418 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003419 }
chaviw8b3871a2017-11-01 17:41:01 -07003420 if (what & layer_state_t::eDetachChildren) {
3421 layer->detachChildren();
3422 }
3423 if (what & layer_state_t::eOverrideScalingModeChanged) {
3424 layer->setOverrideScalingMode(s.overrideScalingMode);
3425 // We don't trigger a traversal here because if no other state is
3426 // changed, we don't want this to cause any more work
3427 }
Marissa Wall61c58622018-07-18 10:12:20 -07003428 if (what & layer_state_t::eTransformChanged) {
3429 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3430 }
3431 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3432 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3433 flags |= eTraversalNeeded;
3434 }
3435 if (what & layer_state_t::eCropChanged) {
3436 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3437 }
Marissa Wall861616d2018-10-22 12:52:23 -07003438 if (what & layer_state_t::eFrameChanged) {
3439 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3440 }
Marissa Wall61c58622018-07-18 10:12:20 -07003441 if (what & layer_state_t::eAcquireFenceChanged) {
3442 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3443 }
3444 if (what & layer_state_t::eDataspaceChanged) {
3445 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3446 }
3447 if (what & layer_state_t::eHdrMetadataChanged) {
3448 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3449 }
3450 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3451 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3452 }
3453 if (what & layer_state_t::eApiChanged) {
3454 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3455 }
3456 if (what & layer_state_t::eSidebandStreamChanged) {
3457 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3458 }
Robert Carr720e5062018-07-30 17:45:14 -07003459 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003460 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003461 layer->setInputInfo(s.inputInfo);
3462 flags |= eTraversalNeeded;
3463 } else {
3464 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3465 }
Robert Carr720e5062018-07-30 17:45:14 -07003466 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003467 if (what & layer_state_t::eMetadataChanged) {
3468 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3469 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003470 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3471 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3472 flags |= eTraversalNeeded;
3473 }
3474 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003475 if (what & layer_state_t::eShadowRadiusChanged) {
3476 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3477 }
Ana Krulecc84d09b2019-11-02 23:10:29 +01003478 if (what & layer_state_t::eFrameRateSelectionPriority) {
3479 if (privileged && layer->setFrameRateSelectionPriority(s.frameRateSelectionPriority)) {
3480 flags |= eTraversalNeeded;
3481 }
3482 }
Steven Thomas3172e202020-01-06 19:25:30 -08003483 if (what & layer_state_t::eFrameRateChanged) {
3484 if (layer->setFrameRate(s.frameRate)) flags |= eTraversalNeeded;
3485 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003486 // This has to happen after we reparent children because when we reparent to null we remove
3487 // child layers from current state and remove its relative z. If the children are reparented in
3488 // the same transaction, then we have to make sure we reparent the children first so we do not
3489 // lose its relative z order.
3490 if (what & layer_state_t::eReparent) {
3491 bool hadParent = layer->hasParent();
3492 if (layer->reparent(s.parentHandleForChild)) {
3493 if (!hadParent) {
3494 mCurrentState.layersSortedByZ.remove(layer);
3495 }
3496 flags |= eTransactionNeeded | eTraversalNeeded;
3497 }
3498 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003499 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003500 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3501 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003502 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3503 }
3504 }
Marissa Wall78b72202019-03-15 14:58:34 -07003505 bool bufferChanged = what & layer_state_t::eBufferChanged;
3506 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3507 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003508 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003509 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003510 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3511 if (success) {
3512 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3513 success = ClientCache::getInstance()
3514 .registerErasedRecipient(s.cachedBuffer,
3515 wp<ClientCache::ErasedRecipient>(this));
3516 if (!success) {
3517 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3518 }
3519 }
Marissa Wall78b72202019-03-15 14:58:34 -07003520 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003521 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003522 } else if (bufferChanged) {
3523 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003524 }
Marissa Wall78b72202019-03-15 14:58:34 -07003525 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003526 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003527 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003528 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003529 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003530 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3531 // Do not put anything that updates layer state or modifies flags after
3532 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003533 return flags;
3534}
3535
chaviw273171b2018-12-26 11:46:30 -08003536uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3537 uint32_t flags = 0;
3538 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3539 flags |= eTraversalNeeded;
3540 }
3541
chaviwa911b102019-02-14 10:18:33 -08003542 if (inputWindowCommands.syncInputWindows) {
3543 flags |= eTraversalNeeded;
3544 }
3545
Vishnu Nairec0ab382019-02-13 15:32:56 -08003546 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003547 return flags;
3548}
3549
chaviwfe94a222019-08-21 13:52:59 -07003550status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3551 sp<IBinder>* outHandle) {
3552 if (!mirrorFromHandle) {
3553 return NAME_NOT_FOUND;
3554 }
3555
3556 sp<Layer> mirrorLayer;
3557 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003558 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003559
3560 {
3561 Mutex::Autolock _l(mStateLock);
3562 mirrorFrom = fromHandle(mirrorFromHandle);
3563 if (!mirrorFrom) {
3564 return NAME_NOT_FOUND;
3565 }
3566
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003567 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3568 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003569 if (result != NO_ERROR) {
3570 return result;
3571 }
3572
3573 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3574 }
3575
3576 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3577}
3578
Marissa Wall2d814fb2019-04-09 18:52:57 +00003579status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3580 uint32_t h, PixelFormat format, uint32_t flags,
3581 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003582 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003583 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3584 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003585 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003586 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003587 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003588 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003589 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003590
Robert Carrc0df3122019-04-11 13:18:21 -07003591 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3592 "Expected only one of parentLayer or parentHandle to be non-null. "
3593 "Programmer error?");
3594
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003595 status_t result = NO_ERROR;
3596
3597 sp<Layer> layer;
3598
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003599 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003600
Evan Roskya1f1e152019-01-24 16:17:46 -08003601 bool primaryDisplayOnly = false;
3602
3603 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3604 // TODO b/64227542
3605 if (metadata.has(METADATA_WINDOW_TYPE)) {
3606 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3607 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003608 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003609 primaryDisplayOnly = true;
3610 }
3611 }
3612
Mathias Agopian3165cc22012-08-08 19:42:09 -07003613 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003614 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003615 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3616 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003617
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003618 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003619 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003620 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003621 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003622 break;
chaviw13fdc492017-06-27 12:40:18 -07003623 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003624 // check if buffer size is set for color layer.
3625 if (w > 0 || h > 0) {
3626 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3627 int(w), int(h));
3628 return BAD_VALUE;
3629 }
3630
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003631 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3632 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003633 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003634 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003635 // check if buffer size is set for container layer.
3636 if (w > 0 || h > 0) {
3637 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3638 int(w), int(h));
3639 return BAD_VALUE;
3640 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003641 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3642 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003643 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003644 default:
3645 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003646 break;
3647 }
3648
Dan Stoza7d89d062015-04-30 13:29:25 -07003649 if (result != NO_ERROR) {
3650 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003651 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003652
Evan Roskya1f1e152019-01-24 16:17:46 -08003653 if (primaryDisplayOnly) {
3654 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003655 }
3656
Robert Carrb89ea9d2018-12-10 13:01:14 -08003657 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003658 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3659 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003660 if (result != NO_ERROR) {
3661 return result;
3662 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003663 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003664
3665 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003666 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003667}
3668
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003669std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3670 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003671
3672 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003673 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003674
Dan Stoza436ccf32018-06-21 12:10:12 -07003675 // Grab the state lock since we're accessing mCurrentState
3676 Mutex::Autolock lock(mStateLock);
3677
Cody Northropbc755282017-03-31 12:00:08 -06003678 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003679 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003680 while (matchFound) {
3681 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003682 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003683 if (layer->getName() == uniqueName) {
3684 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003685 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003686 }
3687 });
3688 }
3689
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003690 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003691 return uniqueName;
3692}
3693
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003694status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003695 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003696 LayerMetadata metadata, PixelFormat& format,
3697 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003698 sp<IGraphicBufferProducer>* gbp,
3699 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003700 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003701 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003702 case PIXEL_FORMAT_TRANSPARENT:
3703 case PIXEL_FORMAT_TRANSLUCENT:
3704 format = PIXEL_FORMAT_RGBA_8888;
3705 break;
3706 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003707 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003708 break;
3709 }
3710
chaviwb4c6e582019-08-16 14:35:07 -07003711 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003712 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003713 args.textureName = getNewTexture();
3714 {
3715 // Grab the SF state lock during this since it's the only safe way to access
3716 // RenderEngine when creating a BufferLayerConsumer
3717 // TODO: Check if this lock is still needed here
3718 Mutex::Autolock lock(mStateLock);
3719 layer = getFactory().createBufferQueueLayer(args);
3720 }
3721
Marissa Wallfd668622018-05-10 10:21:13 -07003722 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003723 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003724 *handle = layer->getHandle();
3725 *gbp = layer->getProducer();
3726 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003727 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003728
Marissa Wallfd668622018-05-10 10:21:13 -07003729 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003730 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003731}
3732
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003733status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003734 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003735 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003736 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003737 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003738 args.displayDevice = getDefaultDisplayDevice();
3739 args.textureName = getNewTexture();
3740 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003741 if (outTransformHint) {
3742 *outTransformHint = layer->getTransformHint();
3743 }
Marissa Wall61c58622018-07-18 10:12:20 -07003744 *handle = layer->getHandle();
3745 *outLayer = layer;
3746
3747 return NO_ERROR;
3748}
3749
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003750status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003751 uint32_t h, uint32_t flags, LayerMetadata metadata,
3752 sp<IBinder>* handle, sp<Layer>* outLayer) {
3753 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003754 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003755 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003756 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003757}
3758
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003759status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003760 uint32_t w, uint32_t h, uint32_t flags,
3761 LayerMetadata metadata, sp<IBinder>* handle,
3762 sp<Layer>* outLayer) {
3763 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003764 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003765 *handle = (*outLayer)->getHandle();
3766 return NO_ERROR;
3767}
3768
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003769void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003770 mLayersPendingRemoval.add(layer);
3771 mLayersRemoved = true;
3772 setTransactionFlags(eTransactionNeeded);
3773}
3774
Robert Carr695d5282018-12-18 15:27:58 -08003775void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003776{
Robert Carr2e102c92018-10-23 12:11:15 -07003777 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003778 // If a layer has a parent, we allow it to out-live it's handle
3779 // with the idea that the parent holds a reference and will eventually
3780 // be cleaned up. However no one cleans up the top-level so we do so
3781 // here.
3782 if (layer->getParent() == nullptr) {
3783 mCurrentState.layersSortedByZ.remove(layer);
3784 }
3785 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003786
3787 auto it = mLayersByLocalBinderToken.begin();
3788 while (it != mLayersByLocalBinderToken.end()) {
3789 if (it->second == layer) {
3790 it = mLayersByLocalBinderToken.erase(it);
3791 } else {
3792 it++;
3793 }
3794 }
3795
Robert Carr695d5282018-12-18 15:27:58 -08003796 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003797}
3798
Mathias Agopianb60314a2012-04-10 22:09:54 -07003799// ---------------------------------------------------------------------------
3800
Andy McFadden13a082e2012-08-24 10:16:42 -07003801void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003802 const auto display = getDefaultDisplayDeviceLocked();
3803 if (!display) return;
3804
3805 const sp<IBinder> token = display->getDisplayToken().promote();
3806 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003807
Jesse Hall01e29052013-02-19 16:13:35 -08003808 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003809 Vector<ComposerState> state;
3810 Vector<DisplayState> displays;
3811 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003812 d.what = DisplayState::eDisplayProjectionChanged |
3813 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003814 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003815 d.layerStack = 0;
Dominik Laskowski718f9602019-11-09 20:01:35 -08003816 d.orientation = ui::ROTATION_0;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003817 d.frame.makeInvalid();
3818 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003819 d.width = 0;
3820 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003821 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003822 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3823 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003824
Dominik Laskowskie9774092018-12-11 10:04:24 -08003825 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003826
Dominik Laskowski83b88212018-12-11 13:34:06 -08003827 const nsecs_t vsyncPeriod = getVsyncPeriod();
3828 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003829
Brian Andersond0010582017-03-07 13:20:31 -08003830 // Use phase of 0 since phase is not known.
3831 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003832 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003833 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003834}
3835
3836void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003837 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003838 postMessageAsync(
3839 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003840}
3841
Ady Abraham27c70212019-06-11 10:52:26 -07003842void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3843 if (mHWCVsyncState != enabled) {
3844 getHwComposer().setVsyncEnabled(displayId, enabled);
3845 mHWCVsyncState = enabled;
3846 }
3847}
3848
Dominik Laskowskie9774092018-12-11 10:04:24 -08003849void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003850 if (display->isVirtual()) {
3851 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003852 return;
3853 }
3854
Dominik Laskowski075d3172018-05-24 15:50:06 -07003855 const auto displayId = display->getId();
3856 LOG_ALWAYS_FATAL_IF(!displayId);
3857
Dominik Laskowski34157762018-10-31 13:07:19 -07003858 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003859
3860 int currentMode = display->getPowerMode();
3861 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003862 return;
3863 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003864
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003865 display->setPowerMode(mode);
3866
Lloyd Pique4dccc412018-01-22 17:21:36 -08003867 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003868 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003869 }
3870
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003871 if (currentMode == HWC_POWER_MODE_OFF) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003872 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003873 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003874 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003875 mScheduler->onScreenAcquired(mAppConnectionHandle);
3876 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003877 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003878
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003879 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003880 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003881 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003882
3883 struct sched_param param = {0};
3884 param.sched_priority = 1;
3885 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3886 ALOGW("Couldn't set SCHED_FIFO on display on");
3887 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003888 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003889 // Turn off the display
3890 struct sched_param param = {0};
3891 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3892 ALOGW("Couldn't set SCHED_OTHER on display off");
3893 }
3894
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003895 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003896 mScheduler->disableHardwareVsync(true);
3897 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003898 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003899
Ady Abraham27c70212019-06-11 10:52:26 -07003900 // Make sure HWVsync is disabled before turning off the display
3901 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3902
Dominik Laskowski075d3172018-05-24 15:50:06 -07003903 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003904 mVisibleRegionsDirty = true;
3905 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003906 } else if (mode == HWC_POWER_MODE_DOZE ||
3907 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003908 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003909 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003910 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003911 mScheduler->onScreenAcquired(mAppConnectionHandle);
3912 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003913 }
3914 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3915 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003916 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003917 mScheduler->disableHardwareVsync(true);
3918 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003919 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003920 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003921 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003922 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003923 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003924 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003925
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003926 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003927 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003928 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003929 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003930 }
3931
Dominik Laskowski34157762018-10-31 13:07:19 -07003932 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003933}
3934
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003935void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003936 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003937 const auto display = getDisplayDevice(displayToken);
3938 if (!display) {
3939 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3940 displayToken.get());
3941 } else if (display->isVirtual()) {
3942 ALOGW("Attempt to set power mode %d for virtual display", mode);
3943 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003944 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003945 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003946 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003947}
3948
3949// ---------------------------------------------------------------------------
3950
Dominik Laskowskic2867142019-01-21 11:33:38 -08003951status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3952 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003953 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003954
Mathias Agopianbd115332013-04-18 16:41:04 -07003955 IPCThreadState* ipc = IPCThreadState::self();
3956 const int pid = ipc->getCallingPid();
3957 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003958
Mathias Agopianbd115332013-04-18 16:41:04 -07003959 if ((uid != AID_SHELL) &&
3960 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003961 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3962 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003963 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003964 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003965 // (this would indicate SF is stuck, but we want to be able to
3966 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003967 status_t err = mStateLock.timedLock(s2ns(1));
3968 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003969 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003970 StringAppendF(&result,
3971 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3972 "(no locks held)\n",
3973 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003974 }
3975
Dominik Laskowskic2867142019-01-21 11:33:38 -08003976 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003977 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003978 {"--dispsync"s,
3979 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003980 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003981 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3982 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3983 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3984 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3985 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3986 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003987 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003988 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3989 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003990
Dominik Laskowskic2867142019-01-21 11:33:38 -08003991 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003992
Dominik Laskowski46470112019-08-02 13:13:11 -07003993 const auto it = dumpers.find(flag);
3994 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003995 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07003996 } else if (!asProto) {
3997 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003998 }
3999
Mathias Agopian9795c422009-08-26 16:36:26 -07004000 if (locked) {
4001 mStateLock.unlock();
4002 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004003
Dominik Laskowski46470112019-08-02 13:13:11 -07004004 if (it == dumpers.end()) {
4005 const LayersProto layersProto = dumpProtoFromMainThread();
4006 if (asProto) {
4007 result.append(layersProto.SerializeAsString());
4008 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07004009 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07004010 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
4011 result.append(LayerProtoParser::layerTreeToString(layerTree));
4012 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07004013 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07004014 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07004015 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004016 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004017 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004018 return NO_ERROR;
4019}
4020
Nataniel Borges8e7dc722019-02-28 15:10:28 -08004021status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
4022 if (asProto && mTracing.isEnabled()) {
4023 mTracing.writeToFileAsync();
4024 }
4025
4026 return doDump(fd, DumpArgs(), asProto);
4027}
4028
Dominik Laskowskic2867142019-01-21 11:33:38 -08004029void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004030 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004031 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004032}
4033
Dominik Laskowskic2867142019-01-21 11:33:38 -08004034void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08004035 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004036
Dominik Laskowskic2867142019-01-21 11:33:38 -08004037 if (args.size() > 1) {
4038 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08004039 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004040 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004041 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004042 }
Robert Carr2047fae2016-11-28 14:09:09 -08004043 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08004044 } else {
4045 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004046 }
4047}
4048
Dominik Laskowskic2867142019-01-21 11:33:38 -08004049void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004050 const bool clearAll = args.size() < 2;
4051 const auto name = clearAll ? String8() : String8(args[1]);
4052
Robert Carr2047fae2016-11-28 14:09:09 -08004053 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004054 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07004055 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004056 }
Robert Carr2047fae2016-11-28 14:09:09 -08004057 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08004058
Svetoslavd85084b2014-03-20 10:28:31 -07004059 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08004060}
4061
Dominik Laskowskic2867142019-01-21 11:33:38 -08004062void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
4063 mTimeStats->parseArgs(asProto, args, result);
4064}
4065
Jamie Gennis6547ff42013-07-16 20:12:42 -07004066// This should only be called from the main thread. Otherwise it would need
4067// the lock and should use mCurrentState rather than mDrawingState.
4068void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08004069 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07004070 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08004071 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07004072
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004073 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07004074}
4075
Yiwei Zhang5434a782018-12-05 18:06:32 -08004076void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004077 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07004078
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004079 if (isLayerTripleBufferingDisabled())
4080 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07004081
Yiwei Zhang5434a782018-12-05 18:06:32 -08004082 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
4083 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
4084 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
4085 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
4086 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
4087 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08004088 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07004089}
4090
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004091void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07004092 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004093
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004094 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004095 result.append("\n");
4096
Ady Abraham9e16a482019-12-03 17:19:41 -08004097 mPhaseConfiguration->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004098 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07004099 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08004100 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004101
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004102 HwcConfigIndexType defaultConfig;
4103 float minFps, maxFps;
4104 mRefreshRateConfigs->getPolicy(&defaultConfig, &minFps, &maxFps);
Ana Krulec234bb162019-11-10 22:55:55 +01004105 StringAppendF(&result,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004106 "DesiredDisplayConfigSpecs: default config ID: %d"
Ana Krulec234bb162019-11-10 22:55:55 +01004107 ", min: %.2f Hz, max: %.2f Hz",
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004108 defaultConfig.value(), minFps, maxFps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07004109 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
4110 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07004111
Ana Krulecc2870422019-01-29 19:00:58 -08004112 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004113}
4114
Yiwei Zhang5434a782018-12-05 18:06:32 -08004115void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
4116 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08004117 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
4118 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004119 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004120 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004121 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004122 }
David Sodman4a36e932017-11-07 14:29:47 -08004123 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08004124 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08004125 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004126 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
4127 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08004128}
4129
Dominik Laskowski87a07e42019-10-10 20:38:02 -07004130void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
4131 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08004132 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
4133 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07004134 for (const auto& segment : history) {
4135 if (!segment.usedThirdBuffer) {
4136 stats.twoBufferTime += segment.totalTime;
4137 }
4138 if (segment.occupancyAverage < 1.0f) {
4139 stats.doubleBufferedTime += segment.totalTime;
4140 } else if (segment.occupancyAverage < 2.0f) {
4141 stats.tripleBufferedTime += segment.totalTime;
4142 }
4143 ++stats.numSegments;
4144 stats.totalTime += segment.totalTime;
4145 }
4146}
4147
Yiwei Zhang5434a782018-12-05 18:06:32 -08004148void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4149 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004150
4151 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4152 const size_t count = currentLayers.size();
4153 for (size_t i=0 ; i<count ; i++) {
4154 currentLayers[i]->dumpFrameEvents(result);
4155 }
4156}
4157
Yiwei Zhang5434a782018-12-05 18:06:32 -08004158void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004159 result.append("Buffering stats:\n");
4160 result.append(" [Layer name] <Active time> <Two buffer> "
4161 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004162 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004163 typedef std::tuple<std::string, float, float, float> BufferTuple;
4164 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004165 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004166 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004167 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004168 if (stats.numSegments == 0) {
4169 continue;
4170 }
4171 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4172 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4173 stats.totalTime;
4174 float doubleBufferRatio = static_cast<float>(
4175 stats.doubleBufferedTime) / stats.totalTime;
4176 float tripleBufferRatio = static_cast<float>(
4177 stats.tripleBufferedTime) / stats.totalTime;
4178 sorted.insert({activeTime, {name, twoBufferRatio,
4179 doubleBufferRatio, tripleBufferRatio}});
4180 }
4181 for (const auto& sortedPair : sorted) {
4182 float activeTime = sortedPair.first;
4183 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004184 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4185 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004186 }
4187 result.append("\n");
4188}
4189
Yiwei Zhang5434a782018-12-05 18:06:32 -08004190void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004191 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004192 const auto displayId = display->getId();
4193 if (!displayId) {
4194 continue;
4195 }
4196 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004197 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004198 continue;
4199 }
4200
Yiwei Zhang5434a782018-12-05 18:06:32 -08004201 StringAppendF(&result,
4202 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4203 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004204 uint8_t port;
4205 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004206 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004207 result.append("no identification data\n");
4208 continue;
4209 }
4210
4211 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004212 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004213 continue;
4214 }
4215
4216 const auto edid = parseEdid(data);
4217 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004218 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004219 continue;
4220 }
4221
Yiwei Zhang5434a782018-12-05 18:06:32 -08004222 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004223 result.append(edid->displayName.data(), edid->displayName.length());
4224 result.append("\"\n");
4225 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004226}
4227
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004228void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4229 std::string& result) const {
4230 hwc2_display_t hwcDisplayId;
4231 uint8_t port;
4232 DisplayIdentificationData data;
4233
4234 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4235 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4236 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4237 }
4238}
4239
Yiwei Zhang5434a782018-12-05 18:06:32 -08004240void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004241 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004242 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4243 StringAppendF(&result, "DisplayColorSetting: %s\n",
4244 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004245
4246 // TODO: print out if wide-color mode is active or not
4247
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004248 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004249 const auto displayId = display->getId();
4250 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004251 continue;
4252 }
4253
Yiwei Zhang5434a782018-12-05 18:06:32 -08004254 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004255 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004256 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004257 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004258 }
4259
Lloyd Pique32cbe282018-10-19 13:09:22 -07004260 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004261 StringAppendF(&result, " Current color mode: %s (%d)\n",
4262 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004263 }
4264 result.append("\n");
4265}
4266
Vishnu Nair8406fd72019-07-30 11:29:31 -07004267LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004268 LayersProto layersProto;
chaviw08f3cb22020-01-13 13:17:21 -08004269 for (const sp<Layer>& layer : mDrawingState.layersSortedByZ) {
4270 layer->writeToProto(layersProto, traceFlags);
4271 }
chaviw1d044282017-09-27 12:19:28 -07004272 return layersProto;
4273}
4274
Vishnu Nair0f085c62019-08-30 08:49:12 -07004275void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4276 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4277 // it.
4278 LayerProto* rootProto = layersProto.add_layers();
4279 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4280 rootProto->set_id(offscreenRootLayerId);
4281 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004282 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004283
4284 for (Layer* offscreenLayer : mOffscreenLayers) {
4285 // Add layer as child of the fake root
4286 rootProto->add_children(offscreenLayer->sequence);
4287
4288 // Add layer
chaviw6d89e2d2020-01-14 14:42:01 -08004289 LayerProto* layerProto = offscreenLayer->writeToProto(layersProto, traceFlags);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004290 layerProto->set_parent(offscreenRootLayerId);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004291 }
4292}
4293
Vishnu Nair8406fd72019-07-30 11:29:31 -07004294LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4295 LayersProto layersProto;
4296 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4297 return layersProto;
4298}
4299
Vishnu Nair0f085c62019-08-30 08:49:12 -07004300void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4301 result.append("Offscreen Layers:\n");
4302 postMessageSync(new LambdaMessage([&]() {
4303 for (Layer* offscreenLayer : mOffscreenLayers) {
4304 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4305 layer->dumpCallingUidPid(result);
4306 });
4307 }
4308 }));
4309}
4310
Dominik Laskowskic2867142019-01-21 11:33:38 -08004311void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4312 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004313 Colorizer colorizer(colorize);
4314
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004315 // figure out if we're stuck somewhere
4316 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004317 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004318 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4319
4320 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004321 * Dump library configuration.
4322 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004323
4324 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004325 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004326 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004327 appendSfConfigString(result);
4328 appendUiConfigString(result);
4329 appendGuiConfigString(result);
4330 result.append("\n");
4331
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004332 result.append("\nDisplay identification data:\n");
4333 dumpDisplayIdentificationData(result);
4334
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004335 result.append("\nWide-Color information:\n");
4336 dumpWideColorInfo(result);
4337
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004338 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004339 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004340 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004341 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004342 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004343
Andy McFadden41d67d72014-04-25 16:58:34 -07004344 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004345 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004346 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004347 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004348 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004349
Dan Stozab90cf072015-03-05 11:05:59 -08004350 dumpStaticScreenStats(result);
4351 result.append("\n");
4352
Alec Mouri40189b02019-03-05 15:07:54 -08004353 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4354 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4355 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004356
Dan Stozae77c7662016-05-13 11:37:28 -07004357 dumpBufferingStats(result);
4358
Andy McFadden4803b742012-09-24 19:07:20 -07004359 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004360 * Dump the visible layer list
4361 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004362 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004363 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004364 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4365 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004366 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004367
Chia-I Wu2f884132018-09-13 15:17:58 -07004368 {
Lloyd Pique207def92019-02-28 16:09:52 -08004369 StringAppendF(&result, "Composition layers\n");
4370 mDrawingState.traverseInZOrder([&](Layer* layer) {
4371 auto compositionLayer = layer->getCompositionLayer();
4372 if (compositionLayer) compositionLayer->dump(result);
4373 });
4374 }
4375
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004376 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004377 * Dump Display state
4378 */
4379
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004380 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004381 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004382 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004383 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004384 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004385 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004386 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004387
4388 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004389 * Dump CompositionEngine state
4390 */
4391
4392 mCompositionEngine->dump(result);
4393
4394 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004395 * Dump SurfaceFlinger global state
4396 */
4397
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004398 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004399 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004400 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004401
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004402 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004403
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004404 DebugEGLImageTracker::getInstance()->dump(result);
4405
Dominik Laskowski075d3172018-05-24 15:50:06 -07004406 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004407 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4408 "undefinedRegion");
Dominik Laskowski718f9602019-11-09 20:01:35 -08004409 StringAppendF(&result, " orientation=%s, isPoweredOn=%d\n",
4410 toCString(display->getOrientation()), display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004411 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004412 StringAppendF(&result,
4413 " transaction-flags : %08x\n"
4414 " gpu_to_cpu_unsupported : %d\n",
4415 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004416
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004417 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004418 displayId && getHwComposer().isConnected(*displayId)) {
4419 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004420 StringAppendF(&result,
4421 " refresh-rate : %f fps\n"
4422 " x-dpi : %f\n"
4423 " y-dpi : %f\n",
Ady Abraham3a77a7b2019-12-02 18:46:59 -08004424 1e9 / getHwComposer().getDisplayVsyncPeriod(*displayId),
4425 activeConfig->getDpiX(), activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004426 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004427
Yiwei Zhang5434a782018-12-05 18:06:32 -08004428 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004429
Dan Stozae22aec72016-08-01 13:20:59 -07004430 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004431 * Tracing state
4432 */
4433 mTracing.dump(result);
4434 result.append("\n");
4435
4436 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004437 * HWC layer minidump
4438 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004439 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004440 const auto displayId = display->getId();
4441 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004442 continue;
4443 }
4444
Yiwei Zhang5434a782018-12-05 18:06:32 -08004445 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004446 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004447 const sp<DisplayDevice> displayDevice = display;
4448 mCurrentState.traverseInZOrder(
4449 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004450 result.append("\n");
4451 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004452
4453 /*
4454 * Dump HWComposer state
4455 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004456 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004457 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004458 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004459 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004460 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004461 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004462
4463 /*
4464 * Dump gralloc state
4465 */
4466 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4467 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004468
4469 /*
4470 * Dump VrFlinger state if in use.
4471 */
4472 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4473 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004474 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004475 result.append("\n");
4476 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004477
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004478 result.append(mTimeStats->miniDump());
4479 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004480}
4481
Chia-I Wu28f320b2018-05-03 11:02:56 -07004482void SurfaceFlinger::updateColorMatrixLocked() {
4483 mat4 colorMatrix;
4484 if (mGlobalSaturationFactor != 1.0f) {
4485 // Rec.709 luma coefficients
4486 float3 luminance{0.213f, 0.715f, 0.072f};
4487 luminance *= 1.0f - mGlobalSaturationFactor;
4488 mat4 saturationMatrix = mat4(
4489 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4490 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4491 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4492 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4493 );
4494 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4495 } else {
4496 colorMatrix = mClientColorMatrix * mDaltonizer();
4497 }
4498
4499 if (mCurrentState.colorMatrix != colorMatrix) {
4500 mCurrentState.colorMatrix = colorMatrix;
4501 mCurrentState.colorMatrixChanged = true;
4502 setTransactionFlags(eTransactionNeeded);
4503 }
4504}
4505
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004506status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004507#pragma clang diagnostic push
4508#pragma clang diagnostic error "-Wswitch-enum"
4509 switch (static_cast<ISurfaceComposerTag>(code)) {
4510 // These methods should at minimum make sure that the client requested
4511 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004512 case BOOT_FINISHED:
4513 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004514 case CREATE_DISPLAY:
4515 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004516 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004517 case GET_ANIMATION_FRAME_STATS:
4518 case GET_HDR_CAPABILITIES:
4519 case SET_ACTIVE_CONFIG:
Ana Krulec0782b882019-10-15 17:34:54 -07004520 case SET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec234bb162019-11-10 22:55:55 +01004521 case GET_DESIRED_DISPLAY_CONFIG_SPECS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004522 case SET_ACTIVE_COLOR_MODE:
Galia Peycheva5492cb52019-10-30 14:13:16 +01004523 case GET_AUTO_LOW_LATENCY_MODE_SUPPORT:
4524 case SET_AUTO_LOW_LATENCY_MODE:
4525 case GET_GAME_CONTENT_TYPE_SUPPORT:
4526 case SET_GAME_CONTENT_TYPE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004527 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004528 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004529 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004530 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004531 case GET_DISPLAYED_CONTENT_SAMPLE:
Vishnu Nairb13bb952019-11-15 10:24:08 -08004532 case NOTIFY_POWER_HINT:
4533 case SET_GLOBAL_SHADOW_SETTINGS: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004534 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4535 IPCThreadState* ipc = IPCThreadState::self();
4536 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4537 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004538 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004539 }
Robert Carr1db73f62016-12-21 12:58:51 -08004540 return OK;
4541 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004542 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004543 IPCThreadState* ipc = IPCThreadState::self();
4544 const int pid = ipc->getCallingPid();
4545 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004546 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4547 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004548 return PERMISSION_DENIED;
4549 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004550 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004551 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004552 // Used by apps to hook Choreographer to SurfaceFlinger.
4553 case CREATE_DISPLAY_EVENT_CONNECTION:
4554 // The following calls are currently used by clients that do not
4555 // request necessary permissions. However, they do not expose any secret
4556 // information, so it is OK to pass them.
4557 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004558 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004559 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004560 case GET_PHYSICAL_DISPLAY_IDS:
4561 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004562 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004563 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004564 case GET_DISPLAY_CONFIGS:
4565 case GET_DISPLAY_STATS:
4566 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4567 // Calling setTransactionState is safe, because you need to have been
4568 // granted a reference to Client* and Handle* to do anything with it.
4569 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004570 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004571 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004572 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004573 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004574 case IS_WIDE_COLOR_DISPLAY:
4575 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4576 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004577 return OK;
4578 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004579 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004580 case CAPTURE_SCREEN:
4581 case ADD_REGION_SAMPLING_LISTENER:
4582 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004583 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004584 IPCThreadState* ipc = IPCThreadState::self();
4585 const int pid = ipc->getCallingPid();
4586 const int uid = ipc->getCallingUid();
4587 if ((uid != AID_GRAPHICS) &&
4588 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4589 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4590 return PERMISSION_DENIED;
4591 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004592 return OK;
4593 }
4594 // The following codes are deprecated and should never be allowed to access SF.
4595 case CONNECT_DISPLAY_UNUSED:
4596 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4597 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4598 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004599 }
chaviw93df2ea2019-04-30 16:45:12 -07004600 case CAPTURE_SCREEN_BY_ID: {
4601 IPCThreadState* ipc = IPCThreadState::self();
4602 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004603 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004604 return OK;
4605 }
4606 return PERMISSION_DENIED;
4607 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004608 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004609
4610 // These codes are used for the IBinder protocol to either interrogate the recipient
4611 // side of the transaction for its canonical interface descriptor or to dump its state.
4612 // We let them pass by default.
4613 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4614 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4615 code == IBinder::SYSPROPS_TRANSACTION) {
4616 return OK;
4617 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004618 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004619 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004620 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004621 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4622 return OK;
4623 }
4624 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4625 return PERMISSION_DENIED;
4626#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004627}
4628
Ana Krulec13be8ad2018-08-21 02:43:56 +00004629status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4630 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004631 status_t credentialCheck = CheckTransactCodeCredentials(code);
4632 if (credentialCheck != OK) {
4633 return credentialCheck;
4634 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004635
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004636 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4637 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004638 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004639 IPCThreadState* ipc = IPCThreadState::self();
4640 const int uid = ipc->getCallingUid();
4641 if (CC_UNLIKELY(uid != AID_SYSTEM
4642 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004643 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004644 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004645 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004646 return PERMISSION_DENIED;
4647 }
4648 int n;
4649 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004650 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004651 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004652 return NO_ERROR;
4653 case 1002: // SHOW_UPDATES
4654 n = data.readInt32();
4655 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004656 invalidateHwcGeometry();
4657 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004658 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004659 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004660 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004661 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004662 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004663 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004664 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004665 setTransactionFlags(
4666 eTransactionNeeded|
4667 eDisplayTransactionNeeded|
4668 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004669 return NO_ERROR;
4670 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004671 case 1006:{ // send empty update
4672 signalRefresh();
4673 return NO_ERROR;
4674 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004675 case 1008: // toggle use of hw composer
4676 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004677 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004678 invalidateHwcGeometry();
4679 repaintEverything();
4680 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004681 case 1009: // toggle use of transform hint
4682 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004683 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004684 invalidateHwcGeometry();
4685 repaintEverything();
4686 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004687 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004688 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004689 reply->writeInt32(0);
4690 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004691 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004692 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004693 return NO_ERROR;
4694 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004695 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004696 if (!display) {
4697 return NAME_NOT_FOUND;
4698 }
4699
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004700 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004701 return NO_ERROR;
4702 }
4703 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004704 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004705 // daltonize
4706 n = data.readInt32();
4707 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004708 case 1:
4709 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4710 break;
4711 case 2:
4712 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4713 break;
4714 case 3:
4715 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4716 break;
4717 default:
4718 mDaltonizer.setType(ColorBlindnessType::None);
4719 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004720 }
4721 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004722 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004723 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004724 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004725 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004726
4727 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004728 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004729 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004730 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004731 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004732 // apply a color matrix
4733 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004734 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004735 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004736 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004737 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004738 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004739 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004740 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004741 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004742 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004743 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004744
4745 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4746 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004747 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004748 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4749 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4750 }
4751
Chia-I Wu28f320b2018-05-03 11:02:56 -07004752 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004753 return NO_ERROR;
4754 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004755 case 1016: { // Unused.
4756 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004757 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004758 case 1017: {
4759 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004760 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004761 return NO_ERROR;
4762 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004763 case 1018: { // Modify Choreographer's phase offset
4764 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004765 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004766 return NO_ERROR;
4767 }
4768 case 1019: { // Modify SurfaceFlinger's phase offset
4769 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004770 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004771 return NO_ERROR;
4772 }
Irvel468051e2016-06-13 16:44:44 -07004773 case 1020: { // Layer updates interceptor
4774 n = data.readInt32();
4775 if (n) {
4776 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004777 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004778 }
4779 else{
4780 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004781 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004782 }
4783 return NO_ERROR;
4784 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004785 case 1021: { // Disable HWC virtual displays
4786 n = data.readInt32();
4787 mUseHwcVirtualDisplays = !n;
4788 return NO_ERROR;
4789 }
Romain Guy0147a172017-06-01 13:53:56 -07004790 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004791 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004792 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004793
Chia-I Wu28f320b2018-05-03 11:02:56 -07004794 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004795 return NO_ERROR;
4796 }
Romain Guy54f154a2017-10-24 21:40:32 +01004797 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004798 int32_t colorMode;
4799
Chia-I Wu0d711262018-05-21 15:19:35 -07004800 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004801 if (data.readInt32(&colorMode) == NO_ERROR) {
4802 mForceColorMode = static_cast<ColorMode>(colorMode);
4803 }
Romain Guy54f154a2017-10-24 21:40:32 +01004804 invalidateHwcGeometry();
4805 repaintEverything();
4806 return NO_ERROR;
4807 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004808 // Deprecate, use 1030 to check whether the device is color managed.
4809 case 1024: {
4810 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004811 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004812 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004813 n = data.readInt32();
4814 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004815 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004816 Mutex::Autolock lock(mStateLock);
4817 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004818 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004819 reply->writeInt32(NO_ERROR);
4820 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004821 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004822 bool writeFile = false;
4823 {
4824 Mutex::Autolock lock(mStateLock);
4825 mTracingEnabledChanged = true;
4826 writeFile = mTracing.disable();
4827 }
4828
4829 if (writeFile) {
4830 reply->writeInt32(mTracing.writeToFile());
4831 } else {
4832 reply->writeInt32(NO_ERROR);
4833 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004834 }
4835 return NO_ERROR;
4836 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004837 case 1026: { // Get layer tracing status
4838 reply->writeBool(mTracing.isEnabled());
4839 return NO_ERROR;
4840 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004841 // Is a DisplayColorSetting supported?
4842 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004843 const auto display = getDefaultDisplayDevice();
4844 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004845 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004846 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004847
4848 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4849 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004850 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004851 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004852 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004853 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004854 reply->writeBool(true);
4855 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004856 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004857 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004858 break;
4859 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004860 reply->writeBool(
4861 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004862 break;
4863 }
4864 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004865 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004866 // Is VrFlinger active?
4867 case 1028: {
4868 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004869 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004870 return NO_ERROR;
4871 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004872 // Set buffer size for SF tracing (value in KB)
4873 case 1029: {
4874 n = data.readInt32();
4875 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4876 ALOGW("Invalid buffer size: %d KB", n);
4877 reply->writeInt32(BAD_VALUE);
4878 return BAD_VALUE;
4879 }
4880
4881 ALOGD("Updating trace buffer to %d KB", n);
4882 mTracing.setBufferSize(n * 1024);
4883 reply->writeInt32(NO_ERROR);
4884 return NO_ERROR;
4885 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004886 // Is device color managed?
4887 case 1030: {
4888 reply->writeBool(useColorManagement);
4889 return NO_ERROR;
4890 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004891 // Override default composition data space
4892 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4893 // && adb shell stop zygote && adb shell start zygote
4894 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4895 // adb shell stop zygote && adb shell start zygote
4896 case 1031: {
4897 Mutex::Autolock _l(mStateLock);
4898 n = data.readInt32();
4899 if (n) {
4900 n = data.readInt32();
4901 if (n) {
4902 Dataspace dataspace = static_cast<Dataspace>(n);
4903 if (!validateCompositionDataspace(dataspace)) {
4904 return BAD_VALUE;
4905 }
4906 mDefaultCompositionDataspace = dataspace;
4907 }
4908 n = data.readInt32();
4909 if (n) {
4910 Dataspace dataspace = static_cast<Dataspace>(n);
4911 if (!validateCompositionDataspace(dataspace)) {
4912 return BAD_VALUE;
4913 }
4914 mWideColorGamutCompositionDataspace = dataspace;
4915 }
4916 } else {
4917 // restore composition data space.
4918 mDefaultCompositionDataspace = defaultCompositionDataspace;
4919 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4920 }
4921 return NO_ERROR;
4922 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004923 // Set trace flags
4924 case 1033: {
4925 n = data.readUint32();
4926 ALOGD("Updating trace flags to 0x%x", n);
4927 mTracing.setTraceFlags(n);
4928 reply->writeInt32(NO_ERROR);
4929 return NO_ERROR;
4930 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004931 case 1034: {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004932 n = data.readInt32();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004933 if (n == 1 && !mRefreshRateOverlay) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004934 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abraham2139f732019-11-13 18:56:40 -08004935 auto current = mRefreshRateConfigs->getCurrentRefreshRate();
4936 mRefreshRateOverlay->changeRefreshRate(current);
Ady Abraham2cb8b622019-12-02 18:55:33 -08004937 } else if (n == 0) {
Ady Abraham03b02dd2019-03-21 15:40:11 -07004938 mRefreshRateOverlay.reset();
Ady Abraham2cb8b622019-12-02 18:55:33 -08004939 } else {
4940 reply->writeBool(mRefreshRateOverlay != nullptr);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004941 }
4942 return NO_ERROR;
4943 }
Ady Abraham34392f72019-04-10 11:29:27 -07004944 case 1035: {
4945 n = data.readInt32();
4946 mDebugDisplayConfigSetByBackdoor = false;
4947 if (n >= 0) {
4948 const auto displayToken = getInternalDisplayToken();
Ana Kruleced3a8cc2019-11-14 00:55:07 +01004949 status_t result = setActiveConfig(displayToken, n);
Ady Abraham34392f72019-04-10 11:29:27 -07004950 if (result != NO_ERROR) {
4951 return result;
4952 }
4953 mDebugDisplayConfigSetByBackdoor = true;
4954 }
4955 return NO_ERROR;
4956 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004957 }
4958 }
4959 return err;
4960}
4961
Steven Thomas6d8110b2017-08-31 18:24:21 -07004962void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004963 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004964 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004965}
4966
Ana Krulec7d1d6832018-12-27 11:10:09 -08004967void SurfaceFlinger::repaintEverythingForHWC() {
4968 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004969 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004970}
4971
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004972// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4973class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004974public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004975 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4976 ~WindowDisconnector() {
4977 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004978 }
4979
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004980private:
4981 ANativeWindow* mWindow;
4982 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004983};
4984
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004985status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07004986 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
Dominik Laskowski718f9602019-11-09 20:01:35 -08004987 Dataspace reqDataspace, ui::PixelFormat reqPixelFormat,
4988 const Rect& sourceCrop, uint32_t reqWidth,
4989 uint32_t reqHeight, bool useIdentityTransform,
4990 ui::Rotation rotation, bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004991 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004992
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004993 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004994
Dominik Laskowski718f9602019-11-09 20:01:35 -08004995 auto renderAreaRotation = ui::Transform::toRotationFlags(rotation);
4996 if (renderAreaRotation == ui::Transform::ROT_INVALID) {
4997 ALOGE("%s: Invalid rotation: %s", __FUNCTION__, toCString(rotation));
4998 renderAreaRotation = ui::Transform::ROT_0;
4999 }
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07005000
Chia-I Wu20261cb2018-08-23 12:55:44 -07005001 sp<DisplayDevice> display;
5002 {
5003 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07005004
Chia-I Wu20261cb2018-08-23 12:55:44 -07005005 display = getDisplayDeviceLocked(displayToken);
5006 if (!display) return BAD_VALUE;
5007
Chia-I Wucb023152018-08-28 12:57:23 -07005008 // set the requested width/height to the logical display viewport size
5009 // by default
5010 if (reqWidth == 0 || reqHeight == 0) {
5011 reqWidth = uint32_t(display->getViewport().width());
5012 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07005013 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07005014 }
5015
Peiyong Lin0e003c92018-09-17 11:09:51 -07005016 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08005017 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005018
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08005019 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5020 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07005021 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005022 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005023}
5024
chaviw93df2ea2019-04-30 16:45:12 -07005025static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
5026 switch (colorMode) {
5027 case ColorMode::DISPLAY_P3:
5028 case ColorMode::BT2100_PQ:
5029 case ColorMode::BT2100_HLG:
5030 case ColorMode::DISPLAY_BT2020:
5031 return Dataspace::DISPLAY_P3;
5032 default:
5033 return Dataspace::V0_SRGB;
5034 }
5035}
5036
5037const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
5038 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
5039 if (displayToken) {
5040 return getDisplayDeviceLocked(displayToken);
5041 }
5042 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
5043 // may not have a displayId.
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005044 return getDisplayByLayerStack(displayOrLayerStack);
5045}
5046
5047const sp<DisplayDevice> SurfaceFlinger::getDisplayByLayerStack(uint64_t layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005048 for (const auto& [token, display] : mDisplays) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005049 if (display->getLayerStack() == layerStack) {
chaviw93df2ea2019-04-30 16:45:12 -07005050 return display;
5051 }
5052 }
5053 return nullptr;
5054}
5055
5056status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
5057 sp<GraphicBuffer>* outBuffer) {
5058 sp<DisplayDevice> display;
5059 uint32_t width;
5060 uint32_t height;
Dominik Laskowski718f9602019-11-09 20:01:35 -08005061 ui::Transform::RotationFlags captureOrientation;
chaviw93df2ea2019-04-30 16:45:12 -07005062 {
5063 Mutex::Autolock _l(mStateLock);
5064 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
5065 if (!display) {
5066 return BAD_VALUE;
5067 }
5068
5069 width = uint32_t(display->getViewport().width());
5070 height = uint32_t(display->getViewport().height());
5071
Dominik Laskowski718f9602019-11-09 20:01:35 -08005072 const auto orientation = display->getOrientation();
5073 captureOrientation = ui::Transform::toRotationFlags(orientation);
5074
5075 switch (captureOrientation) {
5076 case ui::Transform::ROT_90:
5077 captureOrientation = ui::Transform::ROT_270;
5078 break;
5079
5080 case ui::Transform::ROT_270:
5081 captureOrientation = ui::Transform::ROT_90;
5082 break;
5083
5084 case ui::Transform::ROT_INVALID:
5085 ALOGE("%s: Invalid orientation: %s", __FUNCTION__, toCString(orientation));
5086 captureOrientation = ui::Transform::ROT_0;
5087 break;
5088
5089 default:
5090 break;
Alec Mouri21fab752019-06-20 14:12:17 -07005091 }
chaviw93df2ea2019-04-30 16:45:12 -07005092 *outDataspace =
5093 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
5094 }
5095
5096 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
5097 false /* captureSecureLayers */);
5098
5099 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
5100 std::placeholders::_1);
5101 bool ignored = false;
5102 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
5103 false /* useIdentityTransform */,
5104 ignored /* outCapturedSecureLayers */);
5105}
5106
Robert Carr866455f2019-04-02 16:28:26 -07005107status_t SurfaceFlinger::captureLayers(
5108 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
5109 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
5110 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
5111 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07005112 ATRACE_CALL();
5113
5114 class LayerRenderArea : public RenderArea {
5115 public:
Robert Carr578038f2018-03-09 12:25:24 -08005116 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005117 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005118 bool childrenOnly, const Rect& displayViewport)
5119 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace, displayViewport),
Robert Carr578038f2018-03-09 12:25:24 -08005120 mLayer(layer),
5121 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005122 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08005123 mFlinger(flinger),
5124 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07005125 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005126 Rect getBounds() const override {
5127 const Layer::State& layerState(mLayer->getDrawingState());
5128 return mLayer->getBufferSize(layerState);
5129 }
Marissa Wall61c58622018-07-18 10:12:20 -07005130 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005131 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07005132 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08005133 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08005134 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08005135 }
chaviwa76b2712017-09-20 12:02:26 -07005136 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005137 bool needsFiltering() const override { return mNeedsFiltering; }
Dominik Laskowski718f9602019-11-09 20:01:35 -08005138 sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08005139 Rect getSourceCrop() const override {
5140 if (mCrop.isEmpty()) {
5141 return getBounds();
5142 } else {
5143 return mCrop;
5144 }
5145 }
Robert Carr578038f2018-03-09 12:25:24 -08005146 class ReparentForDrawing {
5147 public:
5148 const sp<Layer>& oldParent;
5149 const sp<Layer>& newParent;
5150
Vishnu Nair4351ad52019-02-11 14:13:02 -08005151 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5152 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005153 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005154 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005155 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5156 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005157 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005158 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005159 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005160 };
5161
5162 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005163 const Rect sourceCrop = getSourceCrop();
5164 // no need to check rotation because there is none
5165 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5166 sourceCrop.height() != getReqHeight();
5167
Robert Carr578038f2018-03-09 12:25:24 -08005168 if (!mChildrenOnly) {
5169 mTransform = mLayer->getTransform().inverse();
5170 drawLayers();
5171 } else {
5172 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005173 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5174 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005175 // In the "childrenOnly" case we reparent the children to a screenshot
5176 // layer which has no properties set and which does not draw.
5177 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005178 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5179 "Screenshot Parent"s, w, h, 0,
5180 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005181
Vishnu Nair4351ad52019-02-11 14:13:02 -08005182 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005183 drawLayers();
5184 }
5185 }
chaviwa76b2712017-09-20 12:02:26 -07005186
chaviwa76b2712017-09-20 12:02:26 -07005187 private:
chaviw7206d492017-11-10 16:16:12 -08005188 const sp<Layer> mLayer;
5189 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005190
Peiyong Linefefaac2018-08-17 12:27:51 -07005191 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005192 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005193
5194 SurfaceFlinger* mFlinger;
5195 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005196 };
5197
Robert Carrc0df3122019-04-11 13:18:21 -07005198 int reqWidth = 0;
5199 int reqHeight = 0;
5200 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005201 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005202 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005203 Rect displayViewport;
Robert Carrc0df3122019-04-11 13:18:21 -07005204 {
5205 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005206
Robert Carrc0df3122019-04-11 13:18:21 -07005207 parent = fromHandle(layerHandleBinder);
5208 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5209 ALOGE("captureLayers called with an invalid or removed parent");
5210 return NAME_NOT_FOUND;
5211 }
5212
5213 const int uid = IPCThreadState::self()->getCallingUid();
5214 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5215 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5216 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5217 return PERMISSION_DENIED;
5218 }
5219
Vishnu Nairefc42e22019-12-03 17:36:12 -08005220 Rect parentSourceBounds = parent->getCroppedBufferSize(parent->getCurrentState());
Robert Carrc0df3122019-04-11 13:18:21 -07005221 if (sourceCrop.width() <= 0) {
5222 crop.left = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005223 crop.right = parentSourceBounds.getWidth();
Robert Carrc0df3122019-04-11 13:18:21 -07005224 }
5225
5226 if (sourceCrop.height() <= 0) {
5227 crop.top = 0;
Vishnu Nairefc42e22019-12-03 17:36:12 -08005228 crop.bottom = parentSourceBounds.getHeight();
5229 }
5230
5231 if (crop.isEmpty() || frameScale <= 0.0f) {
5232 // Error out if the layer has no source bounds (i.e. they are boundless) and a source
5233 // crop was not specified, or an invalid frame scale was provided.
5234 return BAD_VALUE;
Robert Carrc0df3122019-04-11 13:18:21 -07005235 }
5236 reqWidth = crop.width() * frameScale;
5237 reqHeight = crop.height() * frameScale;
5238
5239 for (const auto& handle : excludeHandles) {
5240 sp<Layer> excludeLayer = fromHandle(handle);
5241 if (excludeLayer != nullptr) {
5242 excludeLayers.emplace(excludeLayer);
5243 } else {
5244 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5245 return NAME_NOT_FOUND;
5246 }
5247 }
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005248
5249 auto display = getDisplayByLayerStack(parent->getLayerStack());
5250 if (!display) {
5251 return BAD_VALUE;
5252 }
5253
5254 displayViewport = display->getViewport();
Robert Carrc0df3122019-04-11 13:18:21 -07005255 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005256
Chia-I Wu20261cb2018-08-23 12:55:44 -07005257 // really small crop or frameScale
5258 if (reqWidth <= 0) {
5259 reqWidth = 1;
5260 }
5261 if (reqHeight <= 0) {
5262 reqHeight = 1;
5263 }
5264
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005265 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly,
5266 displayViewport);
Robert Carr866455f2019-04-02 16:28:26 -07005267 auto traverseLayers = [parent, childrenOnly,
5268 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005269 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5270 if (!layer->isVisible()) {
5271 return;
Robert Carr578038f2018-03-09 12:25:24 -08005272 } else if (childrenOnly && layer == parent.get()) {
5273 return;
chaviwa76b2712017-09-20 12:02:26 -07005274 }
Robert Carr866455f2019-04-02 16:28:26 -07005275
5276 sp<Layer> p = layer;
5277 while (p != nullptr) {
5278 if (excludeLayers.count(p) != 0) {
5279 return;
5280 }
5281 p = p->getParent();
5282 }
5283
chaviwa76b2712017-09-20 12:02:26 -07005284 visitor(layer);
5285 });
5286 };
Robert Carr108b2c72019-04-02 16:32:58 -07005287
5288 bool outCapturedSecureLayers = false;
5289 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5290 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005291}
5292
5293status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5294 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005295 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005296 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005297 bool useIdentityTransform,
5298 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005299 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005300
Peiyong Lin0e003c92018-09-17 11:09:51 -07005301 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005302 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5303 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005304 *outBuffer =
5305 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5306 static_cast<android_pixel_format>(reqPixelFormat), 1,
5307 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005308
Robert Carr108b2c72019-04-02 16:32:58 -07005309 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5310 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005311}
5312
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005313status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5314 TraverseLayersFunction traverseLayers,
5315 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005316 bool useIdentityTransform,
5317 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005318 // This mutex protects syncFd and captureResult for communication of the return values from the
5319 // main thread back to this Binder thread
5320 std::mutex captureMutex;
5321 std::condition_variable captureCondition;
5322 std::unique_lock<std::mutex> captureLock(captureMutex);
5323 int syncFd = -1;
5324 std::optional<status_t> captureResult;
5325
Robert Carr03480e22018-01-04 16:02:06 -08005326 const int uid = IPCThreadState::self()->getCallingUid();
5327 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5328
Dominik Laskowski8c001672018-05-30 16:52:06 -07005329 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005330 // If there is a refresh pending, bug out early and tell the binder thread to try again
5331 // after the refresh.
5332 if (mRefreshPending) {
5333 ATRACE_NAME("Skipping screenshot for now");
5334 std::unique_lock<std::mutex> captureLock(captureMutex);
5335 captureResult = std::make_optional<status_t>(EAGAIN);
5336 captureCondition.notify_one();
5337 return;
5338 }
5339
5340 status_t result = NO_ERROR;
5341 int fd = -1;
5342 {
5343 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005344 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005345 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005346 useIdentityTransform, forSystem, &fd,
5347 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005348 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005349 }
5350
5351 {
5352 std::unique_lock<std::mutex> captureLock(captureMutex);
5353 syncFd = fd;
5354 captureResult = std::make_optional<status_t>(result);
5355 captureCondition.notify_one();
5356 }
5357 });
5358
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005359 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005360 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005361 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005362 while (*captureResult == EAGAIN) {
5363 captureResult.reset();
5364 result = postMessageAsync(message);
5365 if (result != NO_ERROR) {
5366 return result;
5367 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005368 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005369 }
5370 result = *captureResult;
5371 }
5372
5373 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005374 sync_wait(syncFd, -1);
5375 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005376 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005377
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005378 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005379}
5380
chaviwa76b2712017-09-20 12:02:26 -07005381void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005382 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005383 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5384 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005385 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005386
chaviwa76b2712017-09-20 12:02:26 -07005387 const auto reqWidth = renderArea.getReqWidth();
5388 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005389 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005390 const auto transform = renderArea.getTransform();
5391 const auto sourceCrop = renderArea.getSourceCrop();
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005392 const auto& displayViewport = renderArea.getDisplayViewport();
Dan Stozac1879002014-05-22 15:59:05 -07005393
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005394 renderengine::DisplaySettings clientCompositionDisplay;
5395 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005396
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005397 // assume that bounds are never offset, and that they are the same as the
5398 // buffer bounds.
5399 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005400 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005401 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005402
5403 // Now take into account the rotation flag. We append a transform that
5404 // rotates the layer stack about the origin, then translate by buffer
5405 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005406 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005407 int displacementX = 0;
5408 int displacementY = 0;
5409 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5410 switch (rotation) {
5411 case ui::Transform::ROT_90:
5412 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005413 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005414 break;
5415 case ui::Transform::ROT_180:
5416 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005417 displacementY = renderArea.getBounds().getWidth();
5418 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005419 break;
5420 case ui::Transform::ROT_270:
5421 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005422 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005423 break;
5424 default:
5425 break;
5426 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005427
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005428 // We need to transform the clipping window into the right spot.
5429 // First, rotate the clipping rectangle by the rotation hint to get the
5430 // right orientation
5431 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5432 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5433 const vec4 rotClipTL = rotMatrix * clipTL;
5434 const vec4 rotClipBR = rotMatrix * clipBR;
5435 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5436 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5437 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5438 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5439
5440 // Now reposition the clipping rectangle with the displacement vector
5441 // computed above.
5442 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005443 clientCompositionDisplay.clip =
5444 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5445 newClipRight + displacementX, newClipBottom + displacementY);
5446
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005447 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005448 clientCompositionDisplay.globalTransform =
5449 clipTransform * clientCompositionDisplay.globalTransform;
5450
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005451 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5452 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005453
chaviw50da5042018-04-09 13:49:37 -07005454 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005455
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005456 renderengine::LayerSettings fillLayer;
5457 fillLayer.source.buffer.buffer = nullptr;
5458 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5459 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5460 fillLayer.alpha = half(alpha);
5461 clientCompositionLayers.push_back(fillLayer);
5462
5463 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005464 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005465 const bool supportProtectedContent = false;
5466 Region clip(renderArea.getBounds());
5467 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5468 clip,
5469 useIdentityTransform,
5470 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5471 renderArea.isSecure(),
5472 supportProtectedContent,
5473 clearRegion,
5474 };
5475 auto result = layer->prepareClientComposition(targetSettings);
5476 if (result) {
Vishnu Nair3a7346c2019-12-04 08:09:09 -08005477 std::optional<renderengine::LayerSettings> shadowLayer =
5478 layer->prepareShadowClientComposition(*result, displayViewport,
5479 clientCompositionDisplay.outputDataspace);
5480 if (shadowLayer) {
5481 clientCompositionLayers.push_back(*shadowLayer);
5482 }
Lloyd Piquef16688f2019-02-19 17:47:57 -08005483 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005484 }
chaviwa76b2712017-09-20 12:02:26 -07005485 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005486
5487 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005488 // Use an empty fence for the buffer fence, since we just created the buffer so
5489 // there is no need for synchronization with the GPU.
5490 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005491 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005492 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005493 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005494 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005495
5496 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005497}
5498
chaviwa76b2712017-09-20 12:02:26 -07005499status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5500 TraverseLayersFunction traverseLayers,
5501 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005502 bool useIdentityTransform, bool forSystem,
5503 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005504 ATRACE_CALL();
5505
chaviwa76b2712017-09-20 12:02:26 -07005506 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005507 outCapturedSecureLayers =
5508 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005509 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005510
Robert Carr03480e22018-01-04 16:02:06 -08005511 // We allow the system server to take screenshots of secure layers for
5512 // use in situations like the Screen-rotation animation and place
5513 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005514 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005515 ALOGW("FB is protected: PERMISSION_DENIED");
5516 return PERMISSION_DENIED;
5517 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005518 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005519 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005520}
5521
chaviw95ef3c42019-02-14 10:55:09 -08005522void SurfaceFlinger::setInputWindowsFinished() {
5523 Mutex::Autolock _l(mStateLock);
5524
5525 mPendingSyncInputWindows = false;
5526 mTransactionCV.broadcast();
5527}
chaviw5f21a5e2019-02-14 10:00:34 -08005528
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005529// ---------------------------------------------------------------------------
5530
Dan Stoza412903f2017-04-27 13:42:17 -07005531void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5532 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005533}
5534
Dan Stoza412903f2017-04-27 13:42:17 -07005535void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5536 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005537}
5538
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005539void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005540 const LayerVector::Visitor& visitor) {
5541 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005542 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005543 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005544 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005545 continue;
5546 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005547 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005548 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005549 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005550 return;
5551 }
chaviwa76b2712017-09-20 12:02:26 -07005552 if (!layer->isVisible()) {
5553 return;
5554 }
5555 visitor(layer);
5556 });
5557 }
5558}
5559
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005560status_t SurfaceFlinger::setDesiredDisplayConfigSpecsInternal(const sp<DisplayDevice>& display,
5561 HwcConfigIndexType defaultConfig,
5562 float minRefreshRate,
5563 float maxRefreshRate) {
5564 Mutex::Autolock lock(mStateLock);
5565
Dominik Laskowski22488f62019-03-28 09:53:04 -07005566 if (!display->isPrimary()) {
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005567 // TODO(b/144711714): For non-primary displays we should be able to set an active config
5568 // as well. For now, just call directly to setActiveConfigWithConstraints but ideally
5569 // it should go thru setDesiredActiveConfig, similar to primary display.
5570 ALOGV("setAllowedDisplayConfigsInternal for non-primary display");
5571 const auto displayId = display->getId();
5572 LOG_ALWAYS_FATAL_IF(!displayId);
5573
5574 HWC2::VsyncPeriodChangeConstraints constraints;
5575 constraints.desiredTimeNanos = systemTime();
5576 constraints.seamlessRequired = false;
5577
5578 HWC2::VsyncPeriodChangeTimeline timeline = {0, 0, 0};
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005579 if (getHwComposer().setActiveConfigWithConstraints(*displayId, defaultConfig.value(),
5580 constraints, &timeline) < 0) {
5581 return BAD_VALUE;
5582 }
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005583 if (timeline.refreshRequired) {
5584 repaintEverythingForHWC();
5585 }
5586
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005587 auto configId = HwcConfigIndexType(defaultConfig);
Ady Abraham3a77a7b2019-12-02 18:46:59 -08005588 display->setActiveConfig(configId);
Alec Mouri60aee1c2019-10-28 16:18:59 -07005589 const nsecs_t vsyncPeriod =
5590 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).vsyncPeriod;
5591 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value, configId,
5592 vsyncPeriod);
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005593 return NO_ERROR;
Ady Abraham838de062019-02-04 10:24:03 -08005594 }
5595
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005596 if (mDebugDisplayConfigSetByBackdoor) {
5597 // ignore this request as config is overridden by backdoor
5598 return NO_ERROR;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005599 }
5600
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005601 bool policyChanged;
5602 if (mRefreshRateConfigs->setPolicy(defaultConfig, minRefreshRate, maxRefreshRate,
5603 &policyChanged) < 0) {
5604 return BAD_VALUE;
5605 }
5606 if (!policyChanged) {
5607 return NO_ERROR;
5608 }
5609
5610 ALOGV("Setting desired display config specs: defaultConfig: %d min: %.f max: %.f",
5611 defaultConfig.value(), minRefreshRate, maxRefreshRate);
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005612
5613 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5614 // that listeners that care about a change in allowed configs can get the notification.
5615 // Giving current ActiveConfig so that most other listeners would just drop the event
Alec Mouri60aee1c2019-10-28 16:18:59 -07005616 const nsecs_t vsyncPeriod =
5617 mRefreshRateConfigs->getRefreshRateFromConfigId(display->getActiveConfig()).vsyncPeriod;
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005618 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
Alec Mouri60aee1c2019-10-28 16:18:59 -07005619 display->getActiveConfig(), vsyncPeriod);
Ady Abraham838de062019-02-04 10:24:03 -08005620
Ady Abraham2139f732019-11-13 18:56:40 -08005621 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5622 auto configId = mScheduler->getPreferredConfigId();
5623 auto preferredRefreshRate = configId
5624 ? mRefreshRateConfigs->getRefreshRateFromConfigId(*configId)
5625 : mRefreshRateConfigs->getMinRefreshRateByPolicy();
5626 ALOGV("trying to switch to Scheduler preferred config %d (%s)",
5627 preferredRefreshRate.configId.value(), preferredRefreshRate.name.c_str());
5628 if (isDisplayConfigAllowed(preferredRefreshRate.configId)) {
5629 ALOGV("switching to Scheduler preferred config %d",
5630 preferredRefreshRate.configId.value());
5631 setDesiredActiveConfig(
5632 {preferredRefreshRate.configId, Scheduler::ConfigEvent::Changed});
5633 } else {
5634 // Set the highest allowed config
5635 setDesiredActiveConfig({mRefreshRateConfigs->getMaxRefreshRateByPolicy().configId,
5636 Scheduler::ConfigEvent::Changed});
5637 }
5638 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005639 ALOGV("switching to config %d", defaultConfig.value());
5640 setDesiredActiveConfig({defaultConfig, Scheduler::ConfigEvent::Changed});
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005641 }
5642
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005643 return NO_ERROR;
5644}
5645
Ana Krulec0782b882019-10-15 17:34:54 -07005646status_t SurfaceFlinger::setDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005647 int32_t defaultConfig, float minRefreshRate,
Ana Krulec0782b882019-10-15 17:34:54 -07005648 float maxRefreshRate) {
5649 ATRACE_CALL();
5650
5651 if (!displayToken) {
5652 return BAD_VALUE;
5653 }
5654
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005655 status_t result = NO_ERROR;
5656
Ana Krulec234bb162019-11-10 22:55:55 +01005657 postMessageSync(new LambdaMessage([&]() {
5658 const auto display = getDisplayDeviceLocked(displayToken);
5659 if (!display) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005660 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005661 ALOGE("Attempt to set desired display configs for invalid display token %p",
5662 displayToken.get());
5663 } else if (display->isVirtual()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005664 result = BAD_VALUE;
Ana Krulec234bb162019-11-10 22:55:55 +01005665 ALOGW("Attempt to set desired display configs for virtual display");
5666 } else {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005667 result =
5668 setDesiredDisplayConfigSpecsInternal(display, HwcConfigIndexType(defaultConfig),
5669 minRefreshRate, maxRefreshRate);
Ana Krulec234bb162019-11-10 22:55:55 +01005670 }
5671 }));
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005672
5673 return result;
Ana Krulec234bb162019-11-10 22:55:55 +01005674}
5675
5676status_t SurfaceFlinger::getDesiredDisplayConfigSpecs(const sp<IBinder>& displayToken,
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005677 int32_t* outDefaultConfig,
Ana Krulec234bb162019-11-10 22:55:55 +01005678 float* outMinRefreshRate,
5679 float* outMaxRefreshRate) {
5680 ATRACE_CALL();
5681
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005682 if (!displayToken || !outDefaultConfig || !outMinRefreshRate || !outMaxRefreshRate) {
Ana Krulec234bb162019-11-10 22:55:55 +01005683 return BAD_VALUE;
5684 }
5685
5686 Mutex::Autolock lock(mStateLock);
5687 const auto display = getDisplayDeviceLocked(displayToken);
5688 if (!display) {
5689 return NAME_NOT_FOUND;
5690 }
5691
5692 if (display->isPrimary()) {
Ana Kruleced3a8cc2019-11-14 00:55:07 +01005693 HwcConfigIndexType defaultConfig;
5694 mRefreshRateConfigs->getPolicy(&defaultConfig, outMinRefreshRate, outMaxRefreshRate);
5695 *outDefaultConfig = defaultConfig.value();
5696 return NO_ERROR;
5697 } else if (display->isVirtual()) {
5698 return BAD_VALUE;
5699 } else {
5700 const auto displayId = display->getId();
5701 if (!displayId) {
5702 return BAD_VALUE;
5703 }
5704 *outDefaultConfig = getHwComposer().getActiveConfigIndex(*displayId);
5705 auto vsyncPeriod = getHwComposer().getActiveConfig(*displayId)->getVsyncPeriod();
5706 *outMinRefreshRate = 1e9f / vsyncPeriod;
5707 *outMaxRefreshRate = 1e9f / vsyncPeriod;
5708 return NO_ERROR;
Ana Krulec234bb162019-11-10 22:55:55 +01005709 }
Ana Krulec0782b882019-10-15 17:34:54 -07005710}
5711
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005712void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005713 mFlinger->setInputWindowsFinished();
5714}
5715
Robert Carrc0df3122019-04-11 13:18:21 -07005716sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
Valerie Hau09e60052019-12-15 14:51:15 -08005717 BBinder* b = nullptr;
5718 if (handle) {
5719 b = handle->localBinder();
5720 }
Robert Carrc0df3122019-04-11 13:18:21 -07005721 if (b == nullptr) {
5722 return nullptr;
5723 }
5724 auto it = mLayersByLocalBinderToken.find(b);
5725 if (it != mLayersByLocalBinderToken.end()) {
5726 return it->second.promote();
5727 }
5728 return nullptr;
5729}
5730
Dominik Laskowski75848362019-11-11 17:57:20 -08005731void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005732 mNumLayers++;
5733 mScheduler->registerLayer(layer);
5734}
5735
5736void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5737 mNumLayers--;
Valerie Hauc5686802019-11-22 14:18:09 -08005738 removeFromOffscreenLayers(layer);
5739}
5740
5741// WARNING: ONLY CALL THIS FROM LAYER DTOR
5742// Here we add children in the current state to offscreen layers and remove the
5743// layer itself from the offscreen layer list. Since
5744// this is the dtor, it is safe to access the current state. This keeps us
5745// from dangling children layers such that they are not reachable from the
5746// Drawing state nor the offscreen layer list
5747// See b/141111965
5748void SurfaceFlinger::removeFromOffscreenLayers(Layer* layer) {
5749 for (auto& child : layer->getCurrentChildren()) {
5750 mOffscreenLayers.emplace(child.get());
5751 }
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005752 mOffscreenLayers.erase(layer);
5753}
5754
Alec Mouri4545a8a2019-08-08 20:05:32 -07005755void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5756 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5757}
5758
Vishnu Nair08f6eae2019-11-26 14:01:39 -08005759status_t SurfaceFlinger::setGlobalShadowSettings(const half4& ambientColor, const half4& spotColor,
5760 float lightPosY, float lightPosZ,
5761 float lightRadius) {
5762 Mutex::Autolock _l(mStateLock);
5763 mCurrentState.globalShadowSettings.ambientColor = vec4(ambientColor);
5764 mCurrentState.globalShadowSettings.spotColor = vec4(spotColor);
5765 mCurrentState.globalShadowSettings.lightPos.y = lightPosY;
5766 mCurrentState.globalShadowSettings.lightPos.z = lightPosZ;
5767 mCurrentState.globalShadowSettings.lightRadius = lightRadius;
5768
5769 // these values are overridden when calculating the shadow settings for a layer.
5770 mCurrentState.globalShadowSettings.lightPos.x = 0.f;
5771 mCurrentState.globalShadowSettings.length = 0.f;
Vishnu Nairb13bb952019-11-15 10:24:08 -08005772 return NO_ERROR;
5773}
5774
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005775} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005776
Mathias Agopian3f844832013-08-07 21:24:32 -07005777#if defined(__gl_h_)
5778#error "don't include gl/gl.h in this file"
5779#endif
5780
5781#if defined(__gl2_h_)
5782#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005783#endif