blob: 7c3181e3fab8a975773c23bcc7eb2870c44c64ed [file] [log] [blame]
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2007 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Alec Mourie7d1d4a2019-02-05 01:13:46 +000017//#define LOG_NDEBUG 0
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080018#define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
Mathias Agopian921e6ac2012-07-23 23:11:29 -070020#include <sys/types.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080021#include <errno.h>
Keun young Park63f165f2012-08-31 10:53:36 -070022#include <dlfcn.h>
Dominik Laskowski83b88212018-12-11 13:34:06 -080023
24#include <algorithm>
25#include <cinttypes>
26#include <cmath>
27#include <cstdint>
28#include <functional>
29#include <mutex>
Dan Stoza2b6d38e2017-06-01 16:40:30 -070030#include <optional>
Dominik Laskowskic2867142019-01-21 11:33:38 -080031#include <unordered_map>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070032
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080033#include <cutils/properties.h>
Mark Salyzyn7823e122016-09-29 08:08:05 -070034#include <log/log.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080035
Mathias Agopianc5b2c0b2009-05-19 19:08:10 -070036#include <binder/IPCThreadState.h>
37#include <binder/IServiceManager.h>
Mathias Agopian99b49842011-06-27 16:05:52 -070038#include <binder/PermissionCache.h>
Mathias Agopian7303c6b2009-07-02 18:11:53 -070039
Lloyd Pique70d91362018-10-18 16:02:55 -070040#include <compositionengine/CompositionEngine.h>
Lloyd Piqueab039b52019-02-13 14:22:42 -080041#include <compositionengine/CompositionRefreshArgs.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070042#include <compositionengine/Display.h>
Lloyd Pique3d0c02e2018-10-19 18:38:12 -070043#include <compositionengine/DisplayColorProfile.h>
Lloyd Piquecc01a452018-12-04 17:24:00 -080044#include <compositionengine/OutputLayer.h>
Lloyd Pique31cb2942018-10-19 17:23:03 -070045#include <compositionengine/RenderSurface.h>
Lloyd Pique32cbe282018-10-19 13:09:22 -070046#include <compositionengine/impl/OutputCompositionState.h>
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -080047#include <dvr/vr_flinger.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070048#include <gui/BufferQueue.h>
Ady Abrahama3b08ef2019-07-15 18:43:10 -070049#include <gui/DebugEGLImageTracker.h>
50
Andy McFadden4803b742012-09-24 19:07:20 -070051#include <gui/GuiConfig.h>
Jamie Gennis1a4d8832012-08-02 20:11:05 -070052#include <gui/IDisplayEventConnection.h>
Alec Mouri0a9c7b82018-11-16 13:05:25 -080053#include <gui/IProducerListener.h>
Kalle Raitaa099a242017-01-11 11:17:29 -080054#include <gui/LayerDebugInfo.h>
Mathias Agopiane3c697f2013-02-14 17:11:02 -080055#include <gui/Surface.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070056#include <input/IInputFlinger.h>
Peiyong Lincbc184f2018-08-22 13:24:10 -070057#include <renderengine/RenderEngine.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070058#include <ui/ColorSpace.h>
59#include <ui/DebugUtils.h>
60#include <ui/DisplayInfo.h>
61#include <ui/DisplayStatInfo.h>
Mathias Agopian921e6ac2012-07-23 23:11:29 -070062#include <ui/GraphicBufferAllocator.h>
63#include <ui/PixelFormat.h>
Andy McFadden4803b742012-09-24 19:07:20 -070064#include <ui/UiConfig.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080065#include <utils/StopWatch.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070066#include <utils/String16.h>
67#include <utils/String8.h>
Yusuke Sato0a688f52015-07-30 23:05:39 -070068#include <utils/Timers.h>
Jamie Gennis1c8e95c2012-02-23 19:27:23 -080069#include <utils/Trace.h>
Lloyd Pique70d91362018-10-18 16:02:55 -070070#include <utils/misc.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080071
Mathias Agopian921e6ac2012-07-23 23:11:29 -070072#include <private/android_filesystem_config.h>
Mathias Agopianca088332013-03-28 17:44:13 -070073#include <private/gui/SyncFeatures.h>
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080074
Robert Carr578038f2018-03-09 12:25:24 -080075#include "BufferLayer.h"
Marissa Wallfd668622018-05-10 10:21:13 -070076#include "BufferQueueLayer.h"
Marissa Wall61c58622018-07-18 10:12:20 -070077#include "BufferStateLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020078#include "Client.h"
Robert Carr578038f2018-03-09 12:25:24 -080079#include "ColorLayer.h"
Mathias Agopian3e25fd82013-04-22 17:52:16 +020080#include "Colorizer.h"
Robert Carr578038f2018-03-09 12:25:24 -080081#include "ContainerLayer.h"
Robert Carr578038f2018-03-09 12:25:24 -080082#include "DisplayDevice.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080083#include "Layer.h"
Robert Carr1f0a16a2016-10-24 16:27:39 -070084#include "LayerVector.h"
Robert Carr1db73f62016-12-21 12:58:51 -080085#include "MonitoredProducer.h"
Lloyd Pique22098362018-09-13 11:46:49 -070086#include "NativeWindowSurface.h"
Ady Abraham03b02dd2019-03-21 15:40:11 -070087#include "RefreshRateOverlay.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070088#include "StartPropertySetThread.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080089#include "SurfaceFlinger.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -070090#include "SurfaceInterceptor.h"
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -080091
Steven Thomasb02664d2017-07-26 18:48:28 -070092#include "DisplayHardware/ComposerHal.h"
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -070093#include "DisplayHardware/DisplayIdentification.h"
Mathias Agopiana4912602012-07-12 14:25:33 -070094#include "DisplayHardware/FramebufferSurface.h"
Mathias Agopiana350ff92010-08-10 17:14:02 -070095#include "DisplayHardware/HWComposer.h"
Jesse Hall99c7dbb2013-03-14 14:29:29 -070096#include "DisplayHardware/VirtualDisplaySurface.h"
Mathias Agopianff2ed702013-09-01 21:36:12 -070097#include "Effects/Daltonizer.h"
Mikael Pessa90092f42019-08-26 17:22:04 -070098#include "FrameTracer/FrameTracer.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -070099#include "RegionSamplingThread.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700100#include "Scheduler/DispSync.h"
Ana Krulec241cf832018-08-10 15:03:23 -0700101#include "Scheduler/DispSyncSource.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700102#include "Scheduler/EventControlThread.h"
103#include "Scheduler/EventThread.h"
Lloyd Pique90c115d2018-09-18 21:39:42 -0700104#include "Scheduler/MessageQueue.h"
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700105#include "Scheduler/PhaseOffsets.h"
Ana Krulec98b5b242018-08-10 15:03:23 -0700106#include "Scheduler/Scheduler.h"
Yiwei Zhang7e666a52018-11-15 13:33:42 -0800107#include "TimeStats/TimeStats.h"
Ana Krulecfefcb582018-08-07 14:22:37 -0700108
Mathias Agopianff2ed702013-09-01 21:36:12 -0700109#include <cutils/compiler.h>
Mathias Agopian875d8e12013-06-07 15:35:48 -0700110
Dominik Laskowskib6e54372019-09-04 14:06:28 -0700111#include "android-base/parseint.h"
David Sodman7e4ae112018-02-09 15:02:28 -0800112#include "android-base/stringprintf.h"
113
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900114#include <android/hardware/configstore/1.0/ISurfaceFlingerConfigs.h>
Iris Chang7501ed62018-04-30 14:45:42 +0800115#include <android/hardware/configstore/1.1/ISurfaceFlingerConfigs.h>
116#include <android/hardware/configstore/1.1/types.h>
Ady Abraham8532d012019-05-08 14:50:56 -0700117#include <android/hardware/power/1.0/IPower.h>
Jaesoo Lee43518572017-01-23 19:03:16 +0900118#include <configstore/Utils.h>
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900119
chaviw1d044282017-09-27 12:19:28 -0700120#include <layerproto/LayerProtoParser.h>
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900121#include "SurfaceFlingerProperties.h"
chaviw1d044282017-09-27 12:19:28 -0700122
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800123namespace android {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700124
Dominik Laskowski87a07e42019-10-10 20:38:02 -0700125using namespace std::string_literals;
126
Jaesoo Lee43518572017-01-23 19:03:16 +0900127using namespace android::hardware::configstore;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900128using namespace android::hardware::configstore::V1_0;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900129using namespace android::sysprop;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -0800130
Ady Abraham8532d012019-05-08 14:50:56 -0700131using android::hardware::power::V1_0::PowerHint;
Yiwei Zhang5434a782018-12-05 18:06:32 -0800132using base::StringAppendF;
Peiyong Lin9f034472018-03-28 15:29:00 -0700133using ui::ColorMode;
Peiyong Lin34beb7a2018-03-28 11:57:12 -0700134using ui::Dataspace;
Daniel Solomon42d04562019-01-20 21:03:19 -0800135using ui::DisplayPrimaries;
Peiyong Lin62665892018-04-16 11:07:44 -0700136using ui::Hdr;
Peiyong Lin0e7a7912018-04-05 14:36:36 -0700137using ui::RenderIntent;
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900138
Steven Thomasb02664d2017-07-26 18:48:28 -0700139namespace {
Peiyong Linfca547f2018-07-09 13:03:33 -0700140
141#pragma clang diagnostic push
142#pragma clang diagnostic error "-Wswitch-enum"
143
144bool isWideColorMode(const ColorMode colorMode) {
145 switch (colorMode) {
146 case ColorMode::DISPLAY_P3:
147 case ColorMode::ADOBE_RGB:
148 case ColorMode::DCI_P3:
149 case ColorMode::BT2020:
Valerie Hau9758ae02018-10-09 16:05:09 -0700150 case ColorMode::DISPLAY_BT2020:
Peiyong Linfca547f2018-07-09 13:03:33 -0700151 case ColorMode::BT2100_PQ:
152 case ColorMode::BT2100_HLG:
153 return true;
154 case ColorMode::NATIVE:
155 case ColorMode::STANDARD_BT601_625:
156 case ColorMode::STANDARD_BT601_625_UNADJUSTED:
157 case ColorMode::STANDARD_BT601_525:
158 case ColorMode::STANDARD_BT601_525_UNADJUSTED:
159 case ColorMode::STANDARD_BT709:
160 case ColorMode::SRGB:
161 return false;
162 }
163 return false;
164}
165
Chia-I Wuc80dcbb2018-08-24 15:34:02 -0700166ui::Transform::orientation_flags fromSurfaceComposerRotation(ISurfaceComposer::Rotation rotation) {
167 switch (rotation) {
168 case ISurfaceComposer::eRotateNone:
169 return ui::Transform::ROT_0;
170 case ISurfaceComposer::eRotate90:
171 return ui::Transform::ROT_90;
172 case ISurfaceComposer::eRotate180:
173 return ui::Transform::ROT_180;
174 case ISurfaceComposer::eRotate270:
175 return ui::Transform::ROT_270;
176 }
177 ALOGE("Invalid rotation passed to captureScreen(): %d\n", rotation);
178 return ui::Transform::ROT_0;
179}
180
Peiyong Linfca547f2018-07-09 13:03:33 -0700181#pragma clang diagnostic pop
182
Steven Thomasb02664d2017-07-26 18:48:28 -0700183class ConditionalLock {
184public:
185 ConditionalLock(Mutex& mutex, bool lock) : mMutex(mutex), mLocked(lock) {
186 if (lock) {
187 mMutex.lock();
188 }
189 }
190 ~ConditionalLock() { if (mLocked) mMutex.unlock(); }
191private:
192 Mutex& mMutex;
193 bool mLocked;
194};
Peiyong Linfca547f2018-07-09 13:03:33 -0700195
Peiyong Lin9d846a52018-11-05 13:18:20 -0800196// Currently we only support V0_SRGB and DISPLAY_P3 as composition preference.
197bool validateCompositionDataspace(Dataspace dataspace) {
198 return dataspace == Dataspace::V0_SRGB || dataspace == Dataspace::DISPLAY_P3;
199}
200
Steven Thomasb02664d2017-07-26 18:48:28 -0700201} // namespace anonymous
202
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800203// ---------------------------------------------------------------------------
204
Mathias Agopian99b49842011-06-27 16:05:52 -0700205const String16 sHardwareTest("android.permission.HARDWARE_TEST");
206const String16 sAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER");
207const String16 sReadFramebuffer("android.permission.READ_FRAME_BUFFER");
208const String16 sDump("android.permission.DUMP");
209
210// ---------------------------------------------------------------------------
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700211int64_t SurfaceFlinger::dispSyncPresentTimeOffset;
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700212bool SurfaceFlinger::useHwcForRgbToYuv;
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800213uint64_t SurfaceFlinger::maxVirtualDisplaySize;
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800214bool SurfaceFlinger::hasSyncFramework;
Steven Thomas050b2c82017-03-06 11:45:16 -0800215bool SurfaceFlinger::useVrFlinger;
Fabien Sanglard1971b632017-03-10 14:50:03 -0800216int64_t SurfaceFlinger::maxFrameBufferAcquiredBuffers;
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600217bool SurfaceFlinger::hasWideColorDisplay;
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700218int SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Peiyong Lin13effd12018-07-24 17:01:47 -0700219bool SurfaceFlinger::useColorManagement;
Peiyong Linb3839ad2018-09-05 15:37:19 -0700220bool SurfaceFlinger::useContextPriority;
Peiyong Linc6780972018-10-28 15:24:08 -0700221Dataspace SurfaceFlinger::defaultCompositionDataspace = Dataspace::V0_SRGB;
222ui::PixelFormat SurfaceFlinger::defaultCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
223Dataspace SurfaceFlinger::wideColorGamutCompositionDataspace = Dataspace::V0_SRGB;
224ui::PixelFormat SurfaceFlinger::wideColorGamutCompositionPixelFormat = ui::PixelFormat::RGBA_8888;
Mathias Agopian99b49842011-06-27 16:05:52 -0700225
Kalle Raitaa099a242017-01-11 11:17:29 -0800226std::string getHwcServiceName() {
227 char value[PROPERTY_VALUE_MAX] = {};
228 property_get("debug.sf.hwc_service_name", value, "default");
229 ALOGI("Using HWComposer service: '%s'", value);
230 return std::string(value);
231}
232
233bool useTrebleTestingOverride() {
234 char value[PROPERTY_VALUE_MAX] = {};
235 property_get("debug.sf.treble_testing_override", value, "false");
236 ALOGI("Treble testing override: '%s'", value);
237 return std::string(value) == "true";
238}
239
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800240std::string decodeDisplayColorSetting(DisplayColorSetting displayColorSetting) {
241 switch(displayColorSetting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800242 case DisplayColorSetting::kManaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700243 return std::string("Managed");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800244 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -0700245 return std::string("Unmanaged");
Lloyd Pique6a3b4462019-03-07 20:58:12 -0800246 case DisplayColorSetting::kEnhanced:
Chia-I Wu0d711262018-05-21 15:19:35 -0700247 return std::string("Enhanced");
248 default:
249 return std::string("Unknown ") +
250 std::to_string(static_cast<int>(displayColorSetting));
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800251 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800252}
253
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700254SurfaceFlingerBE::SurfaceFlingerBE() : mHwcServiceName(getHwcServiceName()) {}
David Sodmanbc815282017-11-05 18:57:52 -0800255
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700256SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
257 : mFactory(factory),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700258 mInterceptor(mFactory.createSurfaceInterceptor(this)),
Yiwei Zhangf0229a72019-09-09 19:28:02 -0700259 mTimeStats(std::make_shared<impl::TimeStats>()),
Mikael Pessa90092f42019-08-26 17:22:04 -0700260 mFrameTracer(std::make_unique<FrameTracer>()),
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700261 mEventQueue(mFactory.createMessageQueue()),
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700262 mCompositionEngine(mFactory.createCompositionEngine()),
Valerie Haud251afb2019-03-29 14:19:02 -0700263 mPhaseOffsets(mFactory.createPhaseOffsets()),
264 mPendingSyncInputWindows(false) {}
Lloyd Piqueac648ee2018-01-17 13:42:24 -0800265
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700266SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
Fabien Sanglardcbf153b2017-03-10 17:57:12 -0800267 ALOGI("SurfaceFlinger is starting");
Fabien Sanglard0cc19382017-03-06 11:54:40 -0800268
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900269 hasSyncFramework = running_without_sync_framework(true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800270
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900271 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
Fabien Sanglardc45a7d92017-03-14 13:24:22 -0700272
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900273 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
Fabien Sanglarda34ed632017-03-14 11:43:52 -0700274
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900275 maxVirtualDisplaySize = max_virtual_display_dimension(0);
Fabien Sanglardc8e387e2017-03-10 10:30:28 -0800276
Steven Thomas050b2c82017-03-06 11:45:16 -0800277 // Vr flinger is only enabled on Daydream ready devices.
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900278 useVrFlinger = use_vr_flinger(false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800279
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900280 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
Fabien Sanglard1971b632017-03-10 14:50:03 -0800281
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900282 hasWideColorDisplay = has_wide_color_display(false);
Peiyong Lin0256f722018-08-31 15:45:10 -0700283
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900284 useColorManagement = use_color_management(false);
Courtney Goeltzenleuchter5d943892017-03-22 13:46:46 -0600285
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900286 mDefaultCompositionDataspace =
287 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
Peiyong Lin8cabfc32019-06-14 14:25:43 -0700288 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
289 hasWideColorDisplay ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900290 defaultCompositionDataspace = mDefaultCompositionDataspace;
291 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
292 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
293 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
294 wideColorGamutCompositionPixelFormat =
295 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
Peiyong Linb3839ad2018-09-05 15:37:19 -0700296
Yichi Chenda901bf2019-06-28 14:58:27 +0800297 mColorSpaceAgnosticDataspace =
298 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
299
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900300 useContextPriority = use_context_priority(true);
Iris Chang7501ed62018-04-30 14:45:42 +0800301
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900302 auto tmpPrimaryDisplayOrientation = primary_display_orientation(
303 SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_0);
304 switch (tmpPrimaryDisplayOrientation) {
305 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_90:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700306 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation90;
Iris Chang7501ed62018-04-30 14:45:42 +0800307 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900308 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_180:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700309 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation180;
Iris Chang7501ed62018-04-30 14:45:42 +0800310 break;
Sundong Ahnd5e08f62018-12-12 20:27:28 +0900311 case SurfaceFlingerProperties::primary_display_orientation_values::ORIENTATION_270:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700312 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientation270;
Iris Chang7501ed62018-04-30 14:45:42 +0800313 break;
314 default:
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700315 SurfaceFlinger::primaryDisplayOrientation = DisplayState::eOrientationDefault;
Iris Chang7501ed62018-04-30 14:45:42 +0800316 break;
317 }
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700318 ALOGV("Primary Display Orientation is set to %2d.", SurfaceFlinger::primaryDisplayOrientation);
Iris Chang7501ed62018-04-30 14:45:42 +0800319
Sundong Ahn85131bd2019-02-18 15:51:53 +0900320 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
Daniel Solomon42d04562019-01-20 21:03:19 -0800321
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800322 // debugging stuff...
323 char value[PROPERTY_VALUE_MAX];
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700324
Mathias Agopianb4b17302013-03-20 18:36:41 -0700325 property_get("ro.bq.gpu_to_cpu_unsupported", value, "0");
Mathias Agopian50210b92013-03-21 21:13:21 -0700326 mGpuToCpuSupported = !atoi(value);
Mathias Agopianb4b17302013-03-20 18:36:41 -0700327
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800328 property_get("debug.sf.showupdates", value, "0");
329 mDebugRegion = atoi(value);
Mathias Agopian8afb7e32011-08-15 20:44:40 -0700330
Mathias Agopianc1d359d2012-08-04 20:09:03 -0700331 ALOGI_IF(mDebugRegion, "showupdates enabled");
Orion Hodson34397da2019-02-04 09:36:10 +0000332
333 // DDMS debugging deprecated (b/120782499)
334 property_get("debug.sf.ddms", value, "0");
335 int debugDdms = atoi(value);
336 ALOGI_IF(debugDdms, "DDMS debugging not supported");
Dan Stozac5da2712016-07-20 15:38:12 -0700337
338 property_get("debug.sf.disable_backpressure", value, "0");
339 mPropagateBackpressure = !atoi(value);
340 ALOGI_IF(!mPropagateBackpressure, "Disabling backpressure propagation");
Dan Stoza8cf150a2016-08-02 10:27:31 -0700341
Ady Abrahamadb9a992019-09-19 21:21:55 +0000342 property_get("debug.sf.enable_gl_backpressure", value, "0");
343 mPropagateBackpressureClientComposition = atoi(value);
344 ALOGI_IF(mPropagateBackpressureClientComposition,
345 "Enabling backpressure propagation for Client Composition");
346
Fabien Sanglard642b23d2017-02-09 12:29:39 -0800347 property_get("debug.sf.enable_hwc_vds", value, "0");
348 mUseHwcVirtualDisplays = atoi(value);
Chia-I Wu11d10612018-06-21 15:41:13 +0800349 ALOGI_IF(mUseHwcVirtualDisplays, "Enabling HWC virtual displays");
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800350
Yiwei Zhangb770ed32018-12-17 17:44:28 -0800351 property_get("ro.sf.disable_triple_buffer", value, "0");
Fabien Sanglardc65dafa2017-02-07 14:06:39 -0800352 mLayerTripleBufferingDisabled = atoi(value);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -0800353 ALOGI_IF(mLayerTripleBufferingDisabled, "Disabling Triple Buffering");
Romain Guy3054f002017-06-05 18:38:53 -0700354
Yiwei Zhang243b3782018-05-15 17:40:04 -0700355 const size_t defaultListSize = MAX_LAYERS;
Dan Stoza0a0158c2018-03-16 13:38:54 -0700356 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
357 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
358
Dan Stozaec460082018-12-17 15:35:09 -0800359 property_get("debug.sf.luma_sampling", value, "1");
360 mLumaSampling = atoi(value);
361
Romain Guy11d63f42017-07-20 12:47:14 -0700362 // We should be reading 'persist.sys.sf.color_saturation' here
363 // but since /data may be encrypted, we need to wait until after vold
364 // comes online to attempt to read the property. The property is
365 // instead read after the boot animation
Kalle Raitaa099a242017-01-11 11:17:29 -0800366
367 if (useTrebleTestingOverride()) {
368 // Without the override SurfaceFlinger cannot connect to HIDL
369 // services that are not listed in the manifests. Considered
370 // deriving the setting from the set service name, but it
371 // would be brittle if the name that's not 'default' is used
372 // for production purposes later on.
373 setenv("TREBLE_TESTING_OVERRIDE", "true", true);
374 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800375}
376
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800377void SurfaceFlinger::onFirstRef()
378{
Lloyd Pique3fcdef12018-01-22 17:14:00 -0800379 mEventQueue->init(this);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800380}
381
Dominik Laskowski9dab3432019-03-27 13:21:10 -0700382SurfaceFlinger::~SurfaceFlinger() = default;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800383
Dan Stozac7014012014-02-14 15:03:43 -0800384void SurfaceFlinger::binderDied(const wp<IBinder>& /* who */)
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800385{
386 // the window manager died on us. prepare its eulogy.
387
Andy McFadden13a082e2012-08-24 10:16:42 -0700388 // restore initial conditions (default device unblank, etc)
389 initializeDisplays();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800390
391 // restart the boot-animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700392 startBootAnim();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -0800393}
394
Robert Carr1db73f62016-12-21 12:58:51 -0800395static sp<ISurfaceComposerClient> initClient(const sp<Client>& client) {
Mathias Agopian96f08192010-06-02 23:28:45 -0700396 status_t err = client->initCheck();
397 if (err == NO_ERROR) {
Robert Carr1db73f62016-12-21 12:58:51 -0800398 return client;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800399 }
Robert Carr1db73f62016-12-21 12:58:51 -0800400 return nullptr;
401}
402
403sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() {
404 return initClient(new Client(this));
405}
406
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700407sp<IBinder> SurfaceFlinger::createDisplay(const String8& displayName,
408 bool secure)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700409{
410 class DisplayToken : public BBinder {
411 sp<SurfaceFlinger> flinger;
412 virtual ~DisplayToken() {
413 // no more references, this display must be terminated
414 Mutex::Autolock _l(flinger->mStateLock);
415 flinger->mCurrentState.displays.removeItem(this);
416 flinger->setTransactionFlags(eDisplayTransactionNeeded);
417 }
418 public:
Chih-Hung Hsiehc4067912016-05-03 14:03:27 -0700419 explicit DisplayToken(const sp<SurfaceFlinger>& flinger)
Mathias Agopiane57f2922012-08-09 16:29:12 -0700420 : flinger(flinger) {
421 }
422 };
423
424 sp<BBinder> token = new DisplayToken(this);
425
426 Mutex::Autolock _l(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700427 // Display ID is assigned when virtual display is allocated by HWC.
428 DisplayDeviceState state;
429 state.isSecure = secure;
430 state.displayName = displayName;
431 mCurrentState.displays.add(token, state);
432 mInterceptor->saveDisplayCreation(state);
Mathias Agopiane57f2922012-08-09 16:29:12 -0700433 return token;
434}
435
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700436void SurfaceFlinger::destroyDisplay(const sp<IBinder>& displayToken) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700437 Mutex::Autolock _l(mStateLock);
438
Dominik Laskowski075d3172018-05-24 15:50:06 -0700439 ssize_t index = mCurrentState.displays.indexOfKey(displayToken);
440 if (index < 0) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700441 ALOGE("destroyDisplay: Invalid display token %p", displayToken.get());
Jesse Hall6c913be2013-08-08 12:15:49 -0700442 return;
443 }
444
Dominik Laskowski075d3172018-05-24 15:50:06 -0700445 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
446 if (!state.isVirtual()) {
Jesse Hall6c913be2013-08-08 12:15:49 -0700447 ALOGE("destroyDisplay called for non-virtual display");
448 return;
449 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700450 mInterceptor->saveDisplayDeletion(state.sequenceId);
451 mCurrentState.displays.removeItemsAt(index);
Jesse Hall6c913be2013-08-08 12:15:49 -0700452 setTransactionFlags(eDisplayTransactionNeeded);
453}
454
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800455std::vector<PhysicalDisplayId> SurfaceFlinger::getPhysicalDisplayIds() const {
456 Mutex::Autolock lock(mStateLock);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700457
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800458 const auto internalDisplayId = getInternalDisplayIdLocked();
459 if (!internalDisplayId) {
460 return {};
Dominik Laskowski075d3172018-05-24 15:50:06 -0700461 }
462
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800463 std::vector<PhysicalDisplayId> displayIds;
464 displayIds.reserve(mPhysicalDisplayTokens.size());
465 displayIds.push_back(internalDisplayId->value);
466
467 for (const auto& [id, token] : mPhysicalDisplayTokens) {
468 if (id != *internalDisplayId) {
469 displayIds.push_back(id.value);
470 }
Mathias Agopiane57f2922012-08-09 16:29:12 -0700471 }
Dominik Laskowski075d3172018-05-24 15:50:06 -0700472
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800473 return displayIds;
474}
475
476sp<IBinder> SurfaceFlinger::getPhysicalDisplayToken(PhysicalDisplayId displayId) const {
477 Mutex::Autolock lock(mStateLock);
478 return getPhysicalDisplayTokenLocked(DisplayId{displayId});
Mathias Agopiane57f2922012-08-09 16:29:12 -0700479}
480
Ady Abraham37965d42018-11-01 13:43:32 -0700481status_t SurfaceFlinger::getColorManagement(bool* outGetColorManagement) const {
482 if (!outGetColorManagement) {
483 return BAD_VALUE;
484 }
485 *outGetColorManagement = useColorManagement;
486 return NO_ERROR;
Ady Abraham2a6ab2a2018-10-26 14:25:30 -0700487}
488
Lloyd Pique441d5042018-10-18 16:49:51 -0700489HWComposer& SurfaceFlinger::getHwComposer() const {
490 return mCompositionEngine->getHwComposer();
491}
492
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700493renderengine::RenderEngine& SurfaceFlinger::getRenderEngine() const {
494 return mCompositionEngine->getRenderEngine();
495}
496
Lloyd Pique70d91362018-10-18 16:02:55 -0700497compositionengine::CompositionEngine& SurfaceFlinger::getCompositionEngine() const {
498 return *mCompositionEngine.get();
499}
500
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800501void SurfaceFlinger::bootFinished()
502{
Wei Wangf9b05ee2017-07-19 20:59:39 -0700503 if (mStartPropertySetThread->join() != NO_ERROR) {
504 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800505 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800506 const nsecs_t now = systemTime();
507 const nsecs_t duration = now - mBootTime;
Steve Blocka19954a2012-01-04 20:05:49 +0000508 ALOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700509
Mikael Pessa90092f42019-08-26 17:22:04 -0700510 mFrameTracer->initialize();
Mikael Pessa2e1608f2019-07-19 11:25:35 -0700511
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700512 // wait patiently for the window manager death
513 const String16 name("window");
Steven Morelanda904bb92019-07-02 17:37:23 -0700514 mWindowManager = defaultServiceManager()->getService(name);
515 if (mWindowManager != 0) {
516 mWindowManager->linkToDeath(static_cast<IBinder::DeathRecipient*>(this));
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700517 }
Robert Carr720e5062018-07-30 17:45:14 -0700518 sp<IBinder> input(defaultServiceManager()->getService(
519 String16("inputflinger")));
520 if (input == nullptr) {
521 ALOGE("Failed to link to input service");
522 } else {
523 mInputFlinger = interface_cast<IInputFlinger>(input);
524 }
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700525
Steven Thomas050b2c82017-03-06 11:45:16 -0800526 if (mVrFlinger) {
527 mVrFlinger->OnBootFinished();
528 }
529
Mathias Agopian1f339ff2011-07-01 17:08:43 -0700530 // stop boot animation
Mathias Agopiana67e4182012-06-19 17:26:12 -0700531 // formerly we would just kill the process, but we now ask it to exit so it
532 // can choose where to stop the animation.
533 property_set("service.bootanim.exit", "1");
Yusuke Sato0a688f52015-07-30 23:05:39 -0700534
535 const int LOGTAG_SF_STOP_BOOTANIM = 60110;
536 LOG_EVENT_LONG(LOGTAG_SF_STOP_BOOTANIM,
537 ns2ms(systemTime(SYSTEM_TIME_MONOTONIC)));
Romain Guy11d63f42017-07-20 12:47:14 -0700538
Ana Krulecbd6654b2019-02-15 15:18:15 -0800539 postMessageAsync(new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS {
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800540 readPersistentProperties();
541 mBootStage = BootStage::FINISHED;
Ana Krulecbd6654b2019-02-15 15:18:15 -0800542
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700543 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
544 // set the refresh rate according to the policy
545 const auto& performanceRefreshRate =
546 mRefreshRateConfigs->getRefreshRateFromType(RefreshRateType::PERFORMANCE);
Ady Abraham97d04232019-03-05 19:48:12 -0800547
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700548 if (isDisplayConfigAllowed(performanceRefreshRate.configId)) {
549 setRefreshRateTo(RefreshRateType::PERFORMANCE, Scheduler::ConfigEvent::None);
550 } else {
551 setRefreshRateTo(RefreshRateType::DEFAULT, Scheduler::ConfigEvent::None);
552 }
Ana Krulecbd6654b2019-02-15 15:18:15 -0800553 }
Chia-I Wu14c9c7b2018-06-26 10:18:18 +0800554 }));
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800555}
556
Dan Stoza436ccf32018-06-21 12:10:12 -0700557uint32_t SurfaceFlinger::getNewTexture() {
558 {
559 std::lock_guard lock(mTexturePoolMutex);
560 if (!mTexturePool.empty()) {
561 uint32_t name = mTexturePool.back();
562 mTexturePool.pop_back();
563 ATRACE_INT("TexturePoolSize", mTexturePool.size());
564 return name;
565 }
566
567 // The pool was too small, so increase it for the future
568 ++mTexturePoolSize;
569 }
570
571 // The pool was empty, so we need to get a new texture name directly using a
572 // blocking call to the main thread
573 uint32_t name = 0;
574 postMessageSync(new LambdaMessage([&]() { getRenderEngine().genTextures(1, &name); }));
575 return name;
576}
577
Mathias Agopian3f844832013-08-07 21:24:32 -0700578void SurfaceFlinger::deleteTextureAsync(uint32_t texture) {
Dan Stoza67765d82019-05-07 14:58:27 -0700579 std::lock_guard lock(mTexturePoolMutex);
580 // We don't change the pool size, so the fix-up logic in postComposition will decide whether
581 // to actually delete this or not based on mTexturePoolSize
582 mTexturePool.push_back(texture);
583 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Mathias Agopian921e6ac2012-07-23 23:11:29 -0700584}
585
Wei Wangf9b05ee2017-07-19 20:59:39 -0700586// Do not call property_set on main thread which will be blocked by init
587// Use StartPropertySetThread instead.
Jamie Gennisfaf77cc2013-07-30 15:10:32 -0700588void SurfaceFlinger::init() {
Mathias Agopiana4912602012-07-12 14:25:33 -0700589 ALOGI( "SurfaceFlinger's main thread ready to run. "
590 "Initializing graphics H/W...");
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700591 ALOGI("Phase offset: %" PRId64 " ns", mPhaseOffsets->getCurrentAppOffset());
Jiyong Park4b20c2e2017-01-14 19:45:11 +0900592
Steven Thomasb02664d2017-07-26 18:48:28 -0700593 Mutex::Autolock _l(mStateLock);
Kevin DuBois413287f2019-02-25 08:46:47 -0800594
Steven Thomasb02664d2017-07-26 18:48:28 -0700595 // Get a RenderEngine for the given display / config (can't fail)
Peiyong Lin0256f722018-08-31 15:45:10 -0700596 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
Alec Mourida4cf3b2019-02-12 15:33:01 -0800597 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
Peiyong Lin4137a1d2019-10-09 10:39:09 -0700598 mCompositionEngine->setRenderEngine(renderengine::RenderEngine::create(
599 renderengine::RenderEngineCreationArgs::Builder()
600 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
601 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
602 .setUseColorManagerment(useColorManagement)
603 .setEnableProtectedContext(enable_protected_contents(false))
604 .setPrecacheToneMapperShaderOnly(false)
605 .setContextPriority(useContextPriority
606 ? renderengine::RenderEngine::ContextPriority::HIGH
607 : renderengine::RenderEngine::ContextPriority::MEDIUM)
608 .build()));
Alec Mourie4034bb2019-11-19 12:45:54 -0800609 mCompositionEngine->setTimeStats(mTimeStats);
Steven Thomasb02664d2017-07-26 18:48:28 -0700610
611 LOG_ALWAYS_FATAL_IF(mVrFlingerRequestsDisplay,
612 "Starting with vr flinger active is not currently supported.");
Lloyd Pique441d5042018-10-18 16:49:51 -0700613 mCompositionEngine->setHwComposer(getFactory().createHWComposer(getBE().mHwcServiceName));
614 mCompositionEngine->getHwComposer().registerCallback(this, getBE().mComposerSequenceId);
Lloyd Piqueba04e622017-12-14 17:11:26 -0800615 // Process any initial hotplug and resulting display changes.
616 processDisplayHotplugEventsLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700617 const auto display = getDefaultDisplayDeviceLocked();
618 LOG_ALWAYS_FATAL_IF(!display, "Missing internal display after registering composer callback.");
Dominik Laskowski075d3172018-05-24 15:50:06 -0700619 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(*display->getId()),
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700620 "Internal display is disconnected.");
Jesse Hall692c7232012-11-08 15:41:56 -0800621
Steven Thomas050b2c82017-03-06 11:45:16 -0800622 if (useVrFlinger) {
Dominik Laskowski8c001672018-05-30 16:52:06 -0700623 auto vrFlingerRequestDisplayCallback = [this](bool requestDisplay) {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700624 // This callback is called from the vr flinger dispatch thread. We
625 // need to call signalTransaction(), which requires holding
626 // mStateLock when we're not on the main thread. Acquiring
627 // mStateLock from the vr flinger dispatch thread might trigger a
628 // deadlock in surface flinger (see b/66916578), so post a message
629 // to be handled on the main thread instead.
Dominik Laskowski8c001672018-05-30 16:52:06 -0700630 postMessageAsync(new LambdaMessage([=] {
Steven Thomasbe6cbae2017-09-28 15:30:23 -0700631 ALOGI("VR request display mode: requestDisplay=%d", requestDisplay);
632 mVrFlingerRequestsDisplay = requestDisplay;
633 signalTransaction();
Dominik Laskowski8c001672018-05-30 16:52:06 -0700634 }));
Steven Thomas050b2c82017-03-06 11:45:16 -0800635 };
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700636 mVrFlinger = dvr::VrFlinger::Create(getHwComposer().getComposer(),
637 getHwComposer()
Dominik Laskowski075d3172018-05-24 15:50:06 -0700638 .fromPhysicalDisplayId(*display->getId())
Dominik Laskowski45de9bd2018-06-11 17:44:10 -0700639 .value_or(0),
640 vrFlingerRequestDisplayCallback);
Steven Thomas050b2c82017-03-06 11:45:16 -0800641 if (!mVrFlinger) {
642 ALOGE("Failed to start vrflinger");
643 }
644 }
645
Mathias Agopian92a979a2012-08-02 18:32:23 -0700646 // initialize our drawing state
647 mDrawingState = mCurrentState;
Mathias Agopian86303202012-07-24 22:46:10 -0700648
Andy McFadden13a082e2012-08-24 10:16:42 -0700649 // set initial conditions (e.g. unblank default device)
650 initializeDisplays();
651
Steven Thomas137d4bc2019-07-25 16:55:14 -0700652 char primeShaderCache[PROPERTY_VALUE_MAX];
653 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
654 if (atoi(primeShaderCache)) {
655 getRenderEngine().primeCache();
656 }
Dan Stoza4e637772016-07-28 13:31:51 -0700657
Wei Wangf9b05ee2017-07-19 20:59:39 -0700658 // Inform native graphics APIs whether the present timestamp is supported:
Lloyd Pique90c115d2018-09-18 21:39:42 -0700659
660 const bool presentFenceReliable =
661 !getHwComposer().hasCapability(HWC2::Capability::PresentFenceIsNotReliable);
662 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
Wei Wangf9b05ee2017-07-19 20:59:39 -0700663
664 if (mStartPropertySetThread->Start() != NO_ERROR) {
665 ALOGE("Run StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800666 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800667
Dan Stoza9e56aa02015-11-02 13:00:03 -0800668 ALOGV("Done initializing");
Mathias Agopian3ee454a2012-08-27 16:28:24 -0700669}
670
Romain Guy11d63f42017-07-20 12:47:14 -0700671void SurfaceFlinger::readPersistentProperties() {
Chia-I Wu28f320b2018-05-03 11:02:56 -0700672 Mutex::Autolock _l(mStateLock);
673
Romain Guy11d63f42017-07-20 12:47:14 -0700674 char value[PROPERTY_VALUE_MAX];
675
676 property_get("persist.sys.sf.color_saturation", value, "1.0");
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800677 mGlobalSaturationFactor = atof(value);
Chia-I Wu28f320b2018-05-03 11:02:56 -0700678 updateColorMatrixLocked();
Peiyong Lindd9b2ae2018-03-01 16:22:45 -0800679 ALOGV("Saturation is set to %.2f", mGlobalSaturationFactor);
Romain Guy54f154a2017-10-24 21:40:32 +0100680
681 property_get("persist.sys.sf.native_mode", value, "0");
Chia-I Wu0d711262018-05-21 15:19:35 -0700682 mDisplayColorSetting = static_cast<DisplayColorSetting>(atoi(value));
Peiyong Lina3ea5592019-02-10 14:45:00 -0800683
684 property_get("persist.sys.sf.color_mode", value, "0");
685 mForceColorMode = static_cast<ColorMode>(atoi(value));
Romain Guy11d63f42017-07-20 12:47:14 -0700686}
687
Mathias Agopiana67e4182012-06-19 17:26:12 -0700688void SurfaceFlinger::startBootAnim() {
Wei Wangb254fa32017-01-31 17:43:23 -0800689 // Start boot animation service by setting a property mailbox
690 // if property setting thread is already running, Start() will be just a NOP
Wei Wangf9b05ee2017-07-19 20:59:39 -0700691 mStartPropertySetThread->Start();
Wei Wangb254fa32017-01-31 17:43:23 -0800692 // Wait until property was set
Wei Wangf9b05ee2017-07-19 20:59:39 -0700693 if (mStartPropertySetThread->join() != NO_ERROR) {
694 ALOGE("Join StartPropertySetThread failed!");
Wei Wangb254fa32017-01-31 17:43:23 -0800695 }
Mathias Agopiana67e4182012-06-19 17:26:12 -0700696}
697
Mathias Agopian875d8e12013-06-07 15:35:48 -0700698size_t SurfaceFlinger::getMaxTextureSize() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700699 return getRenderEngine().getMaxTextureSize();
Mathias Agopiana4912602012-07-12 14:25:33 -0700700}
701
Mathias Agopian875d8e12013-06-07 15:35:48 -0700702size_t SurfaceFlinger::getMaxViewportDims() const {
Lloyd Piqueb97e04f2018-10-18 17:07:05 -0700703 return getRenderEngine().getMaxViewportDims();
Mathias Agopiana4912602012-07-12 14:25:33 -0700704}
705
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -0800706// ----------------------------------------------------------------------------
Mathias Agopiand0566bc2011-11-17 17:49:17 -0800707
Jamie Gennis582270d2011-08-17 18:19:00 -0700708bool SurfaceFlinger::authenticateSurfaceTexture(
Andy McFadden2adaf042012-12-18 09:49:45 -0800709 const sp<IGraphicBufferProducer>& bufferProducer) const {
Jamie Gennis134f0422011-03-08 12:18:54 -0800710 Mutex::Autolock _l(mStateLock);
Robert Carr0d480722017-01-10 16:42:54 -0800711 return authenticateSurfaceTextureLocked(bufferProducer);
712}
713
714bool SurfaceFlinger::authenticateSurfaceTextureLocked(
715 const sp<IGraphicBufferProducer>& bufferProducer) const {
Marco Nelissen097ca272014-11-14 08:01:01 -0800716 sp<IBinder> surfaceTextureBinder(IInterface::asBinder(bufferProducer));
Dan Stoza101d8dc2018-02-27 15:42:25 -0800717 return mGraphicBufferProducerList.count(surfaceTextureBinder.get()) > 0;
Jamie Gennis134f0422011-03-08 12:18:54 -0800718}
719
Brian Anderson6b376712017-04-04 10:51:39 -0700720status_t SurfaceFlinger::getSupportedFrameTimestamps(
721 std::vector<FrameEvent>* outSupported) const {
722 *outSupported = {
723 FrameEvent::REQUESTED_PRESENT,
724 FrameEvent::ACQUIRE,
725 FrameEvent::LATCH,
726 FrameEvent::FIRST_REFRESH_START,
727 FrameEvent::LAST_REFRESH_START,
728 FrameEvent::GPU_COMPOSITION_DONE,
729 FrameEvent::DEQUEUE_READY,
730 FrameEvent::RELEASE,
731 };
Steven Thomas6d8110b2017-08-31 18:24:21 -0700732 ConditionalLock _l(mStateLock,
733 std::this_thread::get_id() != mMainThreadId);
Brian Anderson6b376712017-04-04 10:51:39 -0700734 if (!getHwComposer().hasCapability(
735 HWC2::Capability::PresentFenceIsNotReliable)) {
736 outSupported->push_back(FrameEvent::DISPLAY_PRESENT);
737 }
738 return NO_ERROR;
739}
740
Dominik Laskowski22488f62019-03-28 09:53:04 -0700741status_t SurfaceFlinger::getDisplayConfigs(const sp<IBinder>& displayToken,
742 Vector<DisplayInfo>* configs) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700743 if (!displayToken || !configs) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700744 return BAD_VALUE;
745 }
746
Dominik Laskowski22488f62019-03-28 09:53:04 -0700747 Mutex::Autolock lock(mStateLock);
748
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800749 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
Dominik Laskowski075d3172018-05-24 15:50:06 -0700750 if (!displayId) {
751 return NAME_NOT_FOUND;
Mathias Agopianc666cae2012-07-25 18:56:13 -0700752 }
Mathias Agopian8b736f12012-08-13 17:54:26 -0700753
Mathias Agopian8b736f12012-08-13 17:54:26 -0700754 // TODO: Not sure if display density should handled by SF any longer
755 class Density {
Hernan Liatis57568932018-08-16 17:07:08 -0700756 static float getDensityFromProperty(char const* propName) {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700757 char property[PROPERTY_VALUE_MAX];
Hernan Liatis57568932018-08-16 17:07:08 -0700758 float density = 0.0f;
Peiyong Lin566a3b42018-01-09 18:22:43 -0800759 if (property_get(propName, property, nullptr) > 0) {
Hernan Liatis57568932018-08-16 17:07:08 -0700760 density = strtof(property, nullptr);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700761 }
762 return density;
763 }
764 public:
Hernan Liatis57568932018-08-16 17:07:08 -0700765 static float getEmuDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700766 return getDensityFromProperty("qemu.sf.lcd_density"); }
Hernan Liatis57568932018-08-16 17:07:08 -0700767 static float getBuildDensity() {
Mathias Agopian8b736f12012-08-13 17:54:26 -0700768 return getDensityFromProperty("ro.sf.lcd_density"); }
769 };
Mathias Agopian1604f772012-09-18 21:54:42 -0700770
Dan Stoza7f7da322014-05-02 15:26:25 -0700771 configs->clear();
Mathias Agopian1604f772012-09-18 21:54:42 -0700772
Dominik Laskowski075d3172018-05-24 15:50:06 -0700773 for (const auto& hwConfig : getHwComposer().getConfigs(*displayId)) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700774 DisplayInfo info = DisplayInfo();
775
Dan Stoza9e56aa02015-11-02 13:00:03 -0800776 float xdpi = hwConfig->getDpiX();
777 float ydpi = hwConfig->getDpiY();
Dan Stoza7f7da322014-05-02 15:26:25 -0700778
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700779 info.w = hwConfig->getWidth();
780 info.h = hwConfig->getHeight();
781 // Default display viewport to display width and height
782 info.viewportW = info.w;
783 info.viewportH = info.h;
784
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800785 if (displayId == getInternalDisplayIdLocked()) {
Dan Stoza7f7da322014-05-02 15:26:25 -0700786 // The density of the device is provided by a build property
787 float density = Density::getBuildDensity() / 160.0f;
788 if (density == 0) {
789 // the build doesn't provide a density -- this is wrong!
790 // use xdpi instead
791 ALOGE("ro.sf.lcd_density must be defined as a build property");
792 density = xdpi / 160.0f;
793 }
794 if (Density::getEmuDensity()) {
795 // if "qemu.sf.lcd_density" is specified, it overrides everything
796 xdpi = ydpi = density = Density::getEmuDensity();
797 density /= 160.0f;
798 }
799 info.density = density;
800
801 // TODO: this needs to go away (currently needed only by webkit)
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700802 const auto display = getDefaultDisplayDeviceLocked();
803 info.orientation = display ? display->getOrientation() : 0;
Yiwei Zhang27de5df2018-08-23 17:04:51 -0700804
805 // This is for screenrecord
806 const Rect viewport = display->getViewport();
807 if (viewport.isValid()) {
808 info.viewportW = uint32_t(viewport.getWidth());
809 info.viewportH = uint32_t(viewport.getHeight());
810 }
Huihong Luod6f1fc22019-09-10 14:29:20 -0700811 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700812 } else {
813 // TODO: where should this value come from?
814 static const int TV_DENSITY = 213;
815 info.density = TV_DENSITY / 160.0f;
816 info.orientation = 0;
Huihong Luod6f1fc22019-09-10 14:29:20 -0700817
818 const auto display = getDisplayDeviceLocked(displayToken);
819 info.layerStack = display->getLayerStack();
Dan Stoza7f7da322014-05-02 15:26:25 -0700820 }
821
Dan Stoza7f7da322014-05-02 15:26:25 -0700822 info.xdpi = xdpi;
823 info.ydpi = ydpi;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800824 info.fps = 1e9 / hwConfig->getVsyncPeriod();
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700825 const auto refreshRateType =
826 mRefreshRateConfigs->getRefreshRateTypeFromHwcConfigId(hwConfig->getId());
Ady Abraham796beb02019-04-11 15:23:07 -0700827 const auto offset = mPhaseOffsets->getOffsetsForRefreshRate(refreshRateType);
828 info.appVsyncOffset = offset.late.app;
Dan Stoza9e56aa02015-11-02 13:00:03 -0800829
Andy McFadden91b2ca82014-06-13 14:04:23 -0700830 // This is how far in advance a buffer must be queued for
831 // presentation at a given time. If you want a buffer to appear
832 // on the screen at time N, you must submit the buffer before
833 // (N - presentationDeadline).
834 //
835 // Normally it's one full refresh period (to give SF a chance to
836 // latch the buffer), but this can be reduced by configuring a
837 // DispSync offset. Any additional delays introduced by the hardware
838 // composer or panel must be accounted for here.
839 //
840 // We add an additional 1ms to allow for processing time and
841 // differences between the ideal and actual refresh rate.
Ady Abraham796beb02019-04-11 15:23:07 -0700842 info.presentationDeadline = hwConfig->getVsyncPeriod() - offset.late.sf + 1000000;
Dan Stoza7f7da322014-05-02 15:26:25 -0700843
844 // All non-virtual displays are currently considered secure.
845 info.secure = true;
846
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -0800847 if (displayId == getInternalDisplayIdLocked() &&
Chia-I Wu304d9cd2018-08-27 14:38:14 -0700848 primaryDisplayOrientation & DisplayState::eOrientationSwapMask) {
Iris Chang7501ed62018-04-30 14:45:42 +0800849 std::swap(info.w, info.h);
850 }
851
Michael Wright28f24d02016-07-12 13:30:53 -0700852 configs->push_back(info);
Mathias Agopian8b736f12012-08-13 17:54:26 -0700853 }
854
Dan Stoza7f7da322014-05-02 15:26:25 -0700855 return NO_ERROR;
856}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700857
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700858status_t SurfaceFlinger::getDisplayStats(const sp<IBinder>&, DisplayStatInfo* stats) {
859 if (!stats) {
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700860 return BAD_VALUE;
861 }
862
Ana Krulecc2870422019-01-29 19:00:58 -0800863 mScheduler->getDisplayStatInfo(stats);
Lajos Molnar67d8bd62014-09-11 14:58:45 -0700864 return NO_ERROR;
865}
866
Dominik Laskowskieecd6592018-05-29 10:25:41 -0700867int SurfaceFlinger::getActiveConfig(const sp<IBinder>& displayToken) {
868 const auto display = getDisplayDevice(displayToken);
869 if (!display) {
870 ALOGE("getActiveConfig: Invalid display token %p", displayToken.get());
Jinguang Dong9f8b9ae2016-11-29 13:55:57 +0800871 return BAD_VALUE;
872 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -0700873
Steven Thomasc9098452019-09-30 17:15:05 -0700874 if (display->isPrimary()) {
875 std::lock_guard<std::mutex> lock(mActiveConfigLock);
876 if (mDesiredActiveConfigChanged) {
877 return mDesiredActiveConfig.configId;
878 } else {
879 return display->getActiveConfig();
880 }
881 } else {
882 return display->getActiveConfig();
883 }
Dan Stoza7f7da322014-05-02 15:26:25 -0700884}
Jamie Gennisdd3cb842012-10-19 18:19:11 -0700885
Ady Abraham03b02dd2019-03-21 15:40:11 -0700886void SurfaceFlinger::setDesiredActiveConfig(const ActiveConfigInfo& info) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800887 ATRACE_CALL();
Ana Krulec7d1d6832018-12-27 11:10:09 -0800888
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800889 // Don't check against the current mode yet. Worst case we set the desired
Ady Abraham9360a222019-02-27 17:05:30 -0800890 // config twice. However event generation config might have changed so we need to update it
891 // accordingly
Ady Abrahamb838aed2019-02-12 15:30:16 -0800892 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Ady Abraham03b02dd2019-03-21 15:40:11 -0700893 const Scheduler::ConfigEvent prevConfig = mDesiredActiveConfig.event;
894 mDesiredActiveConfig = info;
895 mDesiredActiveConfig.event = mDesiredActiveConfig.event | prevConfig;
Ady Abrahamb838aed2019-02-12 15:30:16 -0800896
897 if (!mDesiredActiveConfigChanged) {
Ady Abrahamb838aed2019-02-12 15:30:16 -0800898 // This will trigger HWC refresh without resetting the idle timer.
899 repaintEverythingForHWC();
Alec Mouri754c98a2019-03-18 18:53:42 -0700900 // Start receiving vsync samples now, so that we can detect a period
901 // switch.
902 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Ady Abraham53852a52019-05-28 18:07:44 -0700903 // As we called to set period, we will call to onRefreshRateChangeCompleted once
904 // DispSync model is locked.
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700905 mVSyncModulator->onRefreshRateChangeInitiated();
Alec Mouri754c98a2019-03-18 18:53:42 -0700906 mPhaseOffsets->setRefreshRateType(info.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700907 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800908 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800909 mDesiredActiveConfigChanged = true;
Ady Abraham03b02dd2019-03-21 15:40:11 -0700910
911 if (mRefreshRateOverlay) {
912 mRefreshRateOverlay->changeRefreshRate(mDesiredActiveConfig.type);
913 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800914}
915
916status_t SurfaceFlinger::setActiveConfig(const sp<IBinder>& displayToken, int mode) {
917 ATRACE_CALL();
Ady Abraham838de062019-02-04 10:24:03 -0800918
919 std::vector<int32_t> allowedConfig;
920 allowedConfig.push_back(mode);
921
922 return setAllowedDisplayConfigs(displayToken, allowedConfig);
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800923}
924
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800925void SurfaceFlinger::setActiveConfigInternal() {
926 ATRACE_CALL();
927
Dominik Laskowski22488f62019-03-28 09:53:04 -0700928 const auto display = getDefaultDisplayDeviceLocked();
929 if (!display) {
930 return;
931 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800932
Dominik Laskowski22488f62019-03-28 09:53:04 -0700933 std::lock_guard<std::mutex> lock(mActiveConfigLock);
Steven Thomas2bbaabe2019-08-28 16:08:35 -0700934 mRefreshRateConfigs->setCurrentConfig(mUpcomingActiveConfig.configId);
935 mRefreshRateStats->setConfigMode(mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700936
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800937 display->setActiveConfig(mUpcomingActiveConfig.configId);
938
Alec Mouri754c98a2019-03-18 18:53:42 -0700939 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700940 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800941 ATRACE_INT("ActiveConfigMode", mUpcomingActiveConfig.configId);
Dominik Laskowski22488f62019-03-28 09:53:04 -0700942
Ana Krulec8d3e4f32019-03-05 10:40:33 -0800943 if (mUpcomingActiveConfig.event != Scheduler::ConfigEvent::None) {
Ady Abraham447052e2019-02-13 16:07:27 -0800944 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
945 mUpcomingActiveConfig.configId);
946 }
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800947}
948
Ady Abraham53852a52019-05-28 18:07:44 -0700949void SurfaceFlinger::desiredActiveConfigChangeDone() {
950 std::lock_guard<std::mutex> lock(mActiveConfigLock);
951 mDesiredActiveConfig.event = Scheduler::ConfigEvent::None;
952 mDesiredActiveConfigChanged = false;
Ady Abraham53852a52019-05-28 18:07:44 -0700953
954 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
955 mPhaseOffsets->setRefreshRateType(mUpcomingActiveConfig.type);
Dominik Laskowskieddeda12019-07-19 11:54:13 -0700956 mVSyncModulator->setPhaseOffsets(mPhaseOffsets->getCurrentOffsets());
Ady Abraham53852a52019-05-28 18:07:44 -0700957}
958
Dominik Laskowski22488f62019-03-28 09:53:04 -0700959bool SurfaceFlinger::performSetActiveConfig() {
Alec Mourife3dc942019-02-12 14:19:18 -0800960 ATRACE_CALL();
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
Dominik Laskowski22488f62019-03-28 09:53:04 -0700984 const auto display = getDefaultDisplayDeviceLocked();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800985 if (!display || display->getActiveConfig() == desiredActiveConfig.configId) {
986 // display is not valid or we are already in the requested mode
987 // on both cases there is nothing left to do
Ady Abraham53852a52019-05-28 18:07:44 -0700988 desiredActiveConfigChangeDone();
Ady Abrahamb838aed2019-02-12 15:30:16 -0800989 return false;
Ana Kruleca5bdd9d2019-01-29 19:00:58 -0800990 }
Ady Abrahamb838aed2019-02-12 15:30:16 -0800991
Ady Abraham838de062019-02-04 10:24:03 -0800992 // Desired active config was set, it is different than the config currently in use, however
993 // allowed configs might have change by the time we process the refresh.
994 // Make sure the desired config is still allowed
Dominik Laskowski22488f62019-03-28 09:53:04 -0700995 if (!isDisplayConfigAllowed(desiredActiveConfig.configId)) {
Ady Abraham53852a52019-05-28 18:07:44 -0700996 desiredActiveConfigChangeDone();
Ady Abraham838de062019-02-04 10:24:03 -0800997 return false;
998 }
Alec Mouri7f015182019-07-11 13:56:22 -0700999
Ady Abrahamb838aed2019-02-12 15:30:16 -08001000 mUpcomingActiveConfig = desiredActiveConfig;
1001 const auto displayId = display->getId();
1002 LOG_ALWAYS_FATAL_IF(!displayId);
1003
1004 ATRACE_INT("ActiveConfigModeHWC", mUpcomingActiveConfig.configId);
1005 getHwComposer().setActiveConfig(*displayId, mUpcomingActiveConfig.configId);
1006
1007 // we need to submit an empty frame to HWC to start the process
Ady Abrahamb838aed2019-02-12 15:30:16 -08001008 mCheckPendingFence = true;
Ady Abraham8532d012019-05-08 14:50:56 -07001009 mEventQueue->invalidate();
Ady Abrahamb838aed2019-02-12 15:30:16 -08001010 return false;
Mathias Agopianc666cae2012-07-25 18:56:13 -07001011}
Dominik Laskowski075d3172018-05-24 15:50:06 -07001012
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001013status_t SurfaceFlinger::getDisplayColorModes(const sp<IBinder>& displayToken,
1014 Vector<ColorMode>* outColorModes) {
1015 if (!displayToken || !outColorModes) {
Michael Wright28f24d02016-07-12 13:30:53 -07001016 return BAD_VALUE;
1017 }
1018
Peiyong Lina52f0292018-03-14 17:26:31 -07001019 std::vector<ColorMode> modes;
Peiyong Linff84a152019-05-17 18:36:19 -07001020 bool isInternalDisplay = false;
Steven Thomas6d8110b2017-08-31 18:24:21 -07001021 {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001022 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
1023
1024 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1025 if (!displayId) {
1026 return NAME_NOT_FOUND;
1027 }
1028
Dominik Laskowski075d3172018-05-24 15:50:06 -07001029 modes = getHwComposer().getColorModes(*displayId);
Peiyong Linff84a152019-05-17 18:36:19 -07001030 isInternalDisplay = displayId == getInternalDisplayIdLocked();
Steven Thomas6d8110b2017-08-31 18:24:21 -07001031 }
Michael Wright28f24d02016-07-12 13:30:53 -07001032 outColorModes->clear();
Peiyong Linff84a152019-05-17 18:36:19 -07001033
1034 // If it's built-in display and the configuration claims it's not wide color capable,
1035 // filter out all wide color modes. The typical reason why this happens is that the
1036 // hardware is not good enough to support GPU composition of wide color, and thus the
1037 // OEMs choose to disable this capability.
1038 if (isInternalDisplay && !hasWideColorDisplay) {
1039 std::remove_copy_if(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes),
1040 isWideColorMode);
1041 } else {
1042 std::copy(modes.cbegin(), modes.cend(), std::back_inserter(*outColorModes));
1043 }
Michael Wright28f24d02016-07-12 13:30:53 -07001044
1045 return NO_ERROR;
1046}
1047
Daniel Solomon42d04562019-01-20 21:03:19 -08001048status_t SurfaceFlinger::getDisplayNativePrimaries(const sp<IBinder>& displayToken,
1049 ui::DisplayPrimaries &primaries) {
1050 if (!displayToken) {
1051 return BAD_VALUE;
1052 }
1053
1054 // Currently we only support this API for a single internal display.
1055 if (getInternalDisplayToken() != displayToken) {
1056 return BAD_VALUE;
1057 }
1058
1059 memcpy(&primaries, &mInternalDisplayPrimaries, sizeof(ui::DisplayPrimaries));
1060 return NO_ERROR;
1061}
1062
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001063ColorMode SurfaceFlinger::getActiveColorMode(const sp<IBinder>& displayToken) {
1064 if (const auto display = getDisplayDevice(displayToken)) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001065 return display->getCompositionDisplay()->getState().colorMode;
Michael Wright28f24d02016-07-12 13:30:53 -07001066 }
Peiyong Lina52f0292018-03-14 17:26:31 -07001067 return static_cast<ColorMode>(BAD_VALUE);
Michael Wright28f24d02016-07-12 13:30:53 -07001068}
1069
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001070status_t SurfaceFlinger::setActiveColorMode(const sp<IBinder>& displayToken, ColorMode mode) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001071 postMessageSync(new LambdaMessage([&] {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001072 Vector<ColorMode> modes;
1073 getDisplayColorModes(displayToken, &modes);
1074 bool exists = std::find(std::begin(modes), std::end(modes), mode) != std::end(modes);
1075 if (mode < ColorMode::NATIVE || !exists) {
1076 ALOGE("Attempt to set invalid active color mode %s (%d) for display token %p",
1077 decodeColorMode(mode).c_str(), mode, displayToken.get());
1078 return;
Michael Wright28f24d02016-07-12 13:30:53 -07001079 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001080 const auto display = getDisplayDevice(displayToken);
1081 if (!display) {
1082 ALOGE("Attempt to set active color mode %s (%d) for invalid display token %p",
1083 decodeColorMode(mode).c_str(), mode, displayToken.get());
1084 } else if (display->isVirtual()) {
1085 ALOGW("Attempt to set active color mode %s (%d) for virtual display",
1086 decodeColorMode(mode).c_str(), mode);
1087 } else {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001088 display->getCompositionDisplay()->setColorProfile(
1089 compositionengine::Output::ColorProfile{mode, Dataspace::UNKNOWN,
1090 RenderIntent::COLORIMETRIC,
1091 Dataspace::UNKNOWN});
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001092 }
1093 }));
1094
Michael Wright28f24d02016-07-12 13:30:53 -07001095 return NO_ERROR;
1096}
Mathias Agopianc666cae2012-07-25 18:56:13 -07001097
Svetoslavd85084b2014-03-20 10:28:31 -07001098status_t SurfaceFlinger::clearAnimationFrameStats() {
1099 Mutex::Autolock _l(mStateLock);
1100 mAnimFrameTracker.clearStats();
1101 return NO_ERROR;
1102}
1103
1104status_t SurfaceFlinger::getAnimationFrameStats(FrameStats* outStats) const {
1105 Mutex::Autolock _l(mStateLock);
1106 mAnimFrameTracker.getStats(outStats);
1107 return NO_ERROR;
1108}
1109
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001110status_t SurfaceFlinger::getHdrCapabilities(const sp<IBinder>& displayToken,
1111 HdrCapabilities* outCapabilities) const {
Dan Stozac4f471e2016-03-24 09:31:08 -07001112 Mutex::Autolock _l(mStateLock);
1113
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001114 const auto display = getDisplayDeviceLocked(displayToken);
1115 if (!display) {
1116 ALOGE("getHdrCapabilities: Invalid display token %p", displayToken.get());
Dan Stozac4f471e2016-03-24 09:31:08 -07001117 return BAD_VALUE;
1118 }
1119
Peiyong Linfb069302018-04-25 14:34:31 -07001120 // At this point the DisplayDeivce should already be set up,
1121 // meaning the luminance information is already queried from
1122 // hardware composer and stored properly.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07001123 const HdrCapabilities& capabilities = display->getHdrCapabilities();
Peiyong Linfb069302018-04-25 14:34:31 -07001124 *outCapabilities = HdrCapabilities(capabilities.getSupportedHdrTypes(),
1125 capabilities.getDesiredMaxLuminance(),
1126 capabilities.getDesiredMaxAverageLuminance(),
1127 capabilities.getDesiredMinLuminance());
Dan Stozac4f471e2016-03-24 09:31:08 -07001128
1129 return NO_ERROR;
1130}
1131
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001132status_t SurfaceFlinger::getDisplayedContentSamplingAttributes(const sp<IBinder>& displayToken,
1133 ui::PixelFormat* outFormat,
1134 ui::Dataspace* outDataspace,
1135 uint8_t* outComponentMask) const {
1136 if (!outFormat || !outDataspace || !outComponentMask) {
1137 return BAD_VALUE;
1138 }
Kevin DuBois74e53772018-11-19 10:52:38 -08001139 const auto display = getDisplayDevice(displayToken);
Kevin DuBois9c0a1762018-10-16 13:32:31 -07001140 if (!display || !display->getId()) {
1141 ALOGE("getDisplayedContentSamplingAttributes: Bad display token: %p", display.get());
1142 return BAD_VALUE;
1143 }
1144 return getHwComposer().getDisplayedContentSamplingAttributes(*display->getId(), outFormat,
1145 outDataspace, outComponentMask);
1146}
1147
Kevin DuBois74e53772018-11-19 10:52:38 -08001148status_t SurfaceFlinger::setDisplayContentSamplingEnabled(const sp<IBinder>& displayToken,
1149 bool enable, uint8_t componentMask,
1150 uint64_t maxFrames) const {
1151 const auto display = getDisplayDevice(displayToken);
1152 if (!display || !display->getId()) {
1153 ALOGE("setDisplayContentSamplingEnabled: Bad display token: %p", display.get());
1154 return BAD_VALUE;
1155 }
1156
1157 return getHwComposer().setDisplayContentSamplingEnabled(*display->getId(), enable,
1158 componentMask, maxFrames);
1159}
1160
Kevin DuBois1d4249a2018-08-29 10:45:14 -07001161status_t SurfaceFlinger::getDisplayedContentSample(const sp<IBinder>& displayToken,
1162 uint64_t maxFrames, uint64_t timestamp,
1163 DisplayedFrameStats* outStats) const {
1164 const auto display = getDisplayDevice(displayToken);
1165 if (!display || !display->getId()) {
1166 ALOGE("getDisplayContentSample: Bad display token: %p", displayToken.get());
1167 return BAD_VALUE;
1168 }
1169
1170 return getHwComposer().getDisplayedContentSample(*display->getId(), maxFrames, timestamp,
1171 outStats);
1172}
1173
Peiyong Lin3c2791e2019-01-14 17:05:18 -08001174status_t SurfaceFlinger::getProtectedContentSupport(bool* outSupported) const {
1175 if (!outSupported) {
1176 return BAD_VALUE;
1177 }
1178 *outSupported = getRenderEngine().supportsProtectedContent();
1179 return NO_ERROR;
1180}
1181
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001182status_t SurfaceFlinger::isWideColorDisplay(const sp<IBinder>& displayToken,
1183 bool* outIsWideColorDisplay) const {
1184 if (!displayToken || !outIsWideColorDisplay) {
1185 return BAD_VALUE;
1186 }
1187 Mutex::Autolock _l(mStateLock);
1188 const auto display = getDisplayDeviceLocked(displayToken);
1189 if (!display) {
1190 return BAD_VALUE;
1191 }
Peiyong Linff84a152019-05-17 18:36:19 -07001192
1193 // Use hasWideColorDisplay to override built-in display.
1194 const auto displayId = display->getId();
1195 if (displayId && displayId == getInternalDisplayIdLocked()) {
1196 *outIsWideColorDisplay = hasWideColorDisplay;
1197 return NO_ERROR;
1198 }
Peiyong Lin4f3fddf2019-01-24 17:21:24 -08001199 *outIsWideColorDisplay = display->hasWideColorGamut();
1200 return NO_ERROR;
1201}
1202
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001203status_t SurfaceFlinger::enableVSyncInjections(bool enable) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07001204 postMessageSync(new LambdaMessage([&] {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001205 Mutex::Autolock lock(mStateLock);
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001206
Dominik Laskowski6505f792019-09-18 11:10:05 -07001207 if (const auto handle = mScheduler->enableVSyncInjection(enable)) {
1208 mEventQueue->setEventConnection(
1209 mScheduler->getEventConnection(enable ? handle : mSfConnectionHandle));
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001210 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07001211 }));
1212
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001213 return NO_ERROR;
1214}
1215
1216status_t SurfaceFlinger::injectVSync(nsecs_t when) {
Dominik Laskowski6505f792019-09-18 11:10:05 -07001217 Mutex::Autolock lock(mStateLock);
1218 return mScheduler->injectVSync(when) ? NO_ERROR : BAD_VALUE;
Sahil Dhanjuc1ba5c42016-06-07 20:09:20 -07001219}
1220
Lloyd Pique755e3192018-01-31 16:46:15 -08001221status_t SurfaceFlinger::getLayerDebugInfo(std::vector<LayerDebugInfo>* outLayers) const
1222 NO_THREAD_SAFETY_ANALYSIS {
Kalle Raitaa099a242017-01-11 11:17:29 -08001223 // Try to acquire a lock for 1s, fail gracefully
1224 const status_t err = mStateLock.timedLock(s2ns(1));
1225 const bool locked = (err == NO_ERROR);
1226 if (!locked) {
1227 ALOGE("LayerDebugInfo: SurfaceFlinger unresponsive (%s [%d]) - exit", strerror(-err), err);
1228 return TIMED_OUT;
1229 }
1230
1231 outLayers->clear();
1232 mCurrentState.traverseInZOrder([&](Layer* layer) {
1233 outLayers->push_back(layer->getLayerDebugInfo());
1234 });
1235
1236 mStateLock.unlock();
1237 return NO_ERROR;
1238}
1239
Peiyong Linc6780972018-10-28 15:24:08 -07001240status_t SurfaceFlinger::getCompositionPreference(
1241 Dataspace* outDataspace, ui::PixelFormat* outPixelFormat,
1242 Dataspace* outWideColorGamutDataspace,
1243 ui::PixelFormat* outWideColorGamutPixelFormat) const {
Peiyong Lin9d846a52018-11-05 13:18:20 -08001244 *outDataspace = mDefaultCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001245 *outPixelFormat = defaultCompositionPixelFormat;
Peiyong Lin9d846a52018-11-05 13:18:20 -08001246 *outWideColorGamutDataspace = mWideColorGamutCompositionDataspace;
Peiyong Linc6780972018-10-28 15:24:08 -07001247 *outWideColorGamutPixelFormat = wideColorGamutCompositionPixelFormat;
Peiyong Lin0256f722018-08-31 15:45:10 -07001248 return NO_ERROR;
1249}
1250
Dan Stozaec460082018-12-17 15:35:09 -08001251status_t SurfaceFlinger::addRegionSamplingListener(const Rect& samplingArea,
1252 const sp<IBinder>& stopLayerHandle,
1253 const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001254 if (!listener || samplingArea == Rect::INVALID_RECT) {
Dan Stozaec460082018-12-17 15:35:09 -08001255 return BAD_VALUE;
1256 }
1257 mRegionSamplingThread->addListener(samplingArea, stopLayerHandle, listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001258 return NO_ERROR;
1259}
1260
Dan Stozaec460082018-12-17 15:35:09 -08001261status_t SurfaceFlinger::removeRegionSamplingListener(const sp<IRegionSamplingListener>& listener) {
tangrobinaf45f012019-02-26 18:10:10 +08001262 if (!listener) {
1263 return BAD_VALUE;
1264 }
Dan Stozaec460082018-12-17 15:35:09 -08001265 mRegionSamplingThread->removeListener(listener);
Dan Stoza84ab9372018-12-17 15:27:57 -08001266 return NO_ERROR;
1267}
Dan Gittik57e63c52019-01-18 16:37:54 +00001268
1269status_t SurfaceFlinger::getDisplayBrightnessSupport(const sp<IBinder>& displayToken,
1270 bool* outSupport) const {
1271 if (!displayToken || !outSupport) {
1272 return BAD_VALUE;
1273 }
1274 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1275 if (!displayId) {
1276 return NAME_NOT_FOUND;
1277 }
1278 *outSupport =
1279 getHwComposer().hasDisplayCapability(displayId, HWC2::DisplayCapability::Brightness);
1280 return NO_ERROR;
1281}
1282
1283status_t SurfaceFlinger::setDisplayBrightness(const sp<IBinder>& displayToken,
1284 float brightness) const {
1285 if (!displayToken) {
1286 return BAD_VALUE;
1287 }
1288 const auto displayId = getPhysicalDisplayIdLocked(displayToken);
1289 if (!displayId) {
1290 return NAME_NOT_FOUND;
1291 }
1292 return getHwComposer().setDisplayBrightness(*displayId, brightness);
1293}
1294
Ady Abraham8532d012019-05-08 14:50:56 -07001295status_t SurfaceFlinger::notifyPowerHint(int32_t hintId) {
1296 PowerHint powerHint = static_cast<PowerHint>(hintId);
1297
1298 if (powerHint == PowerHint::INTERACTION) {
1299 mScheduler->notifyTouchEvent();
1300 }
1301
1302 return NO_ERROR;
1303}
1304
Mathias Agopiand0566bc2011-11-17 17:49:17 -08001305// ----------------------------------------------------------------------------
1306
Jorim Jaggib1e2f8d2017-06-08 15:43:59 -07001307sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
Ady Abraham0f4a1b12019-06-04 16:04:04 -07001308 ISurfaceComposer::VsyncSource vsyncSource, ISurfaceComposer::ConfigChanged configChanged) {
Ana Krulecc2870422019-01-29 19:00:58 -08001309 const auto& handle =
1310 vsyncSource == eVsyncSourceSurfaceFlinger ? mSfConnectionHandle : mAppConnectionHandle;
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001311
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001312 return mScheduler->createDisplayEventConnection(handle, configChanged);
Mathias Agopianbb641242010-05-18 17:06:55 -07001313}
1314
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001315// ----------------------------------------------------------------------------
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001316
1317void SurfaceFlinger::waitForEvent() {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001318 mEventQueue->waitMessage();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001319}
1320
1321void SurfaceFlinger::signalTransaction() {
Ady Abraham8532d012019-05-08 14:50:56 -07001322 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001323 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001324}
1325
1326void SurfaceFlinger::signalLayerUpdate() {
Ady Abraham8532d012019-05-08 14:50:56 -07001327 mScheduler->resetIdleTimer();
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001328 mEventQueue->invalidate();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001329}
1330
1331void SurfaceFlinger::signalRefresh() {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001332 mRefreshPending = true;
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001333 mEventQueue->refresh();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001334}
1335
1336status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001337 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001338 return mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001339}
1340
1341status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
Dan Stozac7014012014-02-14 15:03:43 -08001342 nsecs_t reltime, uint32_t /* flags */) {
Lloyd Pique3fcdef12018-01-22 17:14:00 -08001343 status_t res = mEventQueue->postMessage(msg, reltime);
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001344 if (res == NO_ERROR) {
1345 msg->wait();
1346 }
1347 return res;
1348}
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001349
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001350void SurfaceFlinger::run() {
Mathias Agopian4f4f0942013-08-19 17:26:18 -07001351 do {
1352 waitForEvent();
1353 } while (true);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08001354}
1355
Dominik Laskowski83b88212018-12-11 13:34:06 -08001356nsecs_t SurfaceFlinger::getVsyncPeriod() const {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001357 const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski83b88212018-12-11 13:34:06 -08001358 if (!displayId || !getHwComposer().isConnected(*displayId)) {
1359 return 0;
1360 }
1361
1362 const auto config = getHwComposer().getActiveConfig(*displayId);
1363 return config ? config->getVsyncPeriod() : 0;
1364}
1365
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001366void SurfaceFlinger::onVsyncReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
1367 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001368 ATRACE_NAME("SF onVsync");
1369
Steven Thomas3cfac282017-02-06 12:29:30 -08001370 Mutex::Autolock lock(mStateLock);
Steven Thomasb02664d2017-07-26 18:48:28 -07001371 // Ignore any vsyncs from a previous hardware composer.
David Sodman105b7dc2017-11-04 20:28:14 -07001372 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001373 return;
1374 }
1375
Dominik Laskowski075d3172018-05-24 15:50:06 -07001376 if (!getHwComposer().onVsync(hwcDisplayId, timestamp)) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001377 return;
1378 }
1379
Dominik Laskowski075d3172018-05-24 15:50:06 -07001380 if (hwcDisplayId != getHwComposer().getInternalHwcDisplayId()) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001381 // For now, we don't do anything with external display vsyncs.
1382 return;
1383 }
1384
Alec Mourif8e689c2019-05-20 18:32:22 -07001385 bool periodFlushed = false;
1386 mScheduler->addResyncSample(timestamp, &periodFlushed);
1387 if (periodFlushed) {
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001388 mVSyncModulator->onRefreshRateChangeCompleted();
Alec Mouri754c98a2019-03-18 18:53:42 -07001389 }
Mathias Agopian148994e2012-09-19 17:31:36 -07001390}
1391
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001392void SurfaceFlinger::getCompositorTiming(CompositorTiming* compositorTiming) {
David Sodman99974d22017-11-28 12:04:33 -08001393 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1394 *compositorTiming = getBE().mCompositorTiming;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001395}
1396
Ady Abraham261614e2019-07-10 17:53:12 -07001397bool SurfaceFlinger::isDisplayConfigAllowed(int32_t configId) const {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001398 return mAllowedDisplayConfigs.empty() || mAllowedDisplayConfigs.count(configId);
Ady Abraham838de062019-02-04 10:24:03 -08001399}
1400
Ana Krulec8d3e4f32019-03-05 10:40:33 -08001401void SurfaceFlinger::setRefreshRateTo(RefreshRateType refreshRate, Scheduler::ConfigEvent event) {
Dominik Laskowski22488f62019-03-28 09:53:04 -07001402 const auto display = getDefaultDisplayDeviceLocked();
1403 if (!display || mBootStage != BootStage::FINISHED) {
Ana Krulec7d1d6832018-12-27 11:10:09 -08001404 return;
1405 }
Alec Mouri1c9e82b2019-03-07 12:24:05 -08001406 ATRACE_CALL();
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08001407
Ana Krulec7d1d6832018-12-27 11:10:09 -08001408 // Don't do any updating if the current fps is the same as the new one.
Steven Thomas2bbaabe2019-08-28 16:08:35 -07001409 const auto& refreshRateConfig = mRefreshRateConfigs->getRefreshRateFromType(refreshRate);
1410 const int desiredConfigId = refreshRateConfig.configId;
Alec Mouri0a1cc962019-03-14 12:33:02 -07001411
Dominik Laskowski22488f62019-03-28 09:53:04 -07001412 if (!isDisplayConfigAllowed(desiredConfigId)) {
Ady Abraham1902d072019-03-01 17:18:59 -08001413 ALOGV("Skipping config %d as it is not part of allowed configs", desiredConfigId);
1414 return;
1415 }
1416
Dominik Laskowski22488f62019-03-28 09:53:04 -07001417 setDesiredActiveConfig({refreshRate, desiredConfigId, event});
Ana Krulec7d1d6832018-12-27 11:10:09 -08001418}
1419
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001420void SurfaceFlinger::onHotplugReceived(int32_t sequenceId, hwc2_display_t hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001421 HWC2::Connection connection) {
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001422 ALOGV("%s(%d, %" PRIu64 ", %s)", __FUNCTION__, sequenceId, hwcDisplayId,
Lloyd Pique715a2c12017-12-14 17:18:08 -08001423 connection == HWC2::Connection::Connected ? "connected" : "disconnected");
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001424
Lloyd Piqueba04e622017-12-14 17:11:26 -08001425 // Ignore events that do not have the right sequenceId.
1426 if (sequenceId != getBE().mComposerSequenceId) {
1427 return;
1428 }
1429
Steven Thomasb02664d2017-07-26 18:48:28 -07001430 // Only lock if we're not on the main thread. This function is normally
1431 // called on a hwbinder thread, but for the primary display it's called on
1432 // the main thread with the state lock already held, so don't attempt to
1433 // acquire it here.
Lloyd Piqueba04e622017-12-14 17:11:26 -08001434 ConditionalLock lock(mStateLock, std::this_thread::get_id() != mMainThreadId);
Steven Thomasb02664d2017-07-26 18:48:28 -07001435
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001436 mPendingHotplugEvents.emplace_back(HotplugEvent{hwcDisplayId, connection});
Mathias Agopian9e2463e2012-09-21 18:26:16 -07001437
Jiwen 'Steve' Caiccfd6822018-02-21 16:15:58 -08001438 if (std::this_thread::get_id() == mMainThreadId) {
1439 // Process all pending hot plug events immediately if we are on the main thread.
1440 processDisplayHotplugEventsLocked();
1441 }
1442
Lloyd Piqueba04e622017-12-14 17:11:26 -08001443 setTransactionFlags(eDisplayTransactionNeeded);
Mathias Agopian86303202012-07-24 22:46:10 -07001444}
1445
Dominik Laskowskia2edf612018-06-01 13:15:16 -07001446void SurfaceFlinger::onRefreshReceived(int sequenceId, hwc2_display_t /*hwcDisplayId*/) {
Steven Thomas3cfac282017-02-06 12:29:30 -08001447 Mutex::Autolock lock(mStateLock);
David Sodman105b7dc2017-11-04 20:28:14 -07001448 if (sequenceId != getBE().mComposerSequenceId) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001449 return;
Steven Thomas3cfac282017-02-06 12:29:30 -08001450 }
Ana Krulec7d1d6832018-12-27 11:10:09 -08001451 repaintEverythingForHWC();
Steven Thomas3cfac282017-02-06 12:29:30 -08001452}
1453
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001454void SurfaceFlinger::setPrimaryVsyncEnabled(bool enabled) {
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001455 ATRACE_CALL();
Ady Abraham9ba25122019-06-03 17:10:55 -07001456
1457 // Enable / Disable HWVsync from the main thread to avoid race conditions with
1458 // display power state.
1459 postMessageAsync(new LambdaMessage(
1460 [=]() NO_THREAD_SAFETY_ANALYSIS { setPrimaryVsyncEnabledInternal(enabled); }));
1461}
1462
1463void SurfaceFlinger::setPrimaryVsyncEnabledInternal(bool enabled) {
1464 ATRACE_CALL();
1465
Ady Abraham27c70212019-06-11 10:52:26 -07001466 mHWCVsyncPendingState = enabled ? HWC2::Vsync::Enable : HWC2::Vsync::Disable;
1467
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08001468 if (const auto displayId = getInternalDisplayIdLocked()) {
Ady Abraham9ba25122019-06-03 17:10:55 -07001469 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
1470 if (display && display->isPoweredOn()) {
Ady Abraham27c70212019-06-11 10:52:26 -07001471 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ady Abraham9ba25122019-06-03 17:10:55 -07001472 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07001473 }
Mathias Agopian86303202012-07-24 22:46:10 -07001474}
1475
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001476// Note: it is assumed the caller holds |mStateLock| when this is called
Steven Thomasb02664d2017-07-26 18:48:28 -07001477void SurfaceFlinger::resetDisplayState() {
Ana Krulecc2870422019-01-29 19:00:58 -08001478 mScheduler->disableHardwareVsync(true);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001479 // Clear the drawing state so that the logic inside of
1480 // handleTransactionLocked will fire. It will determine the delta between
1481 // mCurrentState and mDrawingState and re-apply all changes when we make the
1482 // transition.
1483 mDrawingState.displays.clear();
1484 mDisplays.clear();
1485}
1486
Steven Thomas050b2c82017-03-06 11:45:16 -08001487void SurfaceFlinger::updateVrFlinger() {
Alec Mourife3dc942019-02-12 14:19:18 -08001488 ATRACE_CALL();
Steven Thomas050b2c82017-03-06 11:45:16 -08001489 if (!mVrFlinger)
1490 return;
1491 bool vrFlingerRequestsDisplay = mVrFlingerRequestsDisplay;
Lloyd Pique441d5042018-10-18 16:49:51 -07001492 if (vrFlingerRequestsDisplay == getHwComposer().isUsingVrComposer()) {
Mark Urbanus209beca2017-02-23 11:16:04 -08001493 return;
1494 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001495
Lloyd Pique441d5042018-10-18 16:49:51 -07001496 if (vrFlingerRequestsDisplay && !getHwComposer().getComposer()->isRemote()) {
Steven Thomasb02664d2017-07-26 18:48:28 -07001497 ALOGE("Vr flinger is only supported for remote hardware composer"
1498 " service connections. Ignoring request to transition to vr"
1499 " flinger.");
1500 mVrFlingerRequestsDisplay = false;
1501 return;
Mark Urbanus209beca2017-02-23 11:16:04 -08001502 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001503
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001504 Mutex::Autolock _l(mStateLock);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001505
Steven Thomas0123ac62018-07-12 11:32:34 -07001506 sp<DisplayDevice> display = getDefaultDisplayDeviceLocked();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001507 LOG_ALWAYS_FATAL_IF(!display);
Lloyd Pique07e33212018-12-18 16:33:37 -08001508
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07001509 const int currentDisplayPowerMode = display->getPowerMode();
Lloyd Pique07e33212018-12-18 16:33:37 -08001510
1511 // Clear out all the output layers from the composition engine for all
1512 // displays before destroying the hardware composer interface. This ensures
1513 // any HWC layers are destroyed through that interface before it becomes
1514 // invalid.
1515 for (const auto& [token, displayDevice] : mDisplays) {
Lloyd Pique01c77c12019-04-17 12:48:32 -07001516 displayDevice->getCompositionDisplay()->clearOutputLayers();
Lloyd Pique07e33212018-12-18 16:33:37 -08001517 }
1518
Steven Thomas0123ac62018-07-12 11:32:34 -07001519 // This DisplayDevice will no longer be relevant once resetDisplayState() is
1520 // called below. Clear the reference now so we don't accidentally use it
1521 // later.
1522 display.clear();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001523
Steven Thomasb02664d2017-07-26 18:48:28 -07001524 if (!vrFlingerRequestsDisplay) {
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001525 mVrFlinger->SeizeDisplayOwnership();
Steven Thomasb02664d2017-07-26 18:48:28 -07001526 }
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001527
Steven Thomasb02664d2017-07-26 18:48:28 -07001528 resetDisplayState();
Lloyd Pique441d5042018-10-18 16:49:51 -07001529 // Delete the current instance before creating the new one
1530 mCompositionEngine->setHwComposer(std::unique_ptr<HWComposer>());
1531 mCompositionEngine->setHwComposer(getFactory().createHWComposer(
1532 vrFlingerRequestsDisplay ? "vr" : getBE().mHwcServiceName));
1533 getHwComposer().registerCallback(this, ++getBE().mComposerSequenceId);
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001534
Lloyd Pique441d5042018-10-18 16:49:51 -07001535 LOG_ALWAYS_FATAL_IF(!getHwComposer().getComposer()->isRemote(),
David Sodman105b7dc2017-11-04 20:28:14 -07001536 "Switched to non-remote hardware composer");
Steven Thomasb02664d2017-07-26 18:48:28 -07001537
1538 if (vrFlingerRequestsDisplay) {
1539 mVrFlinger->GrantDisplayOwnership();
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001540 }
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001541
1542 mVisibleRegionsDirty = true;
1543 invalidateHwcGeometry();
1544
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001545 // Re-enable default display.
Steven Thomas0123ac62018-07-12 11:32:34 -07001546 display = getDefaultDisplayDeviceLocked();
1547 LOG_ALWAYS_FATAL_IF(!display);
Dominik Laskowskie9774092018-12-11 10:04:24 -08001548 setPowerModeInternal(display, currentDisplayPowerMode);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001549
Steven Thomasb02664d2017-07-26 18:48:28 -07001550 // Reset the timing values to account for the period of the swapped in HWC
Dominik Laskowski83b88212018-12-11 13:34:06 -08001551 const nsecs_t vsyncPeriod = getVsyncPeriod();
1552 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Alex Sakhartchouk096cb992017-06-05 10:37:57 -04001553
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001554 // The present fences returned from vr_hwc are not an accurate
1555 // representation of vsync times.
Ana Krulecc2870422019-01-29 19:00:58 -08001556 mScheduler->setIgnorePresentFences(getHwComposer().isUsingVrComposer() || !hasSyncFramework);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001557
Steven Thomasb02664d2017-07-26 18:48:28 -07001558 // Use phase of 0 since phase is not known.
1559 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08001560 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07001561 setCompositorTimingSnapped(stats, 0);
Stephen Kiazyk82386cd2017-04-14 13:43:29 -07001562
Ana Krulecc2870422019-01-29 19:00:58 -08001563 mScheduler->resyncToHardwareVsync(false, vsyncPeriod);
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001564
Lloyd Piquef1c675b2018-09-12 20:45:39 -07001565 mRepaintEverything = true;
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001566 setTransactionFlags(eDisplayTransactionNeeded);
Hendrik Wagenaar87670ff2017-02-01 12:10:46 -08001567}
1568
Ady Abraham11579302019-09-19 12:35:58 -07001569bool SurfaceFlinger::previousFrameMissed(int graceTimeMs) NO_THREAD_SAFETY_ANALYSIS {
1570 ATRACE_CALL();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001571 // We are storing the last 2 present fences. If sf's phase offset is to be
1572 // woken up before the actual vsync but targeting the next vsync, we need to check
1573 // fence N-2
1574 const sp<Fence>& fence =
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001575 mVSyncModulator->getOffsets().sf < mPhaseOffsets->getOffsetThresholdForNextVsync()
Ady Abrahambe0f9482019-04-24 15:41:53 -07001576 ? mPreviousPresentFences[0]
1577 : mPreviousPresentFences[1];
1578
Ady Abraham11579302019-09-19 12:35:58 -07001579 if (fence == Fence::NO_FENCE) {
1580 return false;
1581 }
1582
1583 if (graceTimeMs > 0 && fence->getStatus() == Fence::Status::Unsignaled) {
1584 fence->wait(graceTimeMs);
1585 }
1586
1587 return (fence->getStatus() == Fence::Status::Unsignaled);
Ady Abrahambe0f9482019-04-24 15:41:53 -07001588}
1589
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001590void SurfaceFlinger::populateExpectedPresentTime() {
Alec Mouriaa614192019-06-06 13:28:34 -07001591 DisplayStatInfo stats;
1592 mScheduler->getDisplayStatInfo(&stats);
Ady Abraham8fe11022019-06-12 17:11:12 -07001593 const nsecs_t presentTime = mScheduler->getDispSyncExpectedPresentTime();
Alec Mouriaa614192019-06-06 13:28:34 -07001594 // Inflate the expected present time if we're targetting the next vsync.
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001595 mExpectedPresentTime.store(mVSyncModulator->getOffsets().sf <
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07001596 mPhaseOffsets->getOffsetThresholdForNextVsync()
1597 ? presentTime
1598 : presentTime + stats.vsyncPeriod);
Alec Mouriaa614192019-06-06 13:28:34 -07001599}
1600
Dominik Laskowski22488f62019-03-28 09:53:04 -07001601void SurfaceFlinger::onMessageReceived(int32_t what) NO_THREAD_SAFETY_ANALYSIS {
Jamie Gennis1c8e95c2012-02-23 19:27:23 -08001602 ATRACE_CALL();
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001603 switch (what) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08001604 case MessageQueue::INVALIDATE: {
Alec Mouri9519bf12019-11-15 16:54:44 -08001605 const nsecs_t frameStart = systemTime();
Ady Abraham7c03ce62019-07-19 10:59:45 -07001606 // calculate the expected present time once and use the cached
1607 // value throughout this frame to make sure all layers are
1608 // seeing this same value.
1609 populateExpectedPresentTime();
1610
Ady Abraham11579302019-09-19 12:35:58 -07001611 // When Backpressure propagation is enabled we want to give a small grace period
1612 // for the present fence to fire instead of just giving up on this frame to handle cases
1613 // where present fence is just about to get signaled.
1614 const int graceTimeForPresentFenceMs =
1615 (mPropagateBackpressure &&
1616 (mPropagateBackpressureClientComposition || !mHadClientComposition))
1617 ? 1
1618 : 0;
1619 const TracedOrdinal<bool> frameMissed = {"FrameMissed",
1620 previousFrameMissed(
1621 graceTimeForPresentFenceMs)};
Ady Abraham50204dd2019-07-19 15:47:11 -07001622 const TracedOrdinal<bool> hwcFrameMissed = {"HwcFrameMissed",
1623 mHadDeviceComposition && frameMissed};
1624 const TracedOrdinal<bool> gpuFrameMissed = {"GpuFrameMissed",
1625 mHadClientComposition && frameMissed};
1626
Alec Mouricc0fc602019-02-26 21:45:19 -08001627 if (frameMissed) {
1628 mFrameMissedCount++;
1629 mTimeStats->incrementMissedFrames();
1630 }
1631
Alec Mouri40189b02019-03-05 15:07:54 -08001632 if (hwcFrameMissed) {
1633 mHwcFrameMissedCount++;
1634 }
1635
1636 if (gpuFrameMissed) {
1637 mGpuFrameMissedCount++;
1638 }
1639
Dominik Laskowski49cea512019-11-12 14:13:23 -08001640 mScheduler->chooseRefreshRateForContent();
Ana Krulecfefd6ae2019-02-13 17:53:08 -08001641
Ady Abrahamb838aed2019-02-12 15:30:16 -08001642 if (performSetActiveConfig()) {
Ana Kruleca5bdd9d2019-01-29 19:00:58 -08001643 break;
1644 }
1645
Ady Abrahamadb9a992019-09-19 21:21:55 +00001646 if (frameMissed && mPropagateBackpressure) {
1647 if ((hwcFrameMissed && !gpuFrameMissed) ||
1648 mPropagateBackpressureClientComposition) {
Yiwei Zhang621f9d42018-05-07 10:40:55 -07001649 signalLayerUpdate();
1650 break;
1651 }
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001652 }
Dan Stoza50182882016-07-08 12:02:20 -07001653
Steven Thomas050b2c82017-03-06 11:45:16 -08001654 // Now that we're going to make it to the handleMessageTransaction()
1655 // call below it's safe to call updateVrFlinger(), which will
1656 // potentially trigger a display handoff.
1657 updateVrFlinger();
1658
Dan Stoza6b9454d2014-11-07 16:00:59 -08001659 bool refreshNeeded = handleMessageTransaction();
1660 refreshNeeded |= handleMessageInvalidate();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001661
1662 updateCursorAsync();
1663 updateInputFlinger();
1664
Dan Stoza58784442014-12-02 16:58:17 -08001665 refreshNeeded |= mRepaintEverything;
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08001666 if (refreshNeeded && CC_LIKELY(mBootStage != BootStage::BOOTLOADER)) {
Dan Stoza58784442014-12-02 16:58:17 -08001667 // Signal a refresh if a transaction modified the window state,
1668 // a new buffer was latched, or if HWC has requested a full
1669 // repaint
Alec Mouri9519bf12019-11-15 16:54:44 -08001670 if (mFrameStartTime <= 0) {
1671 // We should only use the time of the first invalidate
1672 // message that signals a refresh as the beginning of the
1673 // frame. Otherwise the real frame time will be
1674 // underestimated.
1675 mFrameStartTime = frameStart;
1676 }
Dan Stoza6b9454d2014-11-07 16:00:59 -08001677 signalRefresh();
1678 }
1679 break;
1680 }
1681 case MessageQueue::REFRESH: {
1682 handleMessageRefresh();
1683 break;
1684 }
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08001685 }
1686}
1687
Dan Stoza6b9454d2014-11-07 16:00:59 -08001688bool SurfaceFlinger::handleMessageTransaction() {
Alec Mourife3dc942019-02-12 14:19:18 -08001689 ATRACE_CALL();
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08001690 uint32_t transactionFlags = peekTransactionFlags();
Marissa Wall713b63f2018-10-17 15:42:43 -07001691
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001692 bool flushedATransaction = flushTransactionQueues();
1693
1694 bool runHandleTransaction = transactionFlags &&
1695 ((transactionFlags != eTransactionFlushNeeded) || flushedATransaction);
1696
1697 if (runHandleTransaction) {
1698 handleTransaction(eTransactionMask);
1699 } else {
1700 getTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07001701 }
1702
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001703 if (transactionFlushNeeded()) {
1704 setTransactionFlags(eTransactionFlushNeeded);
Mathias Agopian4fec8732012-06-29 14:12:52 -07001705 }
Marissa Wall713b63f2018-10-17 15:42:43 -07001706
Marissa Walle6e3c0d2019-03-29 10:28:30 -07001707 return runHandleTransaction;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001708}
1709
Mathias Agopian4fec8732012-06-29 14:12:52 -07001710void SurfaceFlinger::handleMessageRefresh() {
Mathias Agopiancd60f992012-08-16 16:28:27 -07001711 ATRACE_CALL();
Dan Stoza14cd37c2015-07-09 12:43:33 -07001712
Dan Stoza2b6d38e2017-06-01 16:40:30 -07001713 mRefreshPending = false;
1714
Lloyd Piqueab039b52019-02-13 14:22:42 -08001715 compositionengine::CompositionRefreshArgs refreshArgs;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001716 refreshArgs.outputs.reserve(mDisplays.size());
Lloyd Piqueab039b52019-02-13 14:22:42 -08001717 for (const auto& [_, display] : mDisplays) {
1718 refreshArgs.outputs.push_back(display->getCompositionDisplay());
1719 }
1720 mDrawingState.traverseInZOrder([&refreshArgs](Layer* layer) {
1721 auto compositionLayer = layer->getCompositionLayer();
1722 if (compositionLayer) refreshArgs.layers.push_back(compositionLayer);
1723 });
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001724 refreshArgs.layersWithQueuedFrames.reserve(mLayersWithQueuedFrames.size());
1725 for (sp<Layer> layer : mLayersWithQueuedFrames) {
1726 auto compositionLayer = layer->getCompositionLayer();
Adithya Srinivasan871023e2019-11-05 13:54:13 -08001727 if (compositionLayer) {
1728 refreshArgs.layersWithQueuedFrames.push_back(compositionLayer.get());
1729 mFrameTracer->traceTimestamp(layer->getSequence(), layer->getCurrentBufferId(),
1730 layer->getCurrentFrameNumber(), systemTime(),
1731 FrameTracer::FrameEvent::HWC_COMPOSITION_QUEUED);
1732 }
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001733 }
1734
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001735 refreshArgs.repaintEverything = mRepaintEverything.exchange(false);
Lloyd Pique6a3b4462019-03-07 20:58:12 -08001736 refreshArgs.outputColorSetting = useColorManagement
1737 ? mDisplayColorSetting
1738 : compositionengine::OutputColorSetting::kUnmanaged;
1739 refreshArgs.colorSpaceAgnosticDataspace = mColorSpaceAgnosticDataspace;
1740 refreshArgs.forceOutputColorMode = mForceColorMode;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001741
1742 refreshArgs.updatingOutputGeometryThisFrame = mVisibleRegionsDirty;
1743 refreshArgs.updatingGeometryThisFrame = mGeometryInvalid || mVisibleRegionsDirty;
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001744
1745 if (CC_UNLIKELY(mDrawingState.colorMatrixChanged)) {
1746 refreshArgs.colorTransformMatrix = mDrawingState.colorMatrix;
1747 mDrawingState.colorMatrixChanged = false;
1748 }
1749
1750 refreshArgs.devOptForceClientComposition = mDebugDisableHWC || mDebugRegion;
1751
Lloyd Piquef8cf14d2019-02-28 16:03:12 -08001752 if (mDebugRegion != 0) {
1753 refreshArgs.devOptFlashDirtyRegionsDelay =
1754 std::chrono::milliseconds(mDebugRegion > 1 ? mDebugRegion : 0);
1755 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001756
Lloyd Pique3eb1b212019-03-07 21:15:40 -08001757 mGeometryInvalid = false;
1758
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001759 mCompositionEngine->present(refreshArgs);
Alec Mouri9519bf12019-11-15 16:54:44 -08001760 mTimeStats->recordFrameDuration(mFrameStartTime, systemTime());
1761 // Reset the frame start time now that we've recorded this frame.
1762 mFrameStartTime = 0;
Lloyd Piquec29e4c62019-03-07 21:48:19 -08001763
David Sodmanfa9b2af2017-12-24 13:28:59 -08001764 postFrame();
David Sodman2b406362017-12-15 13:33:47 -08001765 postComposition();
Dan Stoza05dacfb2016-07-01 13:33:38 -07001766
Lloyd Pique66d68602019-02-13 14:23:31 -08001767 mHadClientComposition =
1768 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1769 auto& displayDevice = tokenDisplayPair.second;
1770 return displayDevice->getCompositionDisplay()->getState().usesClientComposition;
1771 });
1772 mHadDeviceComposition =
1773 std::any_of(mDisplays.cbegin(), mDisplays.cend(), [](const auto& tokenDisplayPair) {
1774 auto& displayDevice = tokenDisplayPair.second;
1775 return displayDevice->getCompositionDisplay()->getState().usesDeviceComposition;
1776 });
David Sodmanfa9b2af2017-12-24 13:28:59 -08001777
Dominik Laskowskieddeda12019-07-19 11:54:13 -07001778 mVSyncModulator->onRefreshed(mHadClientComposition);
Dan Stoza14cd37c2015-07-09 12:43:33 -07001779
David Sodman7e4ae112018-02-09 15:02:28 -08001780 mLayersWithQueuedFrames.clear();
Vishnu Nairdf529052019-06-07 14:53:14 -07001781 if (mVisibleRegionsDirty) {
1782 mVisibleRegionsDirty = false;
1783 if (mTracingEnabled) {
1784 mTracing.notify("visibleRegionsDirty");
1785 }
1786 }
Lloyd Piqueab039b52019-02-13 14:22:42 -08001787
1788 if (mCompositionEngine->needsAnotherUpdate()) {
1789 signalLayerUpdate();
1790 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07001791}
Mathias Agopian4fec8732012-06-29 14:12:52 -07001792
David Sodmanfa9b2af2017-12-24 13:28:59 -08001793
1794bool SurfaceFlinger::handleMessageInvalidate() {
1795 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001796 bool refreshNeeded = handlePageFlip();
1797
Vishnu Nair4351ad52019-02-11 14:13:02 -08001798 if (mVisibleRegionsDirty) {
1799 computeLayerBounds();
1800 }
1801
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001802 for (auto& layer : mLayersPendingRefresh) {
1803 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08001804 visibleReg.set(layer->getScreenBounds());
Vishnu Nair6194e2e2019-02-06 12:58:39 -08001805 invalidateLayerStack(layer, visibleReg);
1806 }
1807 mLayersPendingRefresh.clear();
1808 return refreshNeeded;
Mathias Agopian4fec8732012-06-29 14:12:52 -07001809}
1810
Ana Krulece588e312018-09-18 12:32:24 -07001811void SurfaceFlinger::updateCompositorTiming(const DisplayStatInfo& stats, nsecs_t compositeTime,
1812 std::shared_ptr<FenceTime>& presentFenceTime) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001813 // Update queue of past composite+present times and determine the
1814 // most recently known composite to present latency.
David Sodman99974d22017-11-28 12:04:33 -08001815 getBE().mCompositePresentTimes.push({compositeTime, presentFenceTime});
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001816 nsecs_t compositeToPresentLatency = -1;
David Sodman99974d22017-11-28 12:04:33 -08001817 while (!getBE().mCompositePresentTimes.empty()) {
1818 SurfaceFlingerBE::CompositePresentTime& cpt = getBE().mCompositePresentTimes.front();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001819 // Cached values should have been updated before calling this method,
1820 // which helps avoid duplicate syscalls.
1821 nsecs_t displayTime = cpt.display->getCachedSignalTime();
1822 if (displayTime == Fence::SIGNAL_TIME_PENDING) {
1823 break;
1824 }
1825 compositeToPresentLatency = displayTime - cpt.composite;
David Sodman99974d22017-11-28 12:04:33 -08001826 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001827 }
1828
1829 // Don't let mCompositePresentTimes grow unbounded, just in case.
David Sodman99974d22017-11-28 12:04:33 -08001830 while (getBE().mCompositePresentTimes.size() > 16) {
1831 getBE().mCompositePresentTimes.pop();
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001832 }
1833
Ana Krulece588e312018-09-18 12:32:24 -07001834 setCompositorTimingSnapped(stats, compositeToPresentLatency);
Brian Andersond0010582017-03-07 13:20:31 -08001835}
1836
Ana Krulece588e312018-09-18 12:32:24 -07001837void SurfaceFlinger::setCompositorTimingSnapped(const DisplayStatInfo& stats,
1838 nsecs_t compositeToPresentLatency) {
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001839 // Integer division and modulo round toward 0 not -inf, so we need to
1840 // treat negative and positive offsets differently.
Ana Krulec757f63a2019-01-25 10:46:18 -08001841 nsecs_t idealLatency = (mPhaseOffsets->getCurrentSfOffset() > 0)
1842 ? (stats.vsyncPeriod - (mPhaseOffsets->getCurrentSfOffset() % stats.vsyncPeriod))
1843 : ((-mPhaseOffsets->getCurrentSfOffset()) % stats.vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001844
Ana Krulec757f63a2019-01-25 10:46:18 -08001845 // Just in case mPhaseOffsets->getCurrentSfOffset() == -vsyncInterval.
Brian Andersond0010582017-03-07 13:20:31 -08001846 if (idealLatency <= 0) {
Ana Krulece588e312018-09-18 12:32:24 -07001847 idealLatency = stats.vsyncPeriod;
Brian Andersond0010582017-03-07 13:20:31 -08001848 }
1849
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001850 // Snap the latency to a value that removes scheduling jitter from the
1851 // composition and present times, which often have >1ms of jitter.
1852 // Reducing jitter is important if an app attempts to extrapolate
1853 // something (such as user input) to an accurate diasplay time.
Ana Krulec757f63a2019-01-25 10:46:18 -08001854 // Snapping also allows an app to precisely calculate mPhaseOffsets->getCurrentSfOffset()
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001855 // with (presentLatency % interval).
Ana Krulece588e312018-09-18 12:32:24 -07001856 nsecs_t bias = stats.vsyncPeriod / 2;
1857 int64_t extraVsyncs = (compositeToPresentLatency - idealLatency + bias) / stats.vsyncPeriod;
1858 nsecs_t snappedCompositeToPresentLatency =
1859 (extraVsyncs > 0) ? idealLatency + (extraVsyncs * stats.vsyncPeriod) : idealLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001860
David Sodman99974d22017-11-28 12:04:33 -08001861 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
Ana Krulece588e312018-09-18 12:32:24 -07001862 getBE().mCompositorTiming.deadline = stats.vsyncTime - idealLatency;
1863 getBE().mCompositorTiming.interval = stats.vsyncPeriod;
David Sodman99974d22017-11-28 12:04:33 -08001864 getBE().mCompositorTiming.presentLatency = snappedCompositeToPresentLatency;
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001865}
1866
David Sodman2b406362017-12-15 13:33:47 -08001867void SurfaceFlinger::postComposition()
Mathias Agopiancd60f992012-08-16 16:28:27 -07001868{
Dan Stoza9e56aa02015-11-02 13:00:03 -08001869 ATRACE_CALL();
1870 ALOGV("postComposition");
1871
Brian Anderson3546a3f2016-07-14 11:51:14 -07001872 // Release any buffers which were replaced this frame
Brian Andersonf6386862016-10-31 16:34:13 -07001873 nsecs_t dequeueReadyTime = systemTime();
Brian Anderson3546a3f2016-07-14 11:51:14 -07001874 for (auto& layer : mLayersWithQueuedFrames) {
Brian Andersonf6386862016-10-31 16:34:13 -07001875 layer->releasePendingBuffer(dequeueReadyTime);
Brian Anderson3546a3f2016-07-14 11:51:14 -07001876 }
1877
Stephen Kiazyk7d3dcb92017-04-05 16:46:49 -07001878 // |mStateLock| not needed as we are on the main thread
Lloyd Pique32cbe282018-10-19 13:09:22 -07001879 const auto displayDevice = getDefaultDisplayDeviceLocked();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001880
David Sodman73beded2017-11-15 11:56:06 -08001881 getBE().mGlCompositionDoneTimeline.updateSignalTimes();
Brian Anderson3d4039d2016-09-23 16:31:30 -07001882 std::shared_ptr<FenceTime> glCompositionDoneFenceTime;
Lloyd Pique66d68602019-02-13 14:23:31 -08001883 if (displayDevice && displayDevice->getCompositionDisplay()->getState().usesClientComposition) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001884 glCompositionDoneFenceTime =
Lloyd Pique31cb2942018-10-19 17:23:03 -07001885 std::make_shared<FenceTime>(displayDevice->getCompositionDisplay()
1886 ->getRenderSurface()
1887 ->getClientTargetAcquireFence());
David Sodman73beded2017-11-15 11:56:06 -08001888 getBE().mGlCompositionDoneTimeline.push(glCompositionDoneFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001889 } else {
1890 glCompositionDoneFenceTime = FenceTime::NO_FENCE;
1891 }
Brian Anderson3d4039d2016-09-23 16:31:30 -07001892
David Sodman73beded2017-11-15 11:56:06 -08001893 getBE().mDisplayTimeline.updateSignalTimes();
Ady Abrahambe0f9482019-04-24 15:41:53 -07001894 mPreviousPresentFences[1] = mPreviousPresentFences[0];
1895 mPreviousPresentFences[0] = displayDevice
1896 ? getHwComposer().getPresentFence(*displayDevice->getId())
1897 : Fence::NO_FENCE;
1898 auto presentFenceTime = std::make_shared<FenceTime>(mPreviousPresentFences[0]);
David Sodman73beded2017-11-15 11:56:06 -08001899 getBE().mDisplayTimeline.push(presentFenceTime);
Brian Anderson3d4039d2016-09-23 16:31:30 -07001900
Ana Krulece588e312018-09-18 12:32:24 -07001901 DisplayStatInfo stats;
Ana Krulecc2870422019-01-29 19:00:58 -08001902 mScheduler->getDisplayStatInfo(&stats);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001903
Lloyd Piqueab039b52019-02-13 14:22:42 -08001904 // We use the CompositionEngine::getLastFrameRefreshTimestamp() which might
1905 // be sampled a little later than when we started doing work for this frame,
1906 // but that should be okay since updateCompositorTiming has snapping logic.
1907 updateCompositorTiming(stats, mCompositionEngine->getLastFrameRefreshTimestamp(),
1908 presentFenceTime);
Brian Andersond0010582017-03-07 13:20:31 -08001909 CompositorTiming compositorTiming;
1910 {
David Sodman99974d22017-11-28 12:04:33 -08001911 std::lock_guard<std::mutex> lock(getBE().mCompositorTimingLock);
1912 compositorTiming = getBE().mCompositorTiming;
Brian Andersond0010582017-03-07 13:20:31 -08001913 }
Brian Anderson0a61b0c2016-12-07 14:55:56 -08001914
Robert Carr2047fae2016-11-28 14:09:09 -08001915 mDrawingState.traverseInZOrder([&](Layer* layer) {
Adithya Srinivasanb69e0762019-11-11 18:39:53 -08001916 bool frameLatched = layer->onPostComposition(displayDevice, glCompositionDoneFenceTime,
1917 presentFenceTime, compositorTiming);
Dan Stozae77c7662016-05-13 11:37:28 -07001918 if (frameLatched) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07001919 recordBufferingStats(layer->getName(), layer->getOccupancyHistory(false));
Dan Stozae77c7662016-05-13 11:37:28 -07001920 }
Robert Carr2047fae2016-11-28 14:09:09 -08001921 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001922
Brian Andersonfbc80ae2017-05-26 16:23:54 -07001923 if (presentFenceTime->isValid()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001924 mScheduler->addPresentFence(presentFenceTime);
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001925 }
1926
Fabien Sanglardcbf153b2017-03-10 17:57:12 -08001927 if (!hasSyncFramework) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07001928 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1929 displayDevice->isPoweredOn()) {
Ana Krulecc2870422019-01-29 19:00:58 -08001930 mScheduler->enableHardwareVsync();
Jamie Gennisfaf77cc2013-07-30 15:10:32 -07001931 }
1932 }
1933
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001934 if (mAnimCompositionPending) {
1935 mAnimCompositionPending = false;
1936
Brian Anderson4e606e32017-03-16 15:34:57 -07001937 if (presentFenceTime->isValid()) {
Brian Anderson3d4039d2016-09-23 16:31:30 -07001938 mAnimFrameTracker.setActualPresentFence(
Brian Anderson4e606e32017-03-16 15:34:57 -07001939 std::move(presentFenceTime));
Lloyd Pique32cbe282018-10-19 13:09:22 -07001940 } else if (displayDevice && getHwComposer().isConnected(*displayDevice->getId())) {
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001941 // The HWC doesn't support present fences, so use the refresh
1942 // timestamp instead.
Lloyd Pique32cbe282018-10-19 13:09:22 -07001943 const nsecs_t presentTime =
1944 getHwComposer().getRefreshTimestamp(*displayDevice->getId());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08001945 mAnimFrameTracker.setActualPresentTime(presentTime);
1946 }
1947 mAnimFrameTracker.advanceFrame();
1948 }
Dan Stozab90cf072015-03-05 11:05:59 -08001949
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001950 mTimeStats->incrementTotalFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001951 if (mHadClientComposition) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001952 mTimeStats->incrementClientCompositionFrames();
Yiwei Zhangfaf3ded2018-05-02 17:37:17 -07001953 }
1954
Yiwei Zhang7e666a52018-11-15 13:33:42 -08001955 mTimeStats->setPresentFenceGlobal(presentFenceTime);
Yiwei Zhangce6ebc02018-10-20 12:42:38 -07001956
Lloyd Pique32cbe282018-10-19 13:09:22 -07001957 if (displayDevice && getHwComposer().isConnected(*displayDevice->getId()) &&
1958 !displayDevice->isPoweredOn()) {
Dan Stozab90cf072015-03-05 11:05:59 -08001959 return;
1960 }
1961
1962 nsecs_t currentTime = systemTime();
1963 if (mHasPoweredOff) {
1964 mHasPoweredOff = false;
1965 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001966 nsecs_t elapsedTime = currentTime - getBE().mLastSwapTime;
Ana Krulece588e312018-09-18 12:32:24 -07001967 size_t numPeriods = static_cast<size_t>(elapsedTime / stats.vsyncPeriod);
David Sodman4a36e932017-11-07 14:29:47 -08001968 if (numPeriods < SurfaceFlingerBE::NUM_BUCKETS - 1) {
1969 getBE().mFrameBuckets[numPeriods] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001970 } else {
David Sodman4a36e932017-11-07 14:29:47 -08001971 getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001972 }
David Sodman4a36e932017-11-07 14:29:47 -08001973 getBE().mTotalTime += elapsedTime;
Dan Stozab90cf072015-03-05 11:05:59 -08001974 }
David Sodman4a36e932017-11-07 14:29:47 -08001975 getBE().mLastSwapTime = currentTime;
Dan Stoza436ccf32018-06-21 12:10:12 -07001976
1977 {
1978 std::lock_guard lock(mTexturePoolMutex);
Dan Stoza67765d82019-05-07 14:58:27 -07001979 if (mTexturePool.size() < mTexturePoolSize) {
1980 const size_t refillCount = mTexturePoolSize - mTexturePool.size();
Dan Stoza436ccf32018-06-21 12:10:12 -07001981 const size_t offset = mTexturePool.size();
1982 mTexturePool.resize(mTexturePoolSize);
1983 getRenderEngine().genTextures(refillCount, mTexturePool.data() + offset);
1984 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza67765d82019-05-07 14:58:27 -07001985 } else if (mTexturePool.size() > mTexturePoolSize) {
1986 const size_t deleteCount = mTexturePool.size() - mTexturePoolSize;
1987 const size_t offset = mTexturePoolSize;
1988 getRenderEngine().deleteTextures(deleteCount, mTexturePool.data() + offset);
1989 mTexturePool.resize(mTexturePoolSize);
1990 ATRACE_INT("TexturePoolSize", mTexturePool.size());
Dan Stoza436ccf32018-06-21 12:10:12 -07001991 }
1992 }
Marissa Walle2ffb422018-10-12 11:33:52 -07001993
Ady Abrahambe0f9482019-04-24 15:41:53 -07001994 mTransactionCompletedThread.addPresentFence(mPreviousPresentFences[0]);
Marissa Wallefb71af2019-06-27 14:45:53 -07001995 mTransactionCompletedThread.sendCallbacks();
Ady Abraham8164d482019-01-11 14:47:59 -08001996
Kevin DuBois413287f2019-02-25 08:46:47 -08001997 if (mLumaSampling && mRegionSamplingThread) {
1998 mRegionSamplingThread->notifyNewContent();
Dan Stozaec460082018-12-17 15:35:09 -08001999 }
Dan Stoza45de5ba2019-04-25 14:12:09 -07002000
2001 // Even though ATRACE_INT64 already checks if tracing is enabled, it doesn't prevent the
2002 // side-effect of getTotalSize(), so we check that again here
2003 if (ATRACE_ENABLED()) {
2004 ATRACE_INT64("Total Buffer Size", GraphicBufferAllocator::get().getTotalSize());
2005 }
Mathias Agopiancd60f992012-08-16 16:28:27 -07002006}
2007
Vishnu Nair4351ad52019-02-11 14:13:02 -08002008void SurfaceFlinger::computeLayerBounds() {
2009 for (const auto& pair : mDisplays) {
2010 const auto& displayDevice = pair.second;
2011 const auto display = displayDevice->getCompositionDisplay();
2012 for (const auto& layer : mDrawingState.layersSortedByZ) {
2013 // only consider the layers on the given layer stack
2014 if (!display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Vishnu Nair01ace762019-02-12 14:25:24 -08002015 continue;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002016 }
2017
Vishnu Nairc97b8db2019-10-29 18:19:35 -07002018 layer->computeBounds(displayDevice->getViewport().toFloatRect(), ui::Transform(),
2019 0.f /* shadowRadius */);
Vishnu Nair4351ad52019-02-11 14:13:02 -08002020 }
2021 }
2022}
2023
David Sodmanfa9b2af2017-12-24 13:28:59 -08002024void SurfaceFlinger::postFrame()
2025{
2026 // |mStateLock| not needed as we are on the main thread
Dominik Laskowski075d3172018-05-24 15:50:06 -07002027 const auto display = getDefaultDisplayDeviceLocked();
2028 if (display && getHwComposer().isConnected(*display->getId())) {
2029 uint32_t flipCount = display->getPageFlipCount();
David Sodmanfa9b2af2017-12-24 13:28:59 -08002030 if (flipCount % LOG_FRAME_STATS_PERIOD == 0) {
2031 logFrameStats();
2032 }
2033 }
2034}
2035
Mathias Agopian87baae12012-07-31 12:38:26 -07002036void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002037{
Mathias Agopian841cde52012-03-01 15:44:37 -08002038 ATRACE_CALL();
2039
Mathias Agopian7cc6df52013-06-05 14:30:54 -07002040 // here we keep a copy of the drawing state (that is the state that's
2041 // going to be overwritten by handleTransactionLocked()) outside of
2042 // mStateLock so that the side-effects of the State assignment
2043 // don't happen with mStateLock held (which can cause deadlocks).
2044 State drawingState(mDrawingState);
2045
Mathias Agopianca4d3602011-05-19 15:38:14 -07002046 Mutex::Autolock _l(mStateLock);
Dominik Laskowski9dab3432019-03-27 13:21:10 -07002047 mDebugInTransaction = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002048
Mathias Agopianca4d3602011-05-19 15:38:14 -07002049 // Here we're guaranteed that some transaction flags are set
2050 // so we can call handleTransactionLocked() unconditionally.
2051 // We call getTransactionFlags(), which will also clear the flags,
2052 // with mStateLock held to guarantee that mCurrentState won't change
2053 // until the transaction is committed.
Mathias Agopian4da75192010-08-10 17:19:56 -07002054
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002055 mVSyncModulator->onTransactionHandled();
Mathias Agopiane57f2922012-08-09 16:29:12 -07002056 transactionFlags = getTransactionFlags(eTransactionMask);
Mathias Agopian87baae12012-07-31 12:38:26 -07002057 handleTransactionLocked(transactionFlags);
Mathias Agopiandea20b12011-05-03 17:04:02 -07002058
Mathias Agopianca4d3602011-05-19 15:38:14 -07002059 mDebugInTransaction = 0;
2060 invalidateHwcGeometry();
2061 // here the transaction has been committed
Mathias Agopian3d579642009-06-04 18:46:21 -07002062}
2063
Lloyd Piqueba04e622017-12-14 17:11:26 -08002064void SurfaceFlinger::processDisplayHotplugEventsLocked() {
2065 for (const auto& event : mPendingHotplugEvents) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002066 const std::optional<DisplayIdentificationInfo> info =
2067 getHwComposer().onHotplug(event.hwcDisplayId, event.connection);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002068
Dominik Laskowski075d3172018-05-24 15:50:06 -07002069 if (!info) {
Lloyd Piqueba04e622017-12-14 17:11:26 -08002070 continue;
2071 }
2072
Lloyd Piqueba04e622017-12-14 17:11:26 -08002073 if (event.connection == HWC2::Connection::Connected) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002074 if (!mPhysicalDisplayTokens.count(info->id)) {
Dominik Laskowski34157762018-10-31 13:07:19 -07002075 ALOGV("Creating display %s", to_string(info->id).c_str());
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002076 if (event.hwcDisplayId == getHwComposer().getInternalHwcDisplayId()) {
2077 initScheduler(info->id);
2078 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002079 mPhysicalDisplayTokens[info->id] = new BBinder();
2080 DisplayDeviceState state;
2081 state.displayId = info->id;
2082 state.isSecure = true; // All physical displays are currently considered secure.
2083 state.displayName = info->name;
2084 mCurrentState.displays.add(mPhysicalDisplayTokens[info->id], state);
2085 mInterceptor->saveDisplayCreation(state);
Steven Thomaseb6d2052018-03-20 15:40:48 -07002086 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002087 } else {
Dominik Laskowski34157762018-10-31 13:07:19 -07002088 ALOGV("Removing display %s", to_string(info->id).c_str());
Lloyd Piqueba04e622017-12-14 17:11:26 -08002089
Dominik Laskowski075d3172018-05-24 15:50:06 -07002090 ssize_t index = mCurrentState.displays.indexOfKey(mPhysicalDisplayTokens[info->id]);
2091 if (index >= 0) {
2092 const DisplayDeviceState& state = mCurrentState.displays.valueAt(index);
2093 mInterceptor->saveDisplayDeletion(state.sequenceId);
2094 mCurrentState.displays.removeItemsAt(index);
Lloyd Piquefcd86612017-12-14 17:15:36 -08002095 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002096 mPhysicalDisplayTokens.erase(info->id);
Lloyd Piqueba04e622017-12-14 17:11:26 -08002097 }
2098
2099 processDisplayChangesLocked();
2100 }
2101
2102 mPendingHotplugEvents.clear();
2103}
2104
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002105void SurfaceFlinger::dispatchDisplayHotplugEvent(PhysicalDisplayId displayId, bool connected) {
Dominik Laskowski98041832019-08-01 18:35:59 -07002106 mScheduler->onHotplugReceived(mAppConnectionHandle, displayId, connected);
2107 mScheduler->onHotplugReceived(mSfConnectionHandle, displayId, connected);
Dominik Laskowski1eba0202019-01-24 09:14:40 -08002108}
2109
Lloyd Pique99d3da52018-01-22 17:48:03 -08002110sp<DisplayDevice> SurfaceFlinger::setupNewDisplayDeviceInternal(
Dominik Laskowski075d3172018-05-24 15:50:06 -07002111 const wp<IBinder>& displayToken, const std::optional<DisplayId>& displayId,
Lloyd Pique542307f2018-10-19 13:24:08 -07002112 const DisplayDeviceState& state, const sp<compositionengine::DisplaySurface>& dispSurface,
Dominik Laskowski075d3172018-05-24 15:50:06 -07002113 const sp<IGraphicBufferProducer>& producer) {
2114 DisplayDeviceCreationArgs creationArgs(this, displayToken, displayId);
Dominik Laskowskie9774092018-12-11 10:04:24 -08002115 creationArgs.sequenceId = state.sequenceId;
Dominik Laskowski075d3172018-05-24 15:50:06 -07002116 creationArgs.isVirtual = state.isVirtual();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002117 creationArgs.isSecure = state.isSecure;
2118 creationArgs.displaySurface = dispSurface;
2119 creationArgs.hasWideColorGamut = false;
2120 creationArgs.supportedPerFrameMetadata = 0;
Lloyd Pique688abd42019-02-15 15:42:24 -08002121 creationArgs.powerAdvisor = displayId ? &mPowerAdvisor : nullptr;
Peiyong Lin136fbbc2018-04-17 15:09:44 -07002122
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002123 const bool isInternalDisplay = displayId && displayId == getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07002124 creationArgs.isPrimary = isInternalDisplay;
2125
2126 if (useColorManagement && displayId) {
2127 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002128 for (ColorMode colorMode : modes) {
Peiyong Linfca547f2018-07-09 13:03:33 -07002129 if (isWideColorMode(colorMode)) {
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002130 creationArgs.hasWideColorGamut = true;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002131 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002132
Dominik Laskowski7e045462018-05-30 13:02:02 -07002133 std::vector<RenderIntent> renderIntents =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002134 getHwComposer().getRenderIntents(*displayId, colorMode);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002135 creationArgs.hwcColorModes.emplace(colorMode, renderIntents);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002136 }
tangrobin6753a022018-08-10 10:58:54 +08002137 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002138
Dominik Laskowski075d3172018-05-24 15:50:06 -07002139 if (displayId) {
2140 getHwComposer().getHdrCapabilities(*displayId, &creationArgs.hdrCapabilities);
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002141 creationArgs.supportedPerFrameMetadata =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002142 getHwComposer().getSupportedPerFrameMetadata(*displayId);
Chia-I Wu0f509fb2018-06-21 15:52:50 +08002143 }
Lloyd Pique99d3da52018-01-22 17:48:03 -08002144
Lloyd Pique90c115d2018-09-18 21:39:42 -07002145 auto nativeWindowSurface = getFactory().createNativeWindowSurface(producer);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002146 auto nativeWindow = nativeWindowSurface->getNativeWindow();
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002147 creationArgs.nativeWindow = nativeWindow;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002148
Lloyd Pique99d3da52018-01-22 17:48:03 -08002149 // Make sure that composition can never be stalled by a virtual display
2150 // consumer that isn't processing buffers fast enough. We have to do this
Alec Mouri0a9c7b82018-11-16 13:05:25 -08002151 // here, in case the display is composed entirely by HWC.
Dominik Laskowski281644e2018-04-19 15:47:35 -07002152 if (state.isVirtual()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002153 nativeWindow->setSwapInterval(nativeWindow.get(), 0);
2154 }
2155
Dominik Laskowski075d3172018-05-24 15:50:06 -07002156 creationArgs.displayInstallOrientation =
2157 isInternalDisplay ? primaryDisplayOrientation : DisplayState::eOrientationDefault;
Chia-I Wua02871c2018-08-27 14:38:23 -07002158
Lloyd Pique99d3da52018-01-22 17:48:03 -08002159 // virtual displays are always considered enabled
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002160 creationArgs.initialPowerMode = state.isVirtual() ? HWC_POWER_MODE_NORMAL : HWC_POWER_MODE_OFF;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002161
Lloyd Pique90c115d2018-09-18 21:39:42 -07002162 sp<DisplayDevice> display = getFactory().createDisplayDevice(std::move(creationArgs));
Lloyd Pique99d3da52018-01-22 17:48:03 -08002163
2164 if (maxFrameBufferAcquiredBuffers >= 3) {
2165 nativeWindowSurface->preallocateBuffers();
2166 }
2167
2168 ColorMode defaultColorMode = ColorMode::NATIVE;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08002169 Dataspace defaultDataSpace = Dataspace::UNKNOWN;
Lloyd Pique2eef1d22018-09-18 21:30:04 -07002170 if (display->hasWideColorGamut()) {
Lloyd Pique99d3da52018-01-22 17:48:03 -08002171 defaultColorMode = ColorMode::SRGB;
Peiyong Lin14724e62018-12-05 07:27:30 -08002172 defaultDataSpace = Dataspace::V0_SRGB;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002173 }
Lloyd Pique6a3b4462019-03-07 20:58:12 -08002174 display->getCompositionDisplay()->setColorProfile(
2175 compositionengine::Output::ColorProfile{defaultColorMode, defaultDataSpace,
2176 RenderIntent::COLORIMETRIC,
2177 Dataspace::UNKNOWN});
Dominik Laskowski075d3172018-05-24 15:50:06 -07002178 if (!state.isVirtual()) {
2179 LOG_ALWAYS_FATAL_IF(!displayId);
2180 display->setActiveConfig(getHwComposer().getActiveConfigIndex(*displayId));
Lloyd Pique3c085a02018-05-09 19:38:32 -07002181 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07002182
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002183 display->setLayerStack(state.layerStack);
2184 display->setProjection(state.orientation, state.viewport, state.frame);
2185 display->setDisplayName(state.displayName);
Lloyd Pique99d3da52018-01-22 17:48:03 -08002186
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002187 return display;
Lloyd Pique99d3da52018-01-22 17:48:03 -08002188}
2189
Lloyd Pique347200f2017-12-14 17:00:15 -08002190void SurfaceFlinger::processDisplayChangesLocked() {
2191 // here we take advantage of Vector's copy-on-write semantics to
2192 // improve performance by skipping the transaction entirely when
2193 // know that the lists are identical
2194 const KeyedVector<wp<IBinder>, DisplayDeviceState>& curr(mCurrentState.displays);
2195 const KeyedVector<wp<IBinder>, DisplayDeviceState>& draw(mDrawingState.displays);
2196 if (!curr.isIdenticalTo(draw)) {
2197 mVisibleRegionsDirty = true;
2198 const size_t cc = curr.size();
2199 size_t dc = draw.size();
2200
2201 // find the displays that were removed
2202 // (ie: in drawing state but not in current state)
2203 // also handle displays that changed
2204 // (ie: displays that are in both lists)
2205 for (size_t i = 0; i < dc;) {
2206 const ssize_t j = curr.indexOfKey(draw.keyAt(i));
2207 if (j < 0) {
2208 // in drawing state but not in current state
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002209 if (const auto display = getDisplayDeviceLocked(draw.keyAt(i))) {
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002210 // Save display ID before disconnecting.
2211 const auto displayId = display->getId();
Lloyd Pique45a165a2018-10-19 11:54:47 -07002212 display->disconnect();
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002213
2214 if (!display->isVirtual()) {
2215 LOG_ALWAYS_FATAL_IF(!displayId);
2216 dispatchDisplayHotplugEvent(displayId->value, false);
2217 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002218 }
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002219
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002220 mDisplays.erase(draw.keyAt(i));
Lloyd Pique347200f2017-12-14 17:00:15 -08002221 } else {
2222 // this display is in both lists. see if something changed.
2223 const DisplayDeviceState& state(curr[j]);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002224 const wp<IBinder>& displayToken = curr.keyAt(j);
Lloyd Pique347200f2017-12-14 17:00:15 -08002225 const sp<IBinder> state_binder = IInterface::asBinder(state.surface);
2226 const sp<IBinder> draw_binder = IInterface::asBinder(draw[i].surface);
2227 if (state_binder != draw_binder) {
2228 // changing the surface is like destroying and
2229 // recreating the DisplayDevice, so we just remove it
2230 // from the drawing state, so that it get re-added
2231 // below.
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002232 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique45a165a2018-10-19 11:54:47 -07002233 display->disconnect();
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002234 }
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002235 mDisplays.erase(displayToken);
Lloyd Pique347200f2017-12-14 17:00:15 -08002236 mDrawingState.displays.removeItemsAt(i);
2237 dc--;
2238 // at this point we must loop to the next item
2239 continue;
2240 }
2241
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002242 if (const auto display = getDisplayDeviceLocked(displayToken)) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002243 if (state.layerStack != draw[i].layerStack) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002244 display->setLayerStack(state.layerStack);
Lloyd Pique347200f2017-12-14 17:00:15 -08002245 }
2246 if ((state.orientation != draw[i].orientation) ||
2247 (state.viewport != draw[i].viewport) || (state.frame != draw[i].frame)) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002248 display->setProjection(state.orientation, state.viewport, state.frame);
Lloyd Pique347200f2017-12-14 17:00:15 -08002249 }
2250 if (state.width != draw[i].width || state.height != draw[i].height) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002251 display->setDisplaySize(state.width, state.height);
Lloyd Pique347200f2017-12-14 17:00:15 -08002252 }
2253 }
2254 }
2255 ++i;
2256 }
2257
2258 // find displays that were added
2259 // (ie: in current state but not in drawing state)
2260 for (size_t i = 0; i < cc; i++) {
2261 if (draw.indexOfKey(curr.keyAt(i)) < 0) {
2262 const DisplayDeviceState& state(curr[i]);
2263
Lloyd Pique542307f2018-10-19 13:24:08 -07002264 sp<compositionengine::DisplaySurface> dispSurface;
Lloyd Pique347200f2017-12-14 17:00:15 -08002265 sp<IGraphicBufferProducer> producer;
2266 sp<IGraphicBufferProducer> bqProducer;
2267 sp<IGraphicBufferConsumer> bqConsumer;
Lloyd Pique90c115d2018-09-18 21:39:42 -07002268 getFactory().createBufferQueue(&bqProducer, &bqConsumer, false);
Lloyd Pique347200f2017-12-14 17:00:15 -08002269
Dominik Laskowski075d3172018-05-24 15:50:06 -07002270 std::optional<DisplayId> displayId;
Dominik Laskowski663bd282018-04-19 15:26:54 -07002271 if (state.isVirtual()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002272 // Virtual displays without a surface are dormant:
2273 // they have external state (layer stack, projection,
2274 // etc.) but no internal state (i.e. a DisplayDevice).
2275 if (state.surface != nullptr) {
2276 // Allow VR composer to use virtual displays.
Dominik Laskowski075d3172018-05-24 15:50:06 -07002277 if (mUseHwcVirtualDisplays || getHwComposer().isUsingVrComposer()) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002278 int width = 0;
2279 int status = state.surface->query(NATIVE_WINDOW_WIDTH, &width);
2280 ALOGE_IF(status != NO_ERROR, "Unable to query width (%d)", status);
2281 int height = 0;
2282 status = state.surface->query(NATIVE_WINDOW_HEIGHT, &height);
2283 ALOGE_IF(status != NO_ERROR, "Unable to query height (%d)", status);
2284 int intFormat = 0;
2285 status = state.surface->query(NATIVE_WINDOW_FORMAT, &intFormat);
2286 ALOGE_IF(status != NO_ERROR, "Unable to query format (%d)", status);
Peiyong Lin34beb7a2018-03-28 11:57:12 -07002287 auto format = static_cast<ui::PixelFormat>(intFormat);
Lloyd Pique347200f2017-12-14 17:00:15 -08002288
Dominik Laskowski075d3172018-05-24 15:50:06 -07002289 displayId =
2290 getHwComposer().allocateVirtualDisplay(width, height, &format);
Lloyd Pique347200f2017-12-14 17:00:15 -08002291 }
2292
2293 // TODO: Plumb requested format back up to consumer
2294
2295 sp<VirtualDisplaySurface> vds =
Dominik Laskowski075d3172018-05-24 15:50:06 -07002296 new VirtualDisplaySurface(getHwComposer(), displayId, state.surface,
Lloyd Pique347200f2017-12-14 17:00:15 -08002297 bqProducer, bqConsumer,
2298 state.displayName);
2299
2300 dispSurface = vds;
2301 producer = vds;
2302 }
2303 } else {
2304 ALOGE_IF(state.surface != nullptr,
2305 "adding a supported display, but rendering "
2306 "surface is provided (%p), ignoring it",
2307 state.surface.get());
2308
Dominik Laskowski075d3172018-05-24 15:50:06 -07002309 displayId = state.displayId;
2310 LOG_ALWAYS_FATAL_IF(!displayId);
2311 dispSurface = new FramebufferSurface(getHwComposer(), *displayId, bqConsumer);
Lloyd Pique347200f2017-12-14 17:00:15 -08002312 producer = bqProducer;
2313 }
2314
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002315 const wp<IBinder>& displayToken = curr.keyAt(i);
Lloyd Pique347200f2017-12-14 17:00:15 -08002316 if (dispSurface != nullptr) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002317 mDisplays.emplace(displayToken,
Dominik Laskowski7e045462018-05-30 13:02:02 -07002318 setupNewDisplayDeviceInternal(displayToken, displayId, state,
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002319 dispSurface, producer));
Dominik Laskowski663bd282018-04-19 15:26:54 -07002320 if (!state.isVirtual()) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07002321 LOG_ALWAYS_FATAL_IF(!displayId);
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08002322 dispatchDisplayHotplugEvent(displayId->value, true);
Lloyd Pique347200f2017-12-14 17:00:15 -08002323 }
2324 }
2325 }
2326 }
2327 }
Lloyd Piqueba04e622017-12-14 17:11:26 -08002328
2329 mDrawingState.displays = mCurrentState.displays;
Lloyd Pique347200f2017-12-14 17:00:15 -08002330}
2331
Mathias Agopian87baae12012-07-31 12:38:26 -07002332void SurfaceFlinger::handleTransactionLocked(uint32_t transactionFlags)
Mathias Agopian3d579642009-06-04 18:46:21 -07002333{
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002334 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2335
Dan Stoza7dde5992015-05-22 09:51:44 -07002336 // Notify all layers of available frames
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002337 mCurrentState.traverseInZOrder([expectedPresentTime](Layer* layer) {
2338 layer->notifyAvailableFrames(expectedPresentTime);
Robert Carr2047fae2016-11-28 14:09:09 -08002339 });
Dan Stoza7dde5992015-05-22 09:51:44 -07002340
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002341 /*
2342 * Traversal of the children
2343 * (perform the transaction for each of them if needed)
2344 */
2345
Marissa Wall06255332019-03-27 13:48:27 -07002346 if ((transactionFlags & eTraversalNeeded) || mTraversalNeededMainThread) {
Robert Carr2047fae2016-11-28 14:09:09 -08002347 mCurrentState.traverseInZOrder([&](Layer* layer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002348 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
Robert Carr2047fae2016-11-28 14:09:09 -08002349 if (!trFlags) return;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002350
2351 const uint32_t flags = layer->doTransaction(0);
2352 if (flags & Layer::eVisibleRegion)
2353 mVisibleRegionsDirty = true;
Robert Carr720e5062018-07-30 17:45:14 -07002354
2355 if (flags & Layer::eInputInfoChanged) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002356 mInputInfoChanged = true;
Robert Carr720e5062018-07-30 17:45:14 -07002357 }
Robert Carr2047fae2016-11-28 14:09:09 -08002358 });
Marissa Wall06255332019-03-27 13:48:27 -07002359 mTraversalNeededMainThread = false;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002360 }
2361
2362 /*
Mathias Agopian3559b072012-08-15 13:46:03 -07002363 * Perform display own transactions if needed
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002364 */
2365
Mathias Agopiane57f2922012-08-09 16:29:12 -07002366 if (transactionFlags & eDisplayTransactionNeeded) {
Lloyd Pique347200f2017-12-14 17:00:15 -08002367 processDisplayChangesLocked();
Lloyd Piqueba04e622017-12-14 17:11:26 -08002368 processDisplayHotplugEventsLocked();
Mathias Agopian3559b072012-08-15 13:46:03 -07002369 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002370
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002371 if (transactionFlags & (eDisplayLayerStackChanged|eDisplayTransactionNeeded)) {
Mathias Agopian84300952012-11-21 16:02:13 -08002372 // The transform hint might have changed for some layers
2373 // (either because a display has changed, or because a layer
2374 // as changed).
2375 //
2376 // Walk through all the layers in currentLayers,
2377 // and update their transform hint.
2378 //
2379 // If a layer is visible only on a single display, then that
2380 // display is used to calculate the hint, otherwise we use the
2381 // default display.
2382 //
Lloyd Piquec29e4c62019-03-07 21:48:19 -08002383 // NOTE: we do this here, rather than when presenting the display so that
Mathias Agopian84300952012-11-21 16:02:13 -08002384 // the hint is set before we acquire a buffer from the surface texture.
2385 //
2386 // NOTE: layer transactions have taken place already, so we use their
2387 // drawing state. However, SurfaceFlinger's own transaction has not
2388 // happened yet, so we must use the current state layer list
2389 // (soon to become the drawing state list).
2390 //
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002391 sp<const DisplayDevice> hintDisplay;
Mathias Agopian84300952012-11-21 16:02:13 -08002392 uint32_t currentlayerStack = 0;
Robert Carr2047fae2016-11-28 14:09:09 -08002393 bool first = true;
2394 mCurrentState.traverseInZOrder([&](Layer* layer) {
Mathias Agopian84300952012-11-21 16:02:13 -08002395 // NOTE: we rely on the fact that layers are sorted by
2396 // layerStack first (so we don't have to traverse the list
2397 // of displays for every layer).
Robert Carr1f0a16a2016-10-24 16:27:39 -07002398 uint32_t layerStack = layer->getLayerStack();
Robert Carr2047fae2016-11-28 14:09:09 -08002399 if (first || currentlayerStack != layerStack) {
Mathias Agopian84300952012-11-21 16:02:13 -08002400 currentlayerStack = layerStack;
2401 // figure out if this layerstack is mirrored
2402 // (more than one display) if so, pick the default display,
2403 // if not, pick the only display it's on.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002404 hintDisplay = nullptr;
2405 for (const auto& [token, display] : mDisplays) {
Lloyd Piqueef36b002019-01-23 17:52:04 -08002406 if (display->getCompositionDisplay()
2407 ->belongsInOutput(layer->getLayerStack(),
2408 layer->getPrimaryDisplayOnly())) {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002409 if (hintDisplay) {
2410 hintDisplay = nullptr;
Mathias Agopian84300952012-11-21 16:02:13 -08002411 break;
Dominik Laskowskieecd6592018-05-29 10:25:41 -07002412 } else {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002413 hintDisplay = display;
Mathias Agopian84300952012-11-21 16:02:13 -08002414 }
2415 }
2416 }
2417 }
Chet Haase91d25932013-04-11 15:24:55 -07002418
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002419 if (!hintDisplay) {
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002420 // NOTE: TEMPORARY FIX ONLY. Real fix should cause layers to
2421 // redraw after transform hint changes. See bug 8508397.
Robert Carr56a0b9a2017-12-04 16:06:13 -08002422
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002423 // could be null when this layer is using a layerStack
2424 // that is not visible on any display. Also can occur at
2425 // screen off/on times.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002426 hintDisplay = getDefaultDisplayDeviceLocked();
Mathias Agopian84300952012-11-21 16:02:13 -08002427 }
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002428
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002429 // could be null if there is no display available at all to get
Lloyd Piqued432a7c2018-03-23 16:05:31 -07002430 // the transform hint from.
Dominik Laskowski9fae1022018-05-29 13:17:40 -07002431 if (hintDisplay) {
2432 layer->updateTransformHint(hintDisplay);
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08002433 }
Robert Carr2047fae2016-11-28 14:09:09 -08002434
2435 first = false;
2436 });
Mathias Agopian84300952012-11-21 16:02:13 -08002437 }
2438
2439
Mathias Agopian3559b072012-08-15 13:46:03 -07002440 /*
2441 * Perform our own transaction if needed
2442 */
Robert Carr1f0a16a2016-10-24 16:27:39 -07002443
2444 if (mLayersAdded) {
2445 mLayersAdded = false;
2446 // Layers have been added.
Mathias Agopian3559b072012-08-15 13:46:03 -07002447 mVisibleRegionsDirty = true;
2448 }
2449
2450 // some layers might have been removed, so
2451 // we need to update the regions they're exposing.
2452 if (mLayersRemoved) {
2453 mLayersRemoved = false;
2454 mVisibleRegionsDirty = true;
Robert Carr2047fae2016-11-28 14:09:09 -08002455 mDrawingState.traverseInZOrder([&](Layer* layer) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002456 if (mLayersPendingRemoval.indexOf(layer) >= 0) {
Mathias Agopian3559b072012-08-15 13:46:03 -07002457 // this layer is not visible anymore
Robert Carr1f0a16a2016-10-24 16:27:39 -07002458 Region visibleReg;
Vishnu Nair4351ad52019-02-11 14:13:02 -08002459 visibleReg.set(layer->getScreenBounds());
Chia-I Wuab0c3192017-08-01 11:29:00 -07002460 invalidateLayerStack(layer, visibleReg);
Mathias Agopian0aa758d2009-04-22 15:23:34 -07002461 }
Robert Carr2047fae2016-11-28 14:09:09 -08002462 });
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002463 }
2464
Vishnu Nairec0ab382019-02-13 15:32:56 -08002465 commitInputWindowCommands();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002466 commitTransaction();
Riley Andrews03414a12014-07-01 14:22:59 -07002467}
2468
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002469void SurfaceFlinger::updateInputFlinger() {
Robert Carr720e5062018-07-30 17:45:14 -07002470 ATRACE_CALL();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002471 if (!mInputFlinger) {
Vishnu Nairde19f852018-12-18 16:11:53 -08002472 return;
2473 }
2474
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002475 if (mVisibleRegionsDirty || mInputInfoChanged) {
2476 mInputInfoChanged = false;
2477 updateInputWindowInfo();
chaviw95ef3c42019-02-14 10:55:09 -08002478 } else if (mInputWindowCommands.syncInputWindows) {
2479 // If the caller requested to sync input windows, but there are no
2480 // changes to input windows, notify immediately.
2481 setInputWindowsFinished();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002482 }
2483
Arthur Hung6cbb9752019-09-05 16:38:18 +08002484 mInputWindowCommands.clear();
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002485}
2486
2487void SurfaceFlinger::updateInputWindowInfo() {
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002488 std::vector<InputWindowInfo> inputHandles;
Robert Carr720e5062018-07-30 17:45:14 -07002489
2490 mDrawingState.traverseInReverseZOrder([&](Layer* layer) {
2491 if (layer->hasInput()) {
Vishnu Nair51625fa2018-12-06 13:54:33 -08002492 // When calculating the screen bounds we ignore the transparent region since it may
2493 // result in an unwanted offset.
Arthur Hung7c3ae9c2019-03-11 11:23:03 +08002494 inputHandles.push_back(layer->fillInputInfo());
Robert Carr720e5062018-07-30 17:45:14 -07002495 }
2496 });
chaviw291d88a2019-02-14 10:33:58 -08002497
2498 mInputFlinger->setInputWindows(inputHandles,
2499 mInputWindowCommands.syncInputWindows ? mSetInputWindowsListener
2500 : nullptr);
Robert Carr720e5062018-07-30 17:45:14 -07002501}
2502
Vishnu Nairec0ab382019-02-13 15:32:56 -08002503void SurfaceFlinger::commitInputWindowCommands() {
chaviw4fe36852019-04-15 16:25:49 -07002504 mInputWindowCommands = mPendingInputWindowCommands;
Vishnu Nairec0ab382019-02-13 15:32:56 -08002505 mPendingInputWindowCommands.clear();
2506}
2507
Riley Andrews03414a12014-07-01 14:22:59 -07002508void SurfaceFlinger::updateCursorAsync()
2509{
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002510 compositionengine::CompositionRefreshArgs refreshArgs;
2511 for (const auto& [_, display] : mDisplays) {
2512 if (display->getId()) {
2513 refreshArgs.outputs.push_back(display->getCompositionDisplay());
Riley Andrews03414a12014-07-01 14:22:59 -07002514 }
2515 }
Lloyd Piquec7b0c752019-03-07 20:59:59 -08002516
2517 mCompositionEngine->updateCursorAsync(refreshArgs);
Mathias Agopian4fec8732012-06-29 14:12:52 -07002518}
2519
Steven Thomas2bbaabe2019-08-28 16:08:35 -07002520void SurfaceFlinger::initScheduler(DisplayId primaryDisplayId) {
2521 if (mScheduler) {
2522 // In practice it's not allowed to hotplug in/out the primary display once it's been
2523 // connected during startup, but some tests do it, so just warn and return.
2524 ALOGW("Can't re-init scheduler");
2525 return;
2526 }
2527
2528 int currentConfig = getHwComposer().getActiveConfigIndex(primaryDisplayId);
2529 mRefreshRateConfigs =
2530 std::make_unique<scheduler::RefreshRateConfigs>(refresh_rate_switching(false),
2531 getHwComposer().getConfigs(
2532 primaryDisplayId),
2533 currentConfig);
2534 mRefreshRateStats =
2535 std::make_unique<scheduler::RefreshRateStats>(*mRefreshRateConfigs, *mTimeStats,
2536 currentConfig, HWC_POWER_MODE_OFF);
2537 mRefreshRateStats->setConfigMode(currentConfig);
2538
2539 // start the EventThread
2540 mScheduler =
2541 getFactory().createScheduler([this](bool enabled) { setPrimaryVsyncEnabled(enabled); },
2542 *mRefreshRateConfigs);
2543 mAppConnectionHandle =
2544 mScheduler->createConnection("app", mPhaseOffsets->getCurrentAppOffset(),
2545 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2546 impl::EventThread::InterceptVSyncsCallback());
2547 mSfConnectionHandle =
2548 mScheduler->createConnection("sf", mPhaseOffsets->getCurrentSfOffset(),
2549 mPhaseOffsets->getOffsetThresholdForNextVsync(),
2550 [this](nsecs_t timestamp) {
2551 mInterceptor->saveVSyncEvent(timestamp);
2552 });
2553
2554 mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
2555 mVSyncModulator.emplace(*mScheduler, mAppConnectionHandle, mSfConnectionHandle,
2556 mPhaseOffsets->getCurrentOffsets());
2557
2558 mRegionSamplingThread =
2559 new RegionSamplingThread(*this, *mScheduler,
2560 RegionSamplingThread::EnvironmentTimingTunables());
2561
2562 mScheduler->setChangeRefreshRateCallback(
2563 [this](RefreshRateType type, Scheduler::ConfigEvent event) {
2564 Mutex::Autolock lock(mStateLock);
2565 setRefreshRateTo(type, event);
2566 });
2567}
2568
Mathias Agopian4fec8732012-06-29 14:12:52 -07002569void SurfaceFlinger::commitTransaction()
2570{
Lloyd Pique58e24a32019-08-01 15:50:14 -07002571 withTracingLock([this]() { commitTransactionLocked(); });
Nataniel Borges2b796da2019-02-15 13:32:18 -08002572
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002573 mTransactionPending = false;
2574 mAnimTransactionPending = false;
Mathias Agopian4fec8732012-06-29 14:12:52 -07002575 mTransactionCV.broadcast();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002576}
2577
Lloyd Pique58e24a32019-08-01 15:50:14 -07002578void SurfaceFlinger::commitTransactionLocked() {
2579 if (!mLayersPendingRemoval.isEmpty()) {
2580 // Notify removed layers now that they can't be drawn from
2581 for (const auto& l : mLayersPendingRemoval) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07002582 recordBufferingStats(l->getName(), l->getOccupancyHistory(true));
Lloyd Pique58e24a32019-08-01 15:50:14 -07002583
2584 // Ensure any buffers set to display on any children are released.
2585 if (l->isRemovedFromCurrentState()) {
2586 l->latchAndReleaseBuffer();
2587 }
2588
2589 // If the layer has been removed and has no parent, then it will not be reachable
2590 // when traversing layers on screen. Add the layer to the offscreenLayers set to
2591 // ensure we can copy its current to drawing state.
2592 if (!l->getParent()) {
2593 mOffscreenLayers.emplace(l.get());
2594 }
2595 }
2596 mLayersPendingRemoval.clear();
2597 }
2598
2599 // If this transaction is part of a window animation then the next frame
2600 // we composite should be considered an animation as well.
2601 mAnimCompositionPending = mAnimTransactionPending;
2602
2603 mDrawingState = mCurrentState;
2604 // clear the "changed" flags in current state
2605 mCurrentState.colorMatrixChanged = false;
2606
2607 mDrawingState.traverseInZOrder([&](Layer* layer) {
2608 layer->commitChildList();
2609
2610 // If the layer can be reached when traversing mDrawingState, then the layer is no
2611 // longer offscreen. Remove the layer from the offscreenLayer set.
2612 if (mOffscreenLayers.count(layer)) {
2613 mOffscreenLayers.erase(layer);
2614 }
2615 });
2616
2617 commitOffscreenLayers();
chaviw74b03172019-08-19 11:09:03 -07002618 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateMirrorInfo(); });
Lloyd Pique58e24a32019-08-01 15:50:14 -07002619}
2620
Nataniel Borges2b796da2019-02-15 13:32:18 -08002621void SurfaceFlinger::withTracingLock(std::function<void()> lockedOperation) {
2622 if (mTracingEnabledChanged) {
2623 mTracingEnabled = mTracing.isEnabled();
2624 mTracingEnabledChanged = false;
2625 }
2626
2627 // Synchronize with Tracing thread
2628 std::unique_lock<std::mutex> lock;
2629 if (mTracingEnabled) {
2630 lock = std::unique_lock<std::mutex>(mDrawingStateLock);
2631 }
2632
2633 lockedOperation();
2634
2635 // Synchronize with Tracing thread
2636 if (mTracingEnabled) {
2637 lock.unlock();
2638 }
2639}
2640
chaviw74d90ad2019-04-26 14:45:26 -07002641void SurfaceFlinger::commitOffscreenLayers() {
2642 for (Layer* offscreenLayer : mOffscreenLayers) {
2643 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [](Layer* layer) {
2644 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
2645 if (!trFlags) return;
2646
2647 layer->doTransaction(0);
2648 layer->commitChildList();
2649 });
2650 }
2651}
2652
Chia-I Wuab0c3192017-08-01 11:29:00 -07002653void SurfaceFlinger::invalidateLayerStack(const sp<const Layer>& layer, const Region& dirty) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002654 for (const auto& [token, displayDevice] : mDisplays) {
2655 auto display = displayDevice->getCompositionDisplay();
Lloyd Piqueef36b002019-01-23 17:52:04 -08002656 if (display->belongsInOutput(layer->getLayerStack(), layer->getPrimaryDisplayOnly())) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07002657 display->editState().dirtyRegion.orSelf(dirty);
Mathias Agopian92a979a2012-08-02 18:32:23 -07002658 }
2659 }
Mathias Agopian87baae12012-07-31 12:38:26 -07002660}
2661
Dan Stoza6b9454d2014-11-07 16:00:59 -08002662bool SurfaceFlinger::handlePageFlip()
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002663{
Ady Abraham09bd3922019-04-08 10:44:56 -07002664 ATRACE_CALL();
Dan Stoza9e56aa02015-11-02 13:00:03 -08002665 ALOGV("handlePageFlip");
2666
Brian Andersond6927fb2016-07-23 23:37:30 -07002667 nsecs_t latchTime = systemTime();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002668
Mathias Agopian4fec8732012-06-29 14:12:52 -07002669 bool visibleRegions = false;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002670 bool frameQueued = false;
Mike Stroyan0cd76192017-04-20 12:10:48 -06002671 bool newDataLatched = false;
Eric Penner51c59cd2014-07-28 19:51:58 -07002672
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002673 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
2674
Eric Penner51c59cd2014-07-28 19:51:58 -07002675 // Store the set of layers that need updates. This set must not change as
2676 // buffers are being latched, as this could result in a deadlock.
2677 // Example: Two producers share the same command stream and:
2678 // 1.) Layer 0 is latched
2679 // 2.) Layer 0 gets a new frame
2680 // 2.) Layer 1 gets a new frame
2681 // 3.) Layer 1 is latched.
2682 // Display is now waiting on Layer 1's frame, which is behind layer 0's
2683 // second frame. But layer 0's second frame could be waiting on display.
Robert Carr2047fae2016-11-28 14:09:09 -08002684 mDrawingState.traverseInZOrder([&](Layer* layer) {
Marissa Wallfd668622018-05-10 10:21:13 -07002685 if (layer->hasReadyFrame()) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002686 frameQueued = true;
Ana Krulec010d2192018-10-08 06:29:54 -07002687 if (layer->shouldPresentNow(expectedPresentTime)) {
Robert Carr2047fae2016-11-28 14:09:09 -08002688 mLayersWithQueuedFrames.push_back(layer);
Dan Stozaee44edd2015-03-23 15:50:23 -07002689 } else {
Ady Abraham09bd3922019-04-08 10:44:56 -07002690 ATRACE_NAME("!layer->shouldPresentNow()");
Dan Stozaee44edd2015-03-23 15:50:23 -07002691 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002692 }
Dan Stozaee44edd2015-03-23 15:50:23 -07002693 } else {
2694 layer->useEmptyDamage();
Dan Stoza6b9454d2014-11-07 16:00:59 -08002695 }
Robert Carr2047fae2016-11-28 14:09:09 -08002696 });
2697
chaviw49a108c2019-08-12 11:23:06 -07002698 // The client can continue submitting buffers for offscreen layers, but they will not
2699 // be shown on screen. Therefore, we need to latch and release buffers of offscreen
2700 // layers to ensure dequeueBuffer doesn't block indefinitely.
2701 for (Layer* offscreenLayer : mOffscreenLayers) {
2702 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing,
2703 [&](Layer* l) { l->latchAndReleaseBuffer(); });
2704 }
2705
Lloyd Piquef2c79392018-12-20 16:23:33 -08002706 if (!mLayersWithQueuedFrames.empty()) {
2707 // mStateLock is needed for latchBuffer as LayerRejecter::reject()
2708 // writes to Layer current state. See also b/119481871
2709 Mutex::Autolock lock(mStateLock);
2710
2711 for (auto& layer : mLayersWithQueuedFrames) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002712 if (layer->latchBuffer(visibleRegions, latchTime, expectedPresentTime)) {
Vishnu Nair6194e2e2019-02-06 12:58:39 -08002713 mLayersPendingRefresh.push_back(layer);
2714 }
Lloyd Piquef2c79392018-12-20 16:23:33 -08002715 layer->useSurfaceDamage();
Lloyd Piquef2c79392018-12-20 16:23:33 -08002716 if (layer->isBufferLatched()) {
2717 newDataLatched = true;
2718 }
Mike Stroyan0cd76192017-04-20 12:10:48 -06002719 }
Mathias Agopian4fec8732012-06-29 14:12:52 -07002720 }
Mathias Agopian4da75192010-08-10 17:19:56 -07002721
Mathias Agopian3b1d2b62012-07-11 13:48:17 -07002722 mVisibleRegionsDirty |= visibleRegions;
Dan Stoza6b9454d2014-11-07 16:00:59 -08002723
2724 // If we will need to wake up at some time in the future to deal with a
2725 // queued frame that shouldn't be displayed during this vsync period, wake
2726 // up during the next vsync period to check again.
Chia-I Wua36bf922017-06-30 12:51:05 -07002727 if (frameQueued && (mLayersWithQueuedFrames.empty() || !newDataLatched)) {
Dan Stoza6b9454d2014-11-07 16:00:59 -08002728 signalLayerUpdate();
2729 }
2730
Chia-I Wu14c9c7b2018-06-26 10:18:18 +08002731 // enter boot animation on first buffer latch
2732 if (CC_UNLIKELY(mBootStage == BootStage::BOOTLOADER && newDataLatched)) {
2733 ALOGI("Enter boot animation");
2734 mBootStage = BootStage::BOOTANIMATION;
2735 }
2736
chaviw74b03172019-08-19 11:09:03 -07002737 mDrawingState.traverseInZOrder([&](Layer* layer) { layer->updateCloneBufferInfo(); });
2738
Dan Stoza6b9454d2014-11-07 16:00:59 -08002739 // Only continue with the refresh if there is actually new work to do
Mike Stroyan0cd76192017-04-20 12:10:48 -06002740 return !mLayersWithQueuedFrames.empty() && newDataLatched;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002741}
2742
Mathias Agopianad456f92011-01-13 17:53:01 -08002743void SurfaceFlinger::invalidateHwcGeometry()
2744{
Dan Stoza9e56aa02015-11-02 13:00:03 -08002745 mGeometryInvalid = true;
Mathias Agopianad456f92011-01-13 17:53:01 -08002746}
2747
Robert Carrc0df3122019-04-11 13:18:21 -07002748status_t SurfaceFlinger::addClientLayer(const sp<Client>& client, const sp<IBinder>& handle,
2749 const sp<IGraphicBufferProducer>& gbc, const sp<Layer>& lbc,
2750 const sp<IBinder>& parentHandle,
2751 const sp<Layer>& parentLayer, bool addToCurrentState) {
Dan Stoza7d89d062015-04-30 13:29:25 -07002752 // add this layer to the current state list
2753 {
2754 Mutex::Autolock _l(mStateLock);
Robert Carrc0df3122019-04-11 13:18:21 -07002755 sp<Layer> parent;
2756 if (parentHandle != nullptr) {
2757 parent = fromHandle(parentHandle);
2758 if (parent == nullptr) {
2759 return NAME_NOT_FOUND;
2760 }
2761 } else {
2762 parent = parentLayer;
2763 }
2764
Robert Carr1f0a16a2016-10-24 16:27:39 -07002765 if (mNumLayers >= MAX_LAYERS) {
chaviweadf0d42019-08-12 13:28:29 -07002766 ALOGE("AddClientLayer failed, mNumLayers (%zu) >= MAX_LAYERS (%zu)", mNumLayers.load(),
Courtney Goeltzenleuchterab702f52017-04-19 15:14:02 -06002767 MAX_LAYERS);
Dan Stoza7d89d062015-04-30 13:29:25 -07002768 return NO_MEMORY;
2769 }
Robert Carrc0df3122019-04-11 13:18:21 -07002770
2771 mLayersByLocalBinderToken.emplace(handle->localBinder(), lbc);
2772
Robert Carrb89ea9d2018-12-10 13:01:14 -08002773 if (parent == nullptr && addToCurrentState) {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002774 mCurrentState.layersSortedByZ.add(lbc);
chaviwac841852019-01-16 16:04:43 -08002775 } else if (parent == nullptr) {
2776 lbc->onRemovedFromCurrentState();
2777 } else if (parent->isRemovedFromCurrentState()) {
2778 parent->addChild(lbc);
2779 lbc->onRemovedFromCurrentState();
Robert Carrb89ea9d2018-12-10 13:01:14 -08002780 } else {
Robert Carr1f0a16a2016-10-24 16:27:39 -07002781 parent->addChild(lbc);
2782 }
Chia-I Wu98f1c102017-05-30 14:54:08 -07002783
Yiwei Zhang243b3782018-05-15 17:40:04 -07002784 if (gbc != nullptr) {
2785 mGraphicBufferProducerList.insert(IInterface::asBinder(gbc).get());
2786 LOG_ALWAYS_FATAL_IF(mGraphicBufferProducerList.size() >
2787 mMaxGraphicBufferProducerListSize,
2788 "Suspected IGBP leak: %zu IGBPs (%zu max), %zu Layers",
2789 mGraphicBufferProducerList.size(),
chaviweadf0d42019-08-12 13:28:29 -07002790 mMaxGraphicBufferProducerListSize, mNumLayers.load());
Yiwei Zhang243b3782018-05-15 17:40:04 -07002791 }
Robert Carr1f0a16a2016-10-24 16:27:39 -07002792 mLayersAdded = true;
Dan Stoza7d89d062015-04-30 13:29:25 -07002793 }
2794
Mathias Agopian96f08192010-06-02 23:28:45 -07002795 // attach this layer to the client
Mathias Agopianac9fa422013-02-11 16:40:36 -08002796 client->attachLayer(handle, lbc);
Mathias Agopian4f113742011-05-03 16:21:41 -07002797
Dan Stoza7d89d062015-04-30 13:29:25 -07002798 return NO_ERROR;
Mathias Agopian96f08192010-06-02 23:28:45 -07002799}
2800
Fabien Sanglardc8251eb2016-12-07 13:59:48 -08002801uint32_t SurfaceFlinger::peekTransactionFlags() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002802 return mTransactionFlags;
Mathias Agopiandea20b12011-05-03 17:04:02 -07002803}
2804
Mathias Agopian3f844832013-08-07 21:24:32 -07002805uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002806 return mTransactionFlags.fetch_and(~flags) & flags;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002807}
2808
Mathias Agopian3f844832013-08-07 21:24:32 -07002809uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) {
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002810 return setTransactionFlags(flags, Scheduler::TransactionStart::NORMAL);
Dan Stoza84d619e2018-03-28 17:07:36 -07002811}
2812
2813uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags,
Ana Krulec7ecce8c2018-10-12 13:44:41 -07002814 Scheduler::TransactionStart transactionStart) {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07002815 uint32_t old = mTransactionFlags.fetch_or(flags);
Dominik Laskowskieddeda12019-07-19 11:54:13 -07002816 mVSyncModulator->setTransactionStart(transactionStart);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002817 if ((old & flags)==0) { // wake the server up
Mathias Agopian99ce5cd2012-01-31 18:24:27 -08002818 signalTransaction();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08002819 }
2820 return old;
2821}
2822
Marissa Wall713b63f2018-10-17 15:42:43 -07002823bool SurfaceFlinger::flushTransactionQueues() {
Valerie Haufce31b82019-04-30 16:41:14 -07002824 // to prevent onHandleDestroyed from being called while the lock is held,
2825 // we must keep a copy of the transactions (specifically the composer
2826 // states) around outside the scope of the lock
2827 std::vector<const TransactionState> transactions;
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002828 bool flushedATransaction = false;
Valerie Haufce31b82019-04-30 16:41:14 -07002829 {
2830 Mutex::Autolock _l(mStateLock);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002831
Valerie Haufce31b82019-04-30 16:41:14 -07002832 auto it = mTransactionQueues.begin();
2833 while (it != mTransactionQueues.end()) {
2834 auto& [applyToken, transactionQueue] = *it;
Marissa Wall713b63f2018-10-17 15:42:43 -07002835
Valerie Haufce31b82019-04-30 16:41:14 -07002836 while (!transactionQueue.empty()) {
2837 const auto& transaction = transactionQueue.front();
2838 if (!transactionIsReadyToBeApplied(transaction.desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002839 true /* useCachedExpectedPresentTime */,
Valerie Haufce31b82019-04-30 16:41:14 -07002840 transaction.states)) {
2841 setTransactionFlags(eTransactionFlushNeeded);
2842 break;
2843 }
2844 transactions.push_back(transaction);
2845 applyTransactionState(transaction.states, transaction.displays, transaction.flags,
2846 mPendingInputWindowCommands, transaction.desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002847 transaction.buffer, transaction.postTime,
2848 transaction.privileged, transaction.hasListenerCallbacks,
2849 transaction.listenerCallbacks, /*isMainThread*/ true);
Valerie Haufce31b82019-04-30 16:41:14 -07002850 transactionQueue.pop();
2851 flushedATransaction = true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002852 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002853
Valerie Haufce31b82019-04-30 16:41:14 -07002854 if (transactionQueue.empty()) {
2855 it = mTransactionQueues.erase(it);
2856 mTransactionCV.broadcast();
2857 } else {
Valerie Haue5562ec2019-05-14 12:39:16 -07002858 it = std::next(it, 1);
Valerie Haufce31b82019-04-30 16:41:14 -07002859 }
Valerie Hauf6016b62019-03-28 10:49:59 -07002860 }
Marissa Wall713b63f2018-10-17 15:42:43 -07002861 }
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002862 return flushedATransaction;
2863}
2864
2865bool SurfaceFlinger::transactionFlushNeeded() {
2866 return !mTransactionQueues.empty();
Marissa Wall713b63f2018-10-17 15:42:43 -07002867}
2868
chaviwca27f252018-02-06 16:46:39 -08002869
Marissa Wall17b4e452018-12-26 16:32:34 -08002870bool SurfaceFlinger::transactionIsReadyToBeApplied(int64_t desiredPresentTime,
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002871 bool useCachedExpectedPresentTime,
Marissa Wall17b4e452018-12-26 16:32:34 -08002872 const Vector<ComposerState>& states) {
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002873 if (!useCachedExpectedPresentTime)
2874 populateExpectedPresentTime();
2875
2876 const nsecs_t expectedPresentTime = mExpectedPresentTime.load();
Marissa Wall17b4e452018-12-26 16:32:34 -08002877 // Do not present if the desiredPresentTime has not passed unless it is more than one second
2878 // in the future. We ignore timestamps more than 1 second in the future for stability reasons.
2879 if (desiredPresentTime >= 0 && desiredPresentTime >= expectedPresentTime &&
2880 desiredPresentTime < expectedPresentTime + s2ns(1)) {
2881 return false;
2882 }
2883
Marissa Wall713b63f2018-10-17 15:42:43 -07002884 for (const ComposerState& state : states) {
2885 const layer_state_t& s = state.state;
2886 if (!(s.what & layer_state_t::eAcquireFenceChanged)) {
2887 continue;
2888 }
2889 if (s.acquireFence && s.acquireFence->getStatus() == Fence::Status::Unsignaled) {
Marissa Wall17b4e452018-12-26 16:32:34 -08002890 return false;
Marissa Wall713b63f2018-10-17 15:42:43 -07002891 }
2892 }
Marissa Wall17b4e452018-12-26 16:32:34 -08002893 return true;
Marissa Wall713b63f2018-10-17 15:42:43 -07002894}
2895
Valerie Hau9dab9732019-08-20 09:29:25 -07002896void SurfaceFlinger::setTransactionState(
2897 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2898 const sp<IBinder>& applyToken, const InputWindowCommands& inputWindowCommands,
2899 int64_t desiredPresentTime, const client_cache_t& uncacheBuffer, bool hasListenerCallbacks,
2900 const std::vector<ListenerCallbacks>& listenerCallbacks) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002901 ATRACE_CALL();
Robert Carr14167e02019-02-13 13:50:55 -08002902
Valerie Haubc6ddb12019-03-08 11:10:15 -08002903 const int64_t postTime = systemTime();
2904
Robert Carr14167e02019-02-13 13:50:55 -08002905 bool privileged = callingThreadHasUnscopedSurfaceFlingerAccess();
2906
Mathias Agopian698c0872011-06-28 19:09:31 -07002907 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07002908
Marissa Wall713b63f2018-10-17 15:42:43 -07002909 // If its TransactionQueue already has a pending TransactionState or if it is pending
Valerie Hauf6016b62019-03-28 10:49:59 -07002910 auto itr = mTransactionQueues.find(applyToken);
2911 // if this is an animation frame, wait until prior animation frame has
2912 // been applied by SF
2913 if (flags & eAnimation) {
2914 while (itr != mTransactionQueues.end()) {
2915 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
2916 if (CC_UNLIKELY(err != NO_ERROR)) {
2917 ALOGW_IF(err == TIMED_OUT,
2918 "setTransactionState timed out "
2919 "waiting for animation frame to apply");
2920 break;
2921 }
2922 itr = mTransactionQueues.find(applyToken);
2923 }
2924 }
Dominik Laskowskia8955dd2019-07-10 10:19:09 -07002925
2926 // Expected present time is computed and cached on invalidate, so it may be stale.
2927 if (itr != mTransactionQueues.end() || !transactionIsReadyToBeApplied(
2928 desiredPresentTime, false /* useCachedExpectedPresentTime */, states)) {
Robert Carr14167e02019-02-13 13:50:55 -08002929 mTransactionQueues[applyToken].emplace(states, displays, flags, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002930 uncacheBuffer, postTime, privileged,
2931 hasListenerCallbacks, listenerCallbacks);
Marissa Walle6e3c0d2019-03-29 10:28:30 -07002932 setTransactionFlags(eTransactionFlushNeeded);
Marissa Wall713b63f2018-10-17 15:42:43 -07002933 return;
2934 }
2935
Valerie Haubc6ddb12019-03-08 11:10:15 -08002936 applyTransactionState(states, displays, flags, inputWindowCommands, desiredPresentTime,
Valerie Hau9dab9732019-08-20 09:29:25 -07002937 uncacheBuffer, postTime, privileged, hasListenerCallbacks,
2938 listenerCallbacks);
Marissa Wall713b63f2018-10-17 15:42:43 -07002939}
2940
Valerie Hau9dab9732019-08-20 09:29:25 -07002941void SurfaceFlinger::applyTransactionState(
2942 const Vector<ComposerState>& states, const Vector<DisplayState>& displays, uint32_t flags,
2943 const InputWindowCommands& inputWindowCommands, const int64_t desiredPresentTime,
2944 const client_cache_t& uncacheBuffer, const int64_t postTime, bool privileged,
2945 bool hasListenerCallbacks, const std::vector<ListenerCallbacks>& listenerCallbacks,
2946 bool isMainThread) {
Marissa Wall713b63f2018-10-17 15:42:43 -07002947 uint32_t transactionFlags = 0;
2948
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002949 if (flags & eAnimation) {
2950 // For window updates that are part of an animation we must wait for
2951 // previous animation "frames" to be handled.
Valerie Hau38448362019-04-11 14:49:33 -07002952 while (!isMainThread && mAnimTransactionPending) {
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002953 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002954 if (CC_UNLIKELY(err != NO_ERROR)) {
2955 // just in case something goes wrong in SF, return to the
Jamie Gennis7c41bf72012-10-17 09:29:47 -07002956 // caller after a few seconds.
2957 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out "
2958 "waiting for previous animation frame");
Jamie Gennis2d5e2302012-10-15 18:24:43 -07002959 mAnimTransactionPending = false;
2960 break;
2961 }
2962 }
2963 }
2964
chaviwca27f252018-02-06 16:46:39 -08002965 for (const DisplayState& display : displays) {
2966 transactionFlags |= setDisplayStateLocked(display);
Jamie Gennisb8d69a52011-10-10 15:48:06 -07002967 }
2968
Valerie Hau9dab9732019-08-20 09:29:25 -07002969 // start and end registration for listeners w/ no surface so they can get their callback. Note
2970 // that listeners with SurfaceControls will start registration during setClientStateLocked
2971 // below.
2972 for (const auto& listener : listenerCallbacks) {
2973 mTransactionCompletedThread.startRegistration(listener);
2974 mTransactionCompletedThread.endRegistration(listener);
Marissa Walld600d572019-03-26 15:38:50 -07002975 }
2976
Valerie Hau9dab9732019-08-20 09:29:25 -07002977 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash> listenerCallbacksWithSurfaces;
Marissa Walle2ffb422018-10-12 11:33:52 -07002978 uint32_t clientStateFlags = 0;
chaviwca27f252018-02-06 16:46:39 -08002979 for (const ComposerState& state : states) {
Valerie Hau9dab9732019-08-20 09:29:25 -07002980 clientStateFlags |= setClientStateLocked(state, desiredPresentTime, postTime, privileged,
2981 listenerCallbacksWithSurfaces);
Marissa Wall3dad52d2019-03-22 14:03:19 -07002982 }
2983
Valerie Hau9dab9732019-08-20 09:29:25 -07002984 for (const auto& listenerCallback : listenerCallbacksWithSurfaces) {
Marissa Wallefb71af2019-06-27 14:45:53 -07002985 mTransactionCompletedThread.endRegistration(listenerCallback);
2986 }
2987
Marissa Walle2ffb422018-10-12 11:33:52 -07002988 // If the state doesn't require a traversal and there are callbacks, send them now
Valerie Hau9dab9732019-08-20 09:29:25 -07002989 if (!(clientStateFlags & eTraversalNeeded) && hasListenerCallbacks) {
Marissa Walle2ffb422018-10-12 11:33:52 -07002990 mTransactionCompletedThread.sendCallbacks();
2991 }
2992 transactionFlags |= clientStateFlags;
chaviwca27f252018-02-06 16:46:39 -08002993
chaviw273171b2018-12-26 11:46:30 -08002994 transactionFlags |= addInputWindowCommands(inputWindowCommands);
2995
Marissa Wall947d34e2019-03-29 14:03:53 -07002996 if (uncacheBuffer.isValid()) {
2997 ClientCache::getInstance().erase(uncacheBuffer);
Alec Mouri4545a8a2019-08-08 20:05:32 -07002998 getRenderEngine().unbindExternalTextureBuffer(uncacheBuffer.id);
Marissa Wall78b72202019-03-15 14:58:34 -07002999 }
3000
Jorim Jaggibdcf09c2017-08-08 15:22:08 +02003001 // If a synchronous transaction is explicitly requested without any changes, force a transaction
3002 // anyway. This can be used as a flush mechanism for previous async transactions.
3003 // Empty animation transaction can be used to simulate back-pressure, so also force a
3004 // transaction for empty animation transactions.
3005 if (transactionFlags == 0 &&
3006 ((flags & eSynchronous) || (flags & eAnimation))) {
Robert Carr2a7dbb42016-05-24 11:41:28 -07003007 transactionFlags = eTransactionNeeded;
3008 }
3009
Marissa Wall06255332019-03-27 13:48:27 -07003010 // If we are on the main thread, we are about to preform a traversal. Clear the traversal bit
3011 // so we don't have to wake up again next frame to preform an uneeded traversal.
3012 if (isMainThread && (transactionFlags & eTraversalNeeded)) {
3013 transactionFlags = transactionFlags & (~eTraversalNeeded);
3014 mTraversalNeededMainThread = true;
3015 }
3016
Mathias Agopian386aa982011-11-07 21:58:03 -08003017 if (transactionFlags) {
Lloyd Pique4dccc412018-01-22 17:21:36 -08003018 if (mInterceptor->isEnabled()) {
3019 mInterceptor->saveTransaction(states, mCurrentState.displays, displays, flags);
Irvelffc9efc2016-07-27 15:16:37 -07003020 }
Irvel468051e2016-06-13 16:44:44 -07003021
Mathias Agopian386aa982011-11-07 21:58:03 -08003022 // this triggers the transaction
Ana Krulec7ecce8c2018-10-12 13:44:41 -07003023 const auto start = (flags & eEarlyWakeup) ? Scheduler::TransactionStart::EARLY
3024 : Scheduler::TransactionStart::NORMAL;
Dan Stoza84d619e2018-03-28 17:07:36 -07003025 setTransactionFlags(transactionFlags, start);
Mathias Agopian386aa982011-11-07 21:58:03 -08003026
3027 // if this is a synchronous transaction, wait for it to take effect
3028 // before returning.
3029 if (flags & eSynchronous) {
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003030 mTransactionPending = true;
Mathias Agopian386aa982011-11-07 21:58:03 -08003031 }
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003032 if (flags & eAnimation) {
3033 mAnimTransactionPending = true;
3034 }
chaviw4fe36852019-04-15 16:25:49 -07003035 if (mPendingInputWindowCommands.syncInputWindows) {
3036 mPendingSyncInputWindows = true;
3037 }
Valerie Hau0779ded2019-03-19 12:43:04 -07003038
3039 // applyTransactionState can be called by either the main SF thread or by
3040 // another process through setTransactionState. While a given process may wish
3041 // to wait on synchronous transactions, the main SF thread should never
3042 // be blocked. Therefore, we only wait if isMainThread is false.
3043 while (!isMainThread && (mTransactionPending || mPendingSyncInputWindows)) {
Mathias Agopian386aa982011-11-07 21:58:03 -08003044 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
3045 if (CC_UNLIKELY(err != NO_ERROR)) {
3046 // just in case something goes wrong in SF, return to the
3047 // called after a few seconds.
Jamie Gennis2d5e2302012-10-15 18:24:43 -07003048 ALOGW_IF(err == TIMED_OUT, "setTransactionState timed out!");
3049 mTransactionPending = false;
chaviw95ef3c42019-02-14 10:55:09 -08003050 mPendingSyncInputWindows = false;
Mathias Agopian386aa982011-11-07 21:58:03 -08003051 break;
3052 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07003053 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003054 }
3055}
3056
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003057uint32_t SurfaceFlinger::setDisplayStateLocked(const DisplayState& s) {
3058 const ssize_t index = mCurrentState.displays.indexOfKey(s.token);
3059 if (index < 0) return 0;
Jesse Hall9a143922012-10-04 16:29:19 -07003060
Mathias Agopiane57f2922012-08-09 16:29:12 -07003061 uint32_t flags = 0;
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003062 DisplayDeviceState& state = mCurrentState.displays.editValueAt(index);
3063
3064 const uint32_t what = s.what;
3065 if (what & DisplayState::eSurfaceChanged) {
3066 if (IInterface::asBinder(state.surface) != IInterface::asBinder(s.surface)) {
3067 state.surface = s.surface;
3068 flags |= eDisplayTransactionNeeded;
Michael Lentine47e45402014-07-18 15:34:25 -07003069 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003070 }
Dominik Laskowskif07b85b2018-06-11 12:49:15 -07003071 if (what & DisplayState::eLayerStackChanged) {
3072 if (state.layerStack != s.layerStack) {
3073 state.layerStack = s.layerStack;
3074 flags |= eDisplayTransactionNeeded;
3075 }
3076 }
3077 if (what & DisplayState::eDisplayProjectionChanged) {
3078 if (state.orientation != s.orientation) {
3079 state.orientation = s.orientation;
3080 flags |= eDisplayTransactionNeeded;
3081 }
3082 if (state.frame != s.frame) {
3083 state.frame = s.frame;
3084 flags |= eDisplayTransactionNeeded;
3085 }
3086 if (state.viewport != s.viewport) {
3087 state.viewport = s.viewport;
3088 flags |= eDisplayTransactionNeeded;
3089 }
3090 }
3091 if (what & DisplayState::eDisplaySizeChanged) {
3092 if (state.width != s.width) {
3093 state.width = s.width;
3094 flags |= eDisplayTransactionNeeded;
3095 }
3096 if (state.height != s.height) {
3097 state.height = s.height;
3098 flags |= eDisplayTransactionNeeded;
3099 }
3100 }
3101
Mathias Agopiane57f2922012-08-09 16:29:12 -07003102 return flags;
3103}
3104
Robert Carr14167e02019-02-13 13:50:55 -08003105bool SurfaceFlinger::callingThreadHasUnscopedSurfaceFlingerAccess() {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003106 IPCThreadState* ipc = IPCThreadState::self();
3107 const int pid = ipc->getCallingPid();
3108 const int uid = ipc->getCallingUid();
Robert Carrd4ae7f32018-06-07 16:10:57 -07003109 if ((uid != AID_GRAPHICS && uid != AID_SYSTEM) &&
Ana Krulec13be8ad2018-08-21 02:43:56 +00003110 !PermissionCache::checkPermission(sAccessSurfaceFlinger, pid, uid)) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003111 return false;
3112 }
3113 return true;
3114}
3115
Marissa Wall3dad52d2019-03-22 14:03:19 -07003116uint32_t SurfaceFlinger::setClientStateLocked(
Valerie Hau9dab9732019-08-20 09:29:25 -07003117 const ComposerState& composerState, int64_t desiredPresentTime, int64_t postTime,
3118 bool privileged,
3119 std::unordered_set<ListenerCallbacks, ListenerCallbacksHash>& listenerCallbacks) {
chaviwca27f252018-02-06 16:46:39 -08003120 const layer_state_t& s = composerState.state;
chaviwca27f252018-02-06 16:46:39 -08003121
Valerie Hau9dab9732019-08-20 09:29:25 -07003122 for (auto& listener : s.listeners) {
3123 // note that startRegistration will not re-register if the listener has
3124 // already be registered for a prior surface control
3125 mTransactionCompletedThread.startRegistration(listener);
3126 listenerCallbacks.insert(listener);
3127 }
3128
Vishnu Nairf03652d2019-07-16 17:56:56 -07003129 sp<Layer> layer(fromHandle(s.surface));
chaviw8b3871a2017-11-01 17:41:01 -07003130 if (layer == nullptr) {
Valerie Hau9dab9732019-08-20 09:29:25 -07003131 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Wallefb71af2019-06-27 14:45:53 -07003132 mTransactionCompletedThread.registerUnpresentedCallbackHandle(
Valerie Hau9dab9732019-08-20 09:29:25 -07003133 new CallbackHandle(listener, callbackIds, s.surface));
Marissa Wall88e20482019-06-24 10:49:42 -07003134 }
chaviw8b3871a2017-11-01 17:41:01 -07003135 return 0;
3136 }
3137
chaviw8b3871a2017-11-01 17:41:01 -07003138 uint32_t flags = 0;
3139
Garfield Tan8a3083e2018-12-03 13:21:07 -08003140 const uint64_t what = s.what;
Jorim Jaggidba32732018-05-28 17:43:52 +02003141
3142 // If we are deferring transaction, make sure to push the pending state, as otherwise the
3143 // pending state will also be deferred.
Marissa Wallf58c14b2018-07-24 10:50:43 -07003144 if (what & layer_state_t::eDeferTransaction_legacy) {
Jorim Jaggidba32732018-05-28 17:43:52 +02003145 layer->pushPendingState();
3146 }
3147
chaviw8b3871a2017-11-01 17:41:01 -07003148 if (what & layer_state_t::ePositionChanged) {
chaviw214c89d2019-09-04 16:03:53 -07003149 if (layer->setPosition(s.x, s.y)) {
chaviw8b3871a2017-11-01 17:41:01 -07003150 flags |= eTraversalNeeded;
Mathias Agopiane57f2922012-08-09 16:29:12 -07003151 }
chaviw8b3871a2017-11-01 17:41:01 -07003152 }
3153 if (what & layer_state_t::eLayerChanged) {
3154 // NOTE: index needs to be calculated before we update the state
3155 const auto& p = layer->getParent();
3156 if (p == nullptr) {
chaviw64f7b422017-07-12 10:31:58 -07003157 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
chaviw8b3871a2017-11-01 17:41:01 -07003158 if (layer->setLayer(s.z) && idx >= 0) {
Mathias Agopiane57f2922012-08-09 16:29:12 -07003159 mCurrentState.layersSortedByZ.removeAt(idx);
3160 mCurrentState.layersSortedByZ.add(layer);
3161 // we need traversal (state changed)
3162 // AND transaction (list changed)
3163 flags |= eTransactionNeeded|eTraversalNeeded;
3164 }
chaviw8b3871a2017-11-01 17:41:01 -07003165 } else {
3166 if (p->setChildLayer(layer, s.z)) {
chaviw06178942017-07-27 10:25:59 -07003167 flags |= eTransactionNeeded|eTraversalNeeded;
3168 }
3169 }
chaviw8b3871a2017-11-01 17:41:01 -07003170 }
3171 if (what & layer_state_t::eRelativeLayerChanged) {
Robert Carr503c7042017-09-27 15:06:08 -07003172 // NOTE: index needs to be calculated before we update the state
3173 const auto& p = layer->getParent();
3174 if (p == nullptr) {
3175 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3176 if (layer->setRelativeLayer(s.relativeLayerHandle, s.z) && idx >= 0) {
3177 mCurrentState.layersSortedByZ.removeAt(idx);
3178 mCurrentState.layersSortedByZ.add(layer);
3179 // we need traversal (state changed)
3180 // AND transaction (list changed)
3181 flags |= eTransactionNeeded|eTraversalNeeded;
3182 }
3183 } else {
3184 if (p->setChildRelativeLayer(layer, s.relativeLayerHandle, s.z)) {
3185 flags |= eTransactionNeeded|eTraversalNeeded;
3186 }
chaviw8b3871a2017-11-01 17:41:01 -07003187 }
3188 }
3189 if (what & layer_state_t::eSizeChanged) {
3190 if (layer->setSize(s.w, s.h)) {
3191 flags |= eTraversalNeeded;
3192 }
3193 }
3194 if (what & layer_state_t::eAlphaChanged) {
3195 if (layer->setAlpha(s.alpha))
3196 flags |= eTraversalNeeded;
3197 }
3198 if (what & layer_state_t::eColorChanged) {
3199 if (layer->setColor(s.color))
3200 flags |= eTraversalNeeded;
3201 }
Peiyong Lind3788632018-09-18 16:01:31 -07003202 if (what & layer_state_t::eColorTransformChanged) {
3203 if (layer->setColorTransform(s.colorTransform)) {
3204 flags |= eTraversalNeeded;
3205 }
3206 }
Valerie Haudd0b7572019-01-29 14:59:27 -08003207 if (what & layer_state_t::eBackgroundColorChanged) {
3208 if (layer->setBackgroundColor(s.color, s.bgColorAlpha, s.bgColorDataspace)) {
3209 flags |= eTraversalNeeded;
3210 }
3211 }
chaviw8b3871a2017-11-01 17:41:01 -07003212 if (what & layer_state_t::eMatrixChanged) {
Robert Carrd4ae7f32018-06-07 16:10:57 -07003213 // TODO: b/109894387
3214 //
3215 // SurfaceFlinger's renderer is not prepared to handle cropping in the face of arbitrary
3216 // rotation. To see the problem observe that if we have a square parent, and a child
3217 // of the same size, then we rotate the child 45 degrees around it's center, the child
3218 // must now be cropped to a non rectangular 8 sided region.
3219 //
3220 // Of course we can fix this in the future. For now, we are lucky, SurfaceControl is
3221 // private API, and the WindowManager only uses rotation in one case, which is on a top
3222 // level layer in which cropping is not an issue.
3223 //
3224 // However given that abuse of rotation matrices could lead to surfaces extending outside
3225 // of cropped areas, we need to prevent non-root clients without permission ACCESS_SURFACE_FLINGER
3226 // (a.k.a. everyone except WindowManager and tests) from setting non rectangle preserving
3227 // transformations.
Robert Carr14167e02019-02-13 13:50:55 -08003228 if (layer->setMatrix(s.matrix, privileged))
chaviw8b3871a2017-11-01 17:41:01 -07003229 flags |= eTraversalNeeded;
3230 }
3231 if (what & layer_state_t::eTransparentRegionChanged) {
3232 if (layer->setTransparentRegionHint(s.transparentRegion))
3233 flags |= eTraversalNeeded;
3234 }
3235 if (what & layer_state_t::eFlagsChanged) {
3236 if (layer->setFlags(s.flags, s.mask))
3237 flags |= eTraversalNeeded;
3238 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003239 if (what & layer_state_t::eCropChanged_legacy) {
chaviw214c89d2019-09-04 16:03:53 -07003240 if (layer->setCrop_legacy(s.crop_legacy)) flags |= eTraversalNeeded;
chaviw8b3871a2017-11-01 17:41:01 -07003241 }
Lucas Dupin1b6531c2018-07-05 17:18:21 -07003242 if (what & layer_state_t::eCornerRadiusChanged) {
3243 if (layer->setCornerRadius(s.cornerRadius))
3244 flags |= eTraversalNeeded;
3245 }
chaviw8b3871a2017-11-01 17:41:01 -07003246 if (what & layer_state_t::eLayerStackChanged) {
3247 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer);
3248 // We only allow setting layer stacks for top level layers,
3249 // everything else inherits layer stack from its parent.
3250 if (layer->hasParent()) {
3251 ALOGE("Attempt to set layer stack on layer with parent (%s) is invalid",
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003252 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003253 } else if (idx < 0) {
3254 ALOGE("Attempt to set layer stack on layer without parent (%s) that "
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003255 "that also does not appear in the top level layer list. Something"
3256 " has gone wrong.",
3257 layer->getDebugName());
chaviw8b3871a2017-11-01 17:41:01 -07003258 } else if (layer->setLayerStack(s.layerStack)) {
3259 mCurrentState.layersSortedByZ.removeAt(idx);
3260 mCurrentState.layersSortedByZ.add(layer);
3261 // we need traversal (state changed)
3262 // AND transaction (list changed)
Lloyd Piqued432a7c2018-03-23 16:05:31 -07003263 flags |= eTransactionNeeded|eTraversalNeeded|eDisplayLayerStackChanged;
chaviw8b3871a2017-11-01 17:41:01 -07003264 }
3265 }
Marissa Wallf58c14b2018-07-24 10:50:43 -07003266 if (what & layer_state_t::eDeferTransaction_legacy) {
3267 if (s.barrierHandle_legacy != nullptr) {
3268 layer->deferTransactionUntil_legacy(s.barrierHandle_legacy, s.frameNumber_legacy);
3269 } else if (s.barrierGbp_legacy != nullptr) {
3270 const sp<IGraphicBufferProducer>& gbp = s.barrierGbp_legacy;
chaviw8b3871a2017-11-01 17:41:01 -07003271 if (authenticateSurfaceTextureLocked(gbp)) {
3272 const auto& otherLayer =
3273 (static_cast<MonitoredProducer*>(gbp.get()))->getLayer();
Marissa Wallf58c14b2018-07-24 10:50:43 -07003274 layer->deferTransactionUntil_legacy(otherLayer, s.frameNumber_legacy);
chaviw8b3871a2017-11-01 17:41:01 -07003275 } else {
3276 ALOGE("Attempt to defer transaction to to an"
3277 " unrecognized GraphicBufferProducer");
Robert Carr1db73f62016-12-21 12:58:51 -08003278 }
3279 }
chaviw8b3871a2017-11-01 17:41:01 -07003280 // We don't trigger a traversal here because if no other state is
3281 // changed, we don't want this to cause any more work
3282 }
chaviw8b3871a2017-11-01 17:41:01 -07003283 if (what & layer_state_t::eReparentChildren) {
3284 if (layer->reparentChildren(s.reparentHandle)) {
3285 flags |= eTransactionNeeded|eTraversalNeeded;
Robert Carrc3574f72016-03-24 12:19:32 -07003286 }
Mathias Agopiane57f2922012-08-09 16:29:12 -07003287 }
chaviw8b3871a2017-11-01 17:41:01 -07003288 if (what & layer_state_t::eDetachChildren) {
3289 layer->detachChildren();
3290 }
3291 if (what & layer_state_t::eOverrideScalingModeChanged) {
3292 layer->setOverrideScalingMode(s.overrideScalingMode);
3293 // We don't trigger a traversal here because if no other state is
3294 // changed, we don't want this to cause any more work
3295 }
Marissa Wall61c58622018-07-18 10:12:20 -07003296 if (what & layer_state_t::eTransformChanged) {
3297 if (layer->setTransform(s.transform)) flags |= eTraversalNeeded;
3298 }
3299 if (what & layer_state_t::eTransformToDisplayInverseChanged) {
3300 if (layer->setTransformToDisplayInverse(s.transformToDisplayInverse))
3301 flags |= eTraversalNeeded;
3302 }
3303 if (what & layer_state_t::eCropChanged) {
3304 if (layer->setCrop(s.crop)) flags |= eTraversalNeeded;
3305 }
Marissa Wall861616d2018-10-22 12:52:23 -07003306 if (what & layer_state_t::eFrameChanged) {
3307 if (layer->setFrame(s.frame)) flags |= eTraversalNeeded;
3308 }
Marissa Wall61c58622018-07-18 10:12:20 -07003309 if (what & layer_state_t::eAcquireFenceChanged) {
3310 if (layer->setAcquireFence(s.acquireFence)) flags |= eTraversalNeeded;
3311 }
3312 if (what & layer_state_t::eDataspaceChanged) {
3313 if (layer->setDataspace(s.dataspace)) flags |= eTraversalNeeded;
3314 }
3315 if (what & layer_state_t::eHdrMetadataChanged) {
3316 if (layer->setHdrMetadata(s.hdrMetadata)) flags |= eTraversalNeeded;
3317 }
3318 if (what & layer_state_t::eSurfaceDamageRegionChanged) {
3319 if (layer->setSurfaceDamageRegion(s.surfaceDamageRegion)) flags |= eTraversalNeeded;
3320 }
3321 if (what & layer_state_t::eApiChanged) {
3322 if (layer->setApi(s.api)) flags |= eTraversalNeeded;
3323 }
3324 if (what & layer_state_t::eSidebandStreamChanged) {
3325 if (layer->setSidebandStream(s.sidebandStream)) flags |= eTraversalNeeded;
3326 }
Robert Carr720e5062018-07-30 17:45:14 -07003327 if (what & layer_state_t::eInputInfoChanged) {
Vishnu Nairce5d0cc2019-02-28 14:38:41 -08003328 if (privileged) {
Robert Carr11ac2012019-01-22 09:05:25 -08003329 layer->setInputInfo(s.inputInfo);
3330 flags |= eTraversalNeeded;
3331 } else {
3332 ALOGE("Attempt to update InputWindowInfo without permission ACCESS_SURFACE_FLINGER");
3333 }
Robert Carr720e5062018-07-30 17:45:14 -07003334 }
Evan Rosky1f6d6d52018-12-06 10:47:26 -08003335 if (what & layer_state_t::eMetadataChanged) {
3336 if (layer->setMetadata(s.metadata)) flags |= eTraversalNeeded;
3337 }
Peiyong Linc502cb72019-03-01 15:00:23 -08003338 if (what & layer_state_t::eColorSpaceAgnosticChanged) {
3339 if (layer->setColorSpaceAgnostic(s.colorSpaceAgnostic)) {
3340 flags |= eTraversalNeeded;
3341 }
3342 }
Vishnu Nairc97b8db2019-10-29 18:19:35 -07003343 if (what & layer_state_t::eShadowRadiusChanged) {
3344 if (layer->setShadowRadius(s.shadowRadius)) flags |= eTraversalNeeded;
3345 }
Vishnu Nair14d76922019-08-05 08:41:20 -07003346 // This has to happen after we reparent children because when we reparent to null we remove
3347 // child layers from current state and remove its relative z. If the children are reparented in
3348 // the same transaction, then we have to make sure we reparent the children first so we do not
3349 // lose its relative z order.
3350 if (what & layer_state_t::eReparent) {
3351 bool hadParent = layer->hasParent();
3352 if (layer->reparent(s.parentHandleForChild)) {
3353 if (!hadParent) {
3354 mCurrentState.layersSortedByZ.remove(layer);
3355 }
3356 flags |= eTransactionNeeded | eTraversalNeeded;
3357 }
3358 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003359 std::vector<sp<CallbackHandle>> callbackHandles;
Valerie Hau9dab9732019-08-20 09:29:25 -07003360 if ((what & layer_state_t::eHasListenerCallbacksChanged) && (!s.listeners.empty())) {
3361 for (auto& [listener, callbackIds] : s.listeners) {
Marissa Walle2ffb422018-10-12 11:33:52 -07003362 callbackHandles.emplace_back(new CallbackHandle(listener, callbackIds, s.surface));
3363 }
3364 }
Marissa Wall78b72202019-03-15 14:58:34 -07003365 bool bufferChanged = what & layer_state_t::eBufferChanged;
3366 bool cacheIdChanged = what & layer_state_t::eCachedBufferChanged;
3367 sp<GraphicBuffer> buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003368 if (bufferChanged && cacheIdChanged && s.buffer != nullptr) {
Marissa Wall78b72202019-03-15 14:58:34 -07003369 buffer = s.buffer;
Alec Mouri4545a8a2019-08-08 20:05:32 -07003370 bool success = ClientCache::getInstance().add(s.cachedBuffer, s.buffer);
3371 if (success) {
3372 getRenderEngine().cacheExternalTextureBuffer(s.buffer);
3373 success = ClientCache::getInstance()
3374 .registerErasedRecipient(s.cachedBuffer,
3375 wp<ClientCache::ErasedRecipient>(this));
3376 if (!success) {
3377 getRenderEngine().unbindExternalTextureBuffer(s.buffer->getId());
3378 }
3379 }
Marissa Wall78b72202019-03-15 14:58:34 -07003380 } else if (cacheIdChanged) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003381 buffer = ClientCache::getInstance().get(s.cachedBuffer);
Marissa Wall78b72202019-03-15 14:58:34 -07003382 } else if (bufferChanged) {
3383 buffer = s.buffer;
Marissa Wall73411622019-01-25 10:45:41 -08003384 }
Marissa Wall78b72202019-03-15 14:58:34 -07003385 if (buffer) {
Marissa Wall947d34e2019-03-29 14:03:53 -07003386 if (layer->setBuffer(buffer, postTime, desiredPresentTime, s.cachedBuffer)) {
Valerie Haubc6ddb12019-03-08 11:10:15 -08003387 flags |= eTraversalNeeded;
Valerie Haubc6ddb12019-03-08 11:10:15 -08003388 }
Marissa Wallebc2c052019-01-16 19:16:55 -08003389 }
Marissa Walle2ffb422018-10-12 11:33:52 -07003390 if (layer->setTransactionCompletedListeners(callbackHandles)) flags |= eTraversalNeeded;
3391 // Do not put anything that updates layer state or modifies flags after
3392 // setTransactionCompletedListener
Mathias Agopiane57f2922012-08-09 16:29:12 -07003393 return flags;
3394}
3395
chaviw273171b2018-12-26 11:46:30 -08003396uint32_t SurfaceFlinger::addInputWindowCommands(const InputWindowCommands& inputWindowCommands) {
3397 uint32_t flags = 0;
3398 if (!inputWindowCommands.transferTouchFocusCommands.empty()) {
3399 flags |= eTraversalNeeded;
3400 }
3401
chaviwa911b102019-02-14 10:18:33 -08003402 if (inputWindowCommands.syncInputWindows) {
3403 flags |= eTraversalNeeded;
3404 }
3405
Vishnu Nairec0ab382019-02-13 15:32:56 -08003406 mPendingInputWindowCommands.merge(inputWindowCommands);
chaviw273171b2018-12-26 11:46:30 -08003407 return flags;
3408}
3409
chaviwfe94a222019-08-21 13:52:59 -07003410status_t SurfaceFlinger::mirrorLayer(const sp<Client>& client, const sp<IBinder>& mirrorFromHandle,
3411 sp<IBinder>* outHandle) {
3412 if (!mirrorFromHandle) {
3413 return NAME_NOT_FOUND;
3414 }
3415
3416 sp<Layer> mirrorLayer;
3417 sp<Layer> mirrorFrom;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003418 std::string uniqueName = getUniqueLayerName("MirrorRoot");
chaviwfe94a222019-08-21 13:52:59 -07003419
3420 {
3421 Mutex::Autolock _l(mStateLock);
3422 mirrorFrom = fromHandle(mirrorFromHandle);
3423 if (!mirrorFrom) {
3424 return NAME_NOT_FOUND;
3425 }
3426
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003427 status_t result = createContainerLayer(client, std::move(uniqueName), -1, -1, 0,
3428 LayerMetadata(), outHandle, &mirrorLayer);
chaviwfe94a222019-08-21 13:52:59 -07003429 if (result != NO_ERROR) {
3430 return result;
3431 }
3432
3433 mirrorLayer->mClonedChild = mirrorFrom->createClone();
3434 }
3435
3436 return addClientLayer(client, *outHandle, nullptr, mirrorLayer, nullptr, nullptr, false);
3437}
3438
Marissa Wall2d814fb2019-04-09 18:52:57 +00003439status_t SurfaceFlinger::createLayer(const String8& name, const sp<Client>& client, uint32_t w,
3440 uint32_t h, PixelFormat format, uint32_t flags,
3441 LayerMetadata metadata, sp<IBinder>* handle,
Robert Carrc0df3122019-04-11 13:18:21 -07003442 sp<IGraphicBufferProducer>* gbp,
Valerie Hau1acd6962019-10-28 16:35:48 -07003443 const sp<IBinder>& parentHandle, const sp<Layer>& parentLayer,
3444 uint32_t* outTransformHint) {
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003445 if (int32_t(w|h) < 0) {
Mathias Agopian921e6ac2012-07-23 23:11:29 -07003446 ALOGE("createLayer() failed, w or h is negative (w=%d, h=%d)",
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003447 int(w), int(h));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003448 return BAD_VALUE;
Mathias Agopian6e2d6482009-07-09 18:16:43 -07003449 }
Andreas Huber8b42e8a2010-08-16 08:49:37 -07003450
Robert Carrc0df3122019-04-11 13:18:21 -07003451 ALOG_ASSERT(parentLayer == nullptr || parentHandle == nullptr,
3452 "Expected only one of parentLayer or parentHandle to be non-null. "
3453 "Programmer error?");
3454
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003455 status_t result = NO_ERROR;
3456
3457 sp<Layer> layer;
3458
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003459 std::string uniqueName = getUniqueLayerName(name.string());
Cody Northropbc755282017-03-31 12:00:08 -06003460
Evan Roskya1f1e152019-01-24 16:17:46 -08003461 bool primaryDisplayOnly = false;
3462
3463 // window type is WINDOW_TYPE_DONT_SCREENSHOT from SurfaceControl.java
3464 // TODO b/64227542
3465 if (metadata.has(METADATA_WINDOW_TYPE)) {
3466 int32_t windowType = metadata.getInt32(METADATA_WINDOW_TYPE, 0);
3467 if (windowType == 441731) {
Ady Abraham8f1ee7f2019-04-05 10:32:50 -07003468 metadata.setInt32(METADATA_WINDOW_TYPE, InputWindowInfo::TYPE_NAVIGATION_BAR_PANEL);
Evan Roskya1f1e152019-01-24 16:17:46 -08003469 primaryDisplayOnly = true;
3470 }
3471 }
3472
Mathias Agopian3165cc22012-08-08 19:42:09 -07003473 switch (flags & ISurfaceComposerClient::eFXSurfaceMask) {
Marissa Wall61c58622018-07-18 10:12:20 -07003474 case ISurfaceComposerClient::eFXSurfaceBufferQueue:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003475 result = createBufferQueueLayer(client, std::move(uniqueName), w, h, flags,
3476 std::move(metadata), format, handle, gbp, &layer);
David Sodman0c69cad2017-08-21 12:12:51 -07003477
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003478 break;
Marissa Wall61c58622018-07-18 10:12:20 -07003479 case ISurfaceComposerClient::eFXSurfaceBufferState:
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003480 result = createBufferStateLayer(client, std::move(uniqueName), w, h, flags,
Valerie Hau1acd6962019-10-28 16:35:48 -07003481 std::move(metadata), handle, outTransformHint, &layer);
Marissa Wall61c58622018-07-18 10:12:20 -07003482 break;
chaviw13fdc492017-06-27 12:40:18 -07003483 case ISurfaceComposerClient::eFXSurfaceColor:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003484 // check if buffer size is set for color layer.
3485 if (w > 0 || h > 0) {
3486 ALOGE("createLayer() failed, w or h cannot be set for color layer (w=%d, h=%d)",
3487 int(w), int(h));
3488 return BAD_VALUE;
3489 }
3490
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003491 result = createColorLayer(client, std::move(uniqueName), w, h, flags,
3492 std::move(metadata), handle, &layer);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003493 break;
Robert Carr6b3f6c52018-08-13 13:05:17 -07003494 case ISurfaceComposerClient::eFXSurfaceContainer:
Vishnu Nair88a11f22018-11-28 18:30:57 -08003495 // check if buffer size is set for container layer.
3496 if (w > 0 || h > 0) {
3497 ALOGE("createLayer() failed, w or h cannot be set for container layer (w=%d, h=%d)",
3498 int(w), int(h));
3499 return BAD_VALUE;
3500 }
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003501 result = createContainerLayer(client, std::move(uniqueName), w, h, flags,
3502 std::move(metadata), handle, &layer);
Robert Carr6b3f6c52018-08-13 13:05:17 -07003503 break;
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003504 default:
3505 result = BAD_VALUE;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003506 break;
3507 }
3508
Dan Stoza7d89d062015-04-30 13:29:25 -07003509 if (result != NO_ERROR) {
3510 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003511 }
Dan Stoza7d89d062015-04-30 13:29:25 -07003512
Evan Roskya1f1e152019-01-24 16:17:46 -08003513 if (primaryDisplayOnly) {
3514 layer->setPrimaryDisplayOnly();
Chia-I Wuab0c3192017-08-01 11:29:00 -07003515 }
3516
Robert Carrb89ea9d2018-12-10 13:01:14 -08003517 bool addToCurrentState = callingThreadHasUnscopedSurfaceFlingerAccess();
Robert Carrc0df3122019-04-11 13:18:21 -07003518 result = addClientLayer(client, *handle, *gbp, layer, parentHandle, parentLayer,
3519 addToCurrentState);
Dan Stoza7d89d062015-04-30 13:29:25 -07003520 if (result != NO_ERROR) {
3521 return result;
3522 }
Lloyd Pique4dccc412018-01-22 17:21:36 -08003523 mInterceptor->saveSurfaceCreation(layer);
Dan Stoza7d89d062015-04-30 13:29:25 -07003524
3525 setTransactionFlags(eTransactionNeeded);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003526 return result;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003527}
3528
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003529std::string SurfaceFlinger::getUniqueLayerName(const char* name) {
3530 unsigned dupeCounter = 0;
Cody Northropbc755282017-03-31 12:00:08 -06003531
3532 // Tack on our counter whether there is a hit or not, so everyone gets a tag
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003533 std::string uniqueName = base::StringPrintf("%s#%u", name, dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003534
Dan Stoza436ccf32018-06-21 12:10:12 -07003535 // Grab the state lock since we're accessing mCurrentState
3536 Mutex::Autolock lock(mStateLock);
3537
Cody Northropbc755282017-03-31 12:00:08 -06003538 // Loop over layers until we're sure there is no matching name
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003539 bool matchFound = true;
Cody Northropbc755282017-03-31 12:00:08 -06003540 while (matchFound) {
3541 matchFound = false;
Dan Stoza436ccf32018-06-21 12:10:12 -07003542 mCurrentState.traverseInZOrder([&](Layer* layer) {
Cody Northropbc755282017-03-31 12:00:08 -06003543 if (layer->getName() == uniqueName) {
3544 matchFound = true;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003545 uniqueName = base::StringPrintf("%s#%u", name, ++dupeCounter);
Cody Northropbc755282017-03-31 12:00:08 -06003546 }
3547 });
3548 }
3549
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003550 ALOGV_IF(dupeCounter > 0, "duplicate layer name: changing %s to %s", name, uniqueName.c_str());
Cody Northropbc755282017-03-31 12:00:08 -06003551 return uniqueName;
3552}
3553
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003554status_t SurfaceFlinger::createBufferQueueLayer(const sp<Client>& client, std::string name,
Marissa Wallfd668622018-05-10 10:21:13 -07003555 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003556 LayerMetadata metadata, PixelFormat& format,
3557 sp<IBinder>* handle,
Marissa Wallfd668622018-05-10 10:21:13 -07003558 sp<IGraphicBufferProducer>* gbp,
3559 sp<Layer>* outLayer) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003560 // initialize the surfaces
Mathias Agopian92a979a2012-08-02 18:32:23 -07003561 switch (format) {
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003562 case PIXEL_FORMAT_TRANSPARENT:
3563 case PIXEL_FORMAT_TRANSLUCENT:
3564 format = PIXEL_FORMAT_RGBA_8888;
3565 break;
3566 case PIXEL_FORMAT_OPAQUE:
Mathias Agopian8f105402010-04-05 18:01:24 -07003567 format = PIXEL_FORMAT_RGBX_8888;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003568 break;
3569 }
3570
chaviwb4c6e582019-08-16 14:35:07 -07003571 sp<BufferQueueLayer> layer;
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003572 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003573 args.textureName = getNewTexture();
3574 {
3575 // Grab the SF state lock during this since it's the only safe way to access
3576 // RenderEngine when creating a BufferLayerConsumer
3577 // TODO: Check if this lock is still needed here
3578 Mutex::Autolock lock(mStateLock);
3579 layer = getFactory().createBufferQueueLayer(args);
3580 }
3581
Marissa Wallfd668622018-05-10 10:21:13 -07003582 status_t err = layer->setDefaultBufferProperties(w, h, format);
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003583 if (err == NO_ERROR) {
David Sodman0c69cad2017-08-21 12:12:51 -07003584 *handle = layer->getHandle();
3585 *gbp = layer->getProducer();
3586 *outLayer = layer;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003587 }
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003588
Marissa Wallfd668622018-05-10 10:21:13 -07003589 ALOGE_IF(err, "createBufferQueueLayer() failed (%s)", strerror(-err));
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003590 return err;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003591}
3592
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003593status_t SurfaceFlinger::createBufferStateLayer(const sp<Client>& client, std::string name,
Marissa Wall61c58622018-07-18 10:12:20 -07003594 uint32_t w, uint32_t h, uint32_t flags,
Evan Roskya1f1e152019-01-24 16:17:46 -08003595 LayerMetadata metadata, sp<IBinder>* handle,
Valerie Hau1acd6962019-10-28 16:35:48 -07003596 uint32_t* outTransformHint, sp<Layer>* outLayer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003597 LayerCreationArgs args(this, client, std::move(name), w, h, flags, std::move(metadata));
chaviwb4c6e582019-08-16 14:35:07 -07003598 args.displayDevice = getDefaultDisplayDevice();
3599 args.textureName = getNewTexture();
3600 sp<BufferStateLayer> layer = getFactory().createBufferStateLayer(args);
Valerie Hau1acd6962019-10-28 16:35:48 -07003601 if (outTransformHint) {
3602 *outTransformHint = layer->getTransformHint();
3603 }
Marissa Wall61c58622018-07-18 10:12:20 -07003604 *handle = layer->getHandle();
3605 *outLayer = layer;
3606
3607 return NO_ERROR;
3608}
3609
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003610status_t SurfaceFlinger::createColorLayer(const sp<Client>& client, std::string name, uint32_t w,
Evan Roskya1f1e152019-01-24 16:17:46 -08003611 uint32_t h, uint32_t flags, LayerMetadata metadata,
3612 sp<IBinder>* handle, sp<Layer>* outLayer) {
3613 *outLayer = getFactory().createColorLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003614 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003615 *handle = (*outLayer)->getHandle();
Mathias Agopian4d9b8222013-03-12 17:11:48 -07003616 return NO_ERROR;
Mathias Agopian118d0242011-10-13 16:02:48 -07003617}
3618
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003619status_t SurfaceFlinger::createContainerLayer(const sp<Client>& client, std::string name,
Evan Roskya1f1e152019-01-24 16:17:46 -08003620 uint32_t w, uint32_t h, uint32_t flags,
3621 LayerMetadata metadata, sp<IBinder>* handle,
3622 sp<Layer>* outLayer) {
3623 *outLayer = getFactory().createContainerLayer(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003624 {this, client, std::move(name), w, h, flags, std::move(metadata)});
Robert Carr6b3f6c52018-08-13 13:05:17 -07003625 *handle = (*outLayer)->getHandle();
3626 return NO_ERROR;
3627}
3628
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003629void SurfaceFlinger::markLayerPendingRemovalLocked(const sp<Layer>& layer) {
Robert Carr2e102c92018-10-23 12:11:15 -07003630 mLayersPendingRemoval.add(layer);
3631 mLayersRemoved = true;
3632 setTransactionFlags(eTransactionNeeded);
3633}
3634
Robert Carr695d5282018-12-18 15:27:58 -08003635void SurfaceFlinger::onHandleDestroyed(sp<Layer>& layer)
Rob Carr4bba3702018-10-08 21:53:30 +00003636{
Robert Carr2e102c92018-10-23 12:11:15 -07003637 Mutex::Autolock lock(mStateLock);
Robert Carr6fb1a7e2018-12-11 12:07:25 -08003638 // If a layer has a parent, we allow it to out-live it's handle
3639 // with the idea that the parent holds a reference and will eventually
3640 // be cleaned up. However no one cleans up the top-level so we do so
3641 // here.
3642 if (layer->getParent() == nullptr) {
3643 mCurrentState.layersSortedByZ.remove(layer);
3644 }
3645 markLayerPendingRemovalLocked(layer);
Robert Carrc0df3122019-04-11 13:18:21 -07003646
3647 auto it = mLayersByLocalBinderToken.begin();
3648 while (it != mLayersByLocalBinderToken.end()) {
3649 if (it->second == layer) {
3650 it = mLayersByLocalBinderToken.erase(it);
3651 } else {
3652 it++;
3653 }
3654 }
3655
Robert Carr695d5282018-12-18 15:27:58 -08003656 layer.clear();
Rob Carr4bba3702018-10-08 21:53:30 +00003657}
3658
Mathias Agopianb60314a2012-04-10 22:09:54 -07003659// ---------------------------------------------------------------------------
3660
Andy McFadden13a082e2012-08-24 10:16:42 -07003661void SurfaceFlinger::onInitializeDisplays() {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003662 const auto display = getDefaultDisplayDeviceLocked();
3663 if (!display) return;
3664
3665 const sp<IBinder> token = display->getDisplayToken().promote();
3666 LOG_ALWAYS_FATAL_IF(token == nullptr);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003667
Jesse Hall01e29052013-02-19 16:13:35 -08003668 // reset screen orientation and use primary layer stack
Andy McFadden13a082e2012-08-24 10:16:42 -07003669 Vector<ComposerState> state;
3670 Vector<DisplayState> displays;
3671 DisplayState d;
Jesse Hall01e29052013-02-19 16:13:35 -08003672 d.what = DisplayState::eDisplayProjectionChanged |
3673 DisplayState::eLayerStackChanged;
Dominik Laskowski83b88212018-12-11 13:34:06 -08003674 d.token = token;
Jesse Hall01e29052013-02-19 16:13:35 -08003675 d.layerStack = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003676 d.orientation = DisplayState::eOrientationDefault;
Jeff Brown4c05dd12012-09-09 00:07:17 -07003677 d.frame.makeInvalid();
3678 d.viewport.makeInvalid();
Michael Lentine47e45402014-07-18 15:34:25 -07003679 d.width = 0;
3680 d.height = 0;
Andy McFadden13a082e2012-08-24 10:16:42 -07003681 displays.add(d);
Valerie Hau9dab9732019-08-20 09:29:25 -07003682 setTransactionState(state, displays, 0, nullptr, mPendingInputWindowCommands, -1, {}, false,
3683 {});
Jamie Gennis6547ff42013-07-16 20:12:42 -07003684
Dominik Laskowskie9774092018-12-11 10:04:24 -08003685 setPowerModeInternal(display, HWC_POWER_MODE_NORMAL);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07003686
Dominik Laskowski83b88212018-12-11 13:34:06 -08003687 const nsecs_t vsyncPeriod = getVsyncPeriod();
3688 mAnimFrameTracker.setDisplayRefreshPeriod(vsyncPeriod);
Brian Anderson0a61b0c2016-12-07 14:55:56 -08003689
Brian Andersond0010582017-03-07 13:20:31 -08003690 // Use phase of 0 since phase is not known.
3691 // Use latency of 0, which will snap to the ideal latency.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003692 DisplayStatInfo stats{0 /* vsyncTime */, vsyncPeriod};
Ana Krulece588e312018-09-18 12:32:24 -07003693 setCompositorTimingSnapped(stats, 0);
Andy McFadden13a082e2012-08-24 10:16:42 -07003694}
3695
3696void SurfaceFlinger::initializeDisplays() {
Dominik Laskowski8c001672018-05-30 16:52:06 -07003697 // Async since we may be called from the main thread.
Dominik Laskowski83b88212018-12-11 13:34:06 -08003698 postMessageAsync(
3699 new LambdaMessage([this]() NO_THREAD_SAFETY_ANALYSIS { onInitializeDisplays(); }));
Andy McFadden13a082e2012-08-24 10:16:42 -07003700}
3701
Ady Abraham27c70212019-06-11 10:52:26 -07003702void SurfaceFlinger::setVsyncEnabledInHWC(DisplayId displayId, HWC2::Vsync enabled) {
3703 if (mHWCVsyncState != enabled) {
3704 getHwComposer().setVsyncEnabled(displayId, enabled);
3705 mHWCVsyncState = enabled;
3706 }
3707}
3708
Dominik Laskowskie9774092018-12-11 10:04:24 -08003709void SurfaceFlinger::setPowerModeInternal(const sp<DisplayDevice>& display, int mode) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07003710 if (display->isVirtual()) {
3711 ALOGE("%s: Invalid operation on virtual display", __FUNCTION__);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003712 return;
3713 }
3714
Dominik Laskowski075d3172018-05-24 15:50:06 -07003715 const auto displayId = display->getId();
3716 LOG_ALWAYS_FATAL_IF(!displayId);
3717
Dominik Laskowski34157762018-10-31 13:07:19 -07003718 ALOGD("Setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07003719
3720 int currentMode = display->getPowerMode();
3721 if (mode == currentMode) {
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003722 return;
3723 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003724
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003725 display->setPowerMode(mode);
3726
Lloyd Pique4dccc412018-01-22 17:21:36 -08003727 if (mInterceptor->isEnabled()) {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003728 mInterceptor->savePowerModeUpdate(display->getSequenceId(), mode);
Irvelffc9efc2016-07-27 15:16:37 -07003729 }
3730
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003731 if (currentMode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003732 // Turn on the display
Dominik Laskowski075d3172018-05-24 15:50:06 -07003733 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003734 if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ady Abraham27c70212019-06-11 10:52:26 -07003735 setVsyncEnabledInHWC(*displayId, mHWCVsyncPendingState);
Ana Krulecc2870422019-01-29 19:00:58 -08003736 mScheduler->onScreenAcquired(mAppConnectionHandle);
3737 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003738 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003739
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003740 mVisibleRegionsDirty = true;
Dan Stozab90cf072015-03-05 11:05:59 -08003741 mHasPoweredOff = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07003742 repaintEverything();
Tim Murrayf9d4e442016-08-02 15:43:59 -07003743
3744 struct sched_param param = {0};
3745 param.sched_priority = 1;
3746 if (sched_setscheduler(0, SCHED_FIFO, &param) != 0) {
3747 ALOGW("Couldn't set SCHED_FIFO on display on");
3748 }
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003749 } else if (mode == HWC_POWER_MODE_OFF) {
Tim Murrayf9d4e442016-08-02 15:43:59 -07003750 // Turn off the display
3751 struct sched_param param = {0};
3752 if (sched_setscheduler(0, SCHED_OTHER, &param) != 0) {
3753 ALOGW("Couldn't set SCHED_OTHER on display off");
3754 }
3755
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003756 if (display->isPrimary() && currentMode != HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003757 mScheduler->disableHardwareVsync(true);
3758 mScheduler->onScreenReleased(mAppConnectionHandle);
Mathias Agopiancde87a32012-09-13 14:09:01 -07003759 }
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003760
Ady Abraham27c70212019-06-11 10:52:26 -07003761 // Make sure HWVsync is disabled before turning off the display
3762 setVsyncEnabledInHWC(*displayId, HWC2::Vsync::Disable);
3763
Dominik Laskowski075d3172018-05-24 15:50:06 -07003764 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003765 mVisibleRegionsDirty = true;
3766 // from this point on, SF will stop drawing on this display
Matthew Bouyack38d49612017-05-12 12:49:32 -07003767 } else if (mode == HWC_POWER_MODE_DOZE ||
3768 mode == HWC_POWER_MODE_NORMAL) {
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003769 // Update display while dozing
Dominik Laskowski075d3172018-05-24 15:50:06 -07003770 getHwComposer().setPowerMode(*displayId, mode);
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003771 if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
Ana Krulecc2870422019-01-29 19:00:58 -08003772 mScheduler->onScreenAcquired(mAppConnectionHandle);
3773 mScheduler->resyncToHardwareVsync(true, getVsyncPeriod());
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003774 }
3775 } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
3776 // Leave display going to doze
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003777 if (display->isPrimary()) {
Ana Krulecc2870422019-01-29 19:00:58 -08003778 mScheduler->disableHardwareVsync(true);
3779 mScheduler->onScreenReleased(mAppConnectionHandle);
Zheng Zhang8a43fe62017-03-17 11:19:39 +01003780 }
Dominik Laskowski075d3172018-05-24 15:50:06 -07003781 getHwComposer().setPowerMode(*displayId, mode);
Prashant Malani2c9b11f2014-05-25 01:36:31 -07003782 } else {
Matthew Bouyack38d49612017-05-12 12:49:32 -07003783 ALOGE("Attempting to set unknown power mode: %d\n", mode);
Dominik Laskowski075d3172018-05-24 15:50:06 -07003784 getHwComposer().setPowerMode(*displayId, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003785 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003786
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003787 if (display->isPrimary()) {
Yiwei Zhang7e666a52018-11-15 13:33:42 -08003788 mTimeStats->setPowerMode(mode);
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003789 mRefreshRateStats->setPowerMode(mode);
Ady Abraham6fe2c172019-07-12 12:37:57 -07003790 mScheduler->setDisplayPowerState(mode == HWC_POWER_MODE_NORMAL);
Yiwei Zhang3a226d22018-10-16 09:23:03 -07003791 }
3792
Dominik Laskowski34157762018-10-31 13:07:19 -07003793 ALOGD("Finished setting power mode %d on display %s", mode, to_string(*displayId).c_str());
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003794}
3795
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003796void SurfaceFlinger::setPowerMode(const sp<IBinder>& displayToken, int mode) {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003797 postMessageSync(new LambdaMessage([&]() NO_THREAD_SAFETY_ANALYSIS {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003798 const auto display = getDisplayDevice(displayToken);
3799 if (!display) {
3800 ALOGE("Attempt to set power mode %d for invalid display token %p", mode,
3801 displayToken.get());
3802 } else if (display->isVirtual()) {
3803 ALOGW("Attempt to set power mode %d for virtual display", mode);
3804 } else {
Dominik Laskowskie9774092018-12-11 10:04:24 -08003805 setPowerModeInternal(display, mode);
Andy McFaddenc01a79d2012-09-27 16:02:06 -07003806 }
Dominik Laskowskieecd6592018-05-29 10:25:41 -07003807 }));
Mathias Agopianb60314a2012-04-10 22:09:54 -07003808}
3809
3810// ---------------------------------------------------------------------------
3811
Dominik Laskowskic2867142019-01-21 11:33:38 -08003812status_t SurfaceFlinger::doDump(int fd, const DumpArgs& args,
3813 bool asProto) NO_THREAD_SAFETY_ANALYSIS {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003814 std::string result;
Mathias Agopian99b49842011-06-27 16:05:52 -07003815
Mathias Agopianbd115332013-04-18 16:41:04 -07003816 IPCThreadState* ipc = IPCThreadState::self();
3817 const int pid = ipc->getCallingPid();
3818 const int uid = ipc->getCallingUid();
Vishnu Nair6a408532017-10-24 09:11:27 -07003819
Mathias Agopianbd115332013-04-18 16:41:04 -07003820 if ((uid != AID_SHELL) &&
3821 !PermissionCache::checkPermission(sDump, pid, uid)) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003822 StringAppendF(&result, "Permission Denial: can't dump SurfaceFlinger from pid=%d, uid=%d\n",
3823 pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003824 } else {
Jesse Hallfcd15b42014-12-23 13:57:23 -08003825 // Try to get the main lock, but give up after one second
Mathias Agopian9795c422009-08-26 16:36:26 -07003826 // (this would indicate SF is stuck, but we want to be able to
3827 // print something in dumpsys).
Jesse Hallfcd15b42014-12-23 13:57:23 -08003828 status_t err = mStateLock.timedLock(s2ns(1));
3829 bool locked = (err == NO_ERROR);
Mathias Agopian9795c422009-08-26 16:36:26 -07003830 if (!locked) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003831 StringAppendF(&result,
3832 "SurfaceFlinger appears to be unresponsive (%s [%d]), dumping anyways "
3833 "(no locks held)\n",
3834 strerror(-err), err);
Mathias Agopian9795c422009-08-26 16:36:26 -07003835 }
3836
Dominik Laskowskic2867142019-01-21 11:33:38 -08003837 static const std::unordered_map<std::string, Dumper> dumpers = {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003838 {"--display-id"s, dumper(&SurfaceFlinger::dumpDisplayIdentificationData)},
Dominik Laskowski98041832019-08-01 18:35:59 -07003839 {"--dispsync"s,
3840 dumper([this](std::string& s) { mScheduler->getPrimaryDispSync().dump(s); })},
Dominik Laskowskib6e54372019-09-04 14:06:28 -07003841 {"--edid"s, argsDumper(&SurfaceFlinger::dumpRawDisplayIdentificationData)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003842 {"--frame-events"s, dumper(&SurfaceFlinger::dumpFrameEventsLocked)},
3843 {"--latency"s, argsDumper(&SurfaceFlinger::dumpStatsLocked)},
3844 {"--latency-clear"s, argsDumper(&SurfaceFlinger::clearStatsLocked)},
3845 {"--list"s, dumper(&SurfaceFlinger::listLayersLocked)},
3846 {"--static-screen"s, dumper(&SurfaceFlinger::dumpStaticScreenStats)},
3847 {"--timestats"s, protoDumper(&SurfaceFlinger::dumpTimeStats)},
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003848 {"--vsync"s, dumper(&SurfaceFlinger::dumpVSync)},
Dominik Laskowskic2867142019-01-21 11:33:38 -08003849 {"--wide-color"s, dumper(&SurfaceFlinger::dumpWideColorInfo)},
3850 };
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003851
Dominik Laskowskic2867142019-01-21 11:33:38 -08003852 const auto flag = args.empty() ? ""s : std::string(String8(args[0]));
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003853
Dominik Laskowski46470112019-08-02 13:13:11 -07003854 const auto it = dumpers.find(flag);
3855 if (it != dumpers.end()) {
Dominik Laskowskic2867142019-01-21 11:33:38 -08003856 (it->second)(args, asProto, result);
Vishnu Nair8406fd72019-07-30 11:29:31 -07003857 } else if (!asProto) {
3858 dumpAllLocked(args, result);
Mathias Agopian48b888a2011-01-19 16:15:53 -08003859 }
3860
Mathias Agopian9795c422009-08-26 16:36:26 -07003861 if (locked) {
3862 mStateLock.unlock();
3863 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003864
Dominik Laskowski46470112019-08-02 13:13:11 -07003865 if (it == dumpers.end()) {
3866 const LayersProto layersProto = dumpProtoFromMainThread();
3867 if (asProto) {
3868 result.append(layersProto.SerializeAsString());
3869 } else {
Vishnu Nair0f085c62019-08-30 08:49:12 -07003870 // Dump info that we need to access from the main thread
Dominik Laskowski46470112019-08-02 13:13:11 -07003871 const auto layerTree = LayerProtoParser::generateLayerTree(layersProto);
3872 result.append(LayerProtoParser::layerTreeToString(layerTree));
3873 result.append("\n");
Vishnu Nair0f085c62019-08-30 08:49:12 -07003874 dumpOffscreenLayers(result);
Dominik Laskowski46470112019-08-02 13:13:11 -07003875 }
Vishnu Nair8406fd72019-07-30 11:29:31 -07003876 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003877 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08003878 write(fd, result.c_str(), result.size());
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08003879 return NO_ERROR;
3880}
3881
Nataniel Borges8e7dc722019-02-28 15:10:28 -08003882status_t SurfaceFlinger::dumpCritical(int fd, const DumpArgs&, bool asProto) {
3883 if (asProto && mTracing.isEnabled()) {
3884 mTracing.writeToFileAsync();
3885 }
3886
3887 return doDump(fd, DumpArgs(), asProto);
3888}
3889
Dominik Laskowskic2867142019-01-21 11:33:38 -08003890void SurfaceFlinger::listLayersLocked(std::string& result) const {
Yiwei Zhang5434a782018-12-05 18:06:32 -08003891 mCurrentState.traverseInZOrder(
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003892 [&](Layer* layer) { StringAppendF(&result, "%s\n", layer->getDebugName()); });
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003893}
3894
Dominik Laskowskic2867142019-01-21 11:33:38 -08003895void SurfaceFlinger::dumpStatsLocked(const DumpArgs& args, std::string& result) const {
Dominik Laskowski83b88212018-12-11 13:34:06 -08003896 StringAppendF(&result, "%" PRId64 "\n", getVsyncPeriod());
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003897
Dominik Laskowskic2867142019-01-21 11:33:38 -08003898 if (args.size() > 1) {
3899 const auto name = String8(args[1]);
Robert Carr2047fae2016-11-28 14:09:09 -08003900 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003901 if (layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003902 layer->dumpFrameStats(result);
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003903 }
Robert Carr2047fae2016-11-28 14:09:09 -08003904 });
Dominik Laskowskic2867142019-01-21 11:33:38 -08003905 } else {
3906 mAnimFrameTracker.dumpStats(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08003907 }
3908}
3909
Dominik Laskowskic2867142019-01-21 11:33:38 -08003910void SurfaceFlinger::clearStatsLocked(const DumpArgs& args, std::string&) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003911 const bool clearAll = args.size() < 2;
3912 const auto name = clearAll ? String8() : String8(args[1]);
3913
Robert Carr2047fae2016-11-28 14:09:09 -08003914 mCurrentState.traverseInZOrder([&](Layer* layer) {
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003915 if (clearAll || layer->getName() == name.string()) {
Svetoslavd85084b2014-03-20 10:28:31 -07003916 layer->clearFrameStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003917 }
Robert Carr2047fae2016-11-28 14:09:09 -08003918 });
Jamie Gennis4b0eba92013-02-05 13:30:24 -08003919
Svetoslavd85084b2014-03-20 10:28:31 -07003920 mAnimFrameTracker.clearStats();
Mathias Agopian25e66fc2012-01-28 22:31:55 -08003921}
3922
Dominik Laskowskic2867142019-01-21 11:33:38 -08003923void SurfaceFlinger::dumpTimeStats(const DumpArgs& args, bool asProto, std::string& result) const {
3924 mTimeStats->parseArgs(asProto, args, result);
3925}
3926
Jamie Gennis6547ff42013-07-16 20:12:42 -07003927// This should only be called from the main thread. Otherwise it would need
3928// the lock and should use mCurrentState rather than mDrawingState.
3929void SurfaceFlinger::logFrameStats() {
Robert Carr2047fae2016-11-28 14:09:09 -08003930 mDrawingState.traverseInZOrder([&](Layer* layer) {
Jamie Gennis6547ff42013-07-16 20:12:42 -07003931 layer->logFrameStats();
Robert Carr2047fae2016-11-28 14:09:09 -08003932 });
Jamie Gennis6547ff42013-07-16 20:12:42 -07003933
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003934 mAnimFrameTracker.logAndResetStats("<win-anim>");
Jamie Gennis6547ff42013-07-16 20:12:42 -07003935}
3936
Yiwei Zhang5434a782018-12-05 18:06:32 -08003937void SurfaceFlinger::appendSfConfigString(std::string& result) const {
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003938 result.append(" [sf");
Fabien Sanglardc93afd52017-03-13 13:02:42 -07003939
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003940 if (isLayerTripleBufferingDisabled())
3941 result.append(" DISABLE_TRIPLE_BUFFERING");
Fabien Sanglardc45a7d92017-03-14 13:24:22 -07003942
Yiwei Zhang5434a782018-12-05 18:06:32 -08003943 StringAppendF(&result, " PRESENT_TIME_OFFSET=%" PRId64, dispSyncPresentTimeOffset);
3944 StringAppendF(&result, " FORCE_HWC_FOR_RBG_TO_YUV=%d", useHwcForRgbToYuv);
3945 StringAppendF(&result, " MAX_VIRT_DISPLAY_DIM=%" PRIu64, maxVirtualDisplaySize);
3946 StringAppendF(&result, " RUNNING_WITHOUT_SYNC_FRAMEWORK=%d", !hasSyncFramework);
3947 StringAppendF(&result, " NUM_FRAMEBUFFER_SURFACE_BUFFERS=%" PRId64,
3948 maxFrameBufferAcquiredBuffers);
Fabien Sanglard63a5fcd2016-12-29 15:13:07 -08003949 result.append("]");
Andy McFadden4803b742012-09-24 19:07:20 -07003950}
3951
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003952void SurfaceFlinger::dumpVSync(std::string& result) const {
Dominik Laskowski98041832019-08-01 18:35:59 -07003953 mScheduler->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07003954
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003955 mRefreshRateStats->dump(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07003956 result.append("\n");
3957
Ana Krulec757f63a2019-01-25 10:46:18 -08003958 mPhaseOffsets->dump(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003959 StringAppendF(&result,
Dominik Laskowski98041832019-08-01 18:35:59 -07003960 " present offset: %9" PRId64 " ns\t VSYNC period: %9" PRId64 " ns\n\n",
Ana Krulec757f63a2019-01-25 10:46:18 -08003961 dispSyncPresentTimeOffset, getVsyncPeriod());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003962
Ady Abraham42b3beb2019-07-09 18:09:52 -07003963 StringAppendF(&result, "Allowed Display Configs: ");
Steven Thomas2bbaabe2019-08-28 16:08:35 -07003964 for (int32_t configId : mAllowedDisplayConfigs) {
3965 StringAppendF(&result, "%" PRIu32 " Hz, ",
3966 mRefreshRateConfigs->getRefreshRateFromConfigId(configId).fps);
Ady Abraham42b3beb2019-07-09 18:09:52 -07003967 }
3968 StringAppendF(&result, "(config override by backdoor: %s)\n\n",
3969 mDebugDisplayConfigSetByBackdoor ? "yes" : "no");
Dominik Laskowski98041832019-08-01 18:35:59 -07003970
Ana Krulecc2870422019-01-29 19:00:58 -08003971 mScheduler->dump(mAppConnectionHandle, result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08003972}
3973
Yiwei Zhang5434a782018-12-05 18:06:32 -08003974void SurfaceFlinger::dumpStaticScreenStats(std::string& result) const {
3975 result.append("Static screen stats:\n");
David Sodman4a36e932017-11-07 14:29:47 -08003976 for (size_t b = 0; b < SurfaceFlingerBE::NUM_BUCKETS - 1; ++b) {
3977 float bucketTimeSec = getBE().mFrameBuckets[b] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003978 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003979 static_cast<float>(getBE().mFrameBuckets[b]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003980 StringAppendF(&result, " < %zd frames: %.3f s (%.1f%%)\n", b + 1, bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003981 }
David Sodman4a36e932017-11-07 14:29:47 -08003982 float bucketTimeSec = getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1] / 1e9;
Dan Stozab90cf072015-03-05 11:05:59 -08003983 float percent = 100.0f *
David Sodman4a36e932017-11-07 14:29:47 -08003984 static_cast<float>(getBE().mFrameBuckets[SurfaceFlingerBE::NUM_BUCKETS - 1]) / getBE().mTotalTime;
Yiwei Zhang5434a782018-12-05 18:06:32 -08003985 StringAppendF(&result, " %zd+ frames: %.3f s (%.1f%%)\n", SurfaceFlingerBE::NUM_BUCKETS - 1,
3986 bucketTimeSec, percent);
Dan Stozab90cf072015-03-05 11:05:59 -08003987}
3988
Dominik Laskowski87a07e42019-10-10 20:38:02 -07003989void SurfaceFlinger::recordBufferingStats(const std::string& layerName,
3990 std::vector<OccupancyTracker::Segment>&& history) {
David Sodmancbaf0832017-11-07 14:21:36 -08003991 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
3992 auto& stats = getBE().mBufferingStats[layerName];
Dan Stozae77c7662016-05-13 11:37:28 -07003993 for (const auto& segment : history) {
3994 if (!segment.usedThirdBuffer) {
3995 stats.twoBufferTime += segment.totalTime;
3996 }
3997 if (segment.occupancyAverage < 1.0f) {
3998 stats.doubleBufferedTime += segment.totalTime;
3999 } else if (segment.occupancyAverage < 2.0f) {
4000 stats.tripleBufferedTime += segment.totalTime;
4001 }
4002 ++stats.numSegments;
4003 stats.totalTime += segment.totalTime;
4004 }
4005}
4006
Yiwei Zhang5434a782018-12-05 18:06:32 -08004007void SurfaceFlinger::dumpFrameEventsLocked(std::string& result) {
4008 result.append("Layer frame timestamps:\n");
Brian Andersond6927fb2016-07-23 23:37:30 -07004009
4010 const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
4011 const size_t count = currentLayers.size();
4012 for (size_t i=0 ; i<count ; i++) {
4013 currentLayers[i]->dumpFrameEvents(result);
4014 }
4015}
4016
Yiwei Zhang5434a782018-12-05 18:06:32 -08004017void SurfaceFlinger::dumpBufferingStats(std::string& result) const {
Dan Stozae77c7662016-05-13 11:37:28 -07004018 result.append("Buffering stats:\n");
4019 result.append(" [Layer name] <Active time> <Two buffer> "
4020 "<Double buffered> <Triple buffered>\n");
David Sodmancbaf0832017-11-07 14:21:36 -08004021 Mutex::Autolock lock(getBE().mBufferingStatsMutex);
Dan Stozae77c7662016-05-13 11:37:28 -07004022 typedef std::tuple<std::string, float, float, float> BufferTuple;
4023 std::map<float, BufferTuple, std::greater<float>> sorted;
David Sodmancbaf0832017-11-07 14:21:36 -08004024 for (const auto& statsPair : getBE().mBufferingStats) {
Dan Stozae77c7662016-05-13 11:37:28 -07004025 const char* name = statsPair.first.c_str();
David Sodmancbaf0832017-11-07 14:21:36 -08004026 const SurfaceFlingerBE::BufferingStats& stats = statsPair.second;
Dan Stozae77c7662016-05-13 11:37:28 -07004027 if (stats.numSegments == 0) {
4028 continue;
4029 }
4030 float activeTime = ns2ms(stats.totalTime) / 1000.0f;
4031 float twoBufferRatio = static_cast<float>(stats.twoBufferTime) /
4032 stats.totalTime;
4033 float doubleBufferRatio = static_cast<float>(
4034 stats.doubleBufferedTime) / stats.totalTime;
4035 float tripleBufferRatio = static_cast<float>(
4036 stats.tripleBufferedTime) / stats.totalTime;
4037 sorted.insert({activeTime, {name, twoBufferRatio,
4038 doubleBufferRatio, tripleBufferRatio}});
4039 }
4040 for (const auto& sortedPair : sorted) {
4041 float activeTime = sortedPair.first;
4042 const BufferTuple& values = sortedPair.second;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004043 StringAppendF(&result, " [%s] %.2f %.3f %.3f %.3f\n", std::get<0>(values).c_str(),
4044 activeTime, std::get<1>(values), std::get<2>(values), std::get<3>(values));
Dan Stozae77c7662016-05-13 11:37:28 -07004045 }
4046 result.append("\n");
4047}
4048
Yiwei Zhang5434a782018-12-05 18:06:32 -08004049void SurfaceFlinger::dumpDisplayIdentificationData(std::string& result) const {
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004050 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004051 const auto displayId = display->getId();
4052 if (!displayId) {
4053 continue;
4054 }
4055 const auto hwcDisplayId = getHwComposer().fromPhysicalDisplayId(*displayId);
Dominik Laskowski7e045462018-05-30 13:02:02 -07004056 if (!hwcDisplayId) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004057 continue;
4058 }
4059
Yiwei Zhang5434a782018-12-05 18:06:32 -08004060 StringAppendF(&result,
4061 "Display %s (HWC display %" PRIu64 "): ", to_string(*displayId).c_str(),
4062 *hwcDisplayId);
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004063 uint8_t port;
4064 DisplayIdentificationData data;
Dominik Laskowski7e045462018-05-30 13:02:02 -07004065 if (!getHwComposer().getDisplayIdentificationData(*hwcDisplayId, &port, &data)) {
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004066 result.append("no identification data\n");
4067 continue;
4068 }
4069
4070 if (!isEdid(data)) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004071 result.append("unknown identification data\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004072 continue;
4073 }
4074
4075 const auto edid = parseEdid(data);
4076 if (!edid) {
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004077 result.append("invalid EDID\n");
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004078 continue;
4079 }
4080
Yiwei Zhang5434a782018-12-05 18:06:32 -08004081 StringAppendF(&result, "port=%u pnpId=%s displayName=\"", port, edid->pnpId.data());
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004082 result.append(edid->displayName.data(), edid->displayName.length());
4083 result.append("\"\n");
4084 }
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004085}
4086
Dominik Laskowskib6e54372019-09-04 14:06:28 -07004087void SurfaceFlinger::dumpRawDisplayIdentificationData(const DumpArgs& args,
4088 std::string& result) const {
4089 hwc2_display_t hwcDisplayId;
4090 uint8_t port;
4091 DisplayIdentificationData data;
4092
4093 if (args.size() > 1 && base::ParseUint(String8(args[1]), &hwcDisplayId) &&
4094 getHwComposer().getDisplayIdentificationData(hwcDisplayId, &port, &data)) {
4095 result.append(reinterpret_cast<const char*>(data.data()), data.size());
4096 }
4097}
4098
Yiwei Zhang5434a782018-12-05 18:06:32 -08004099void SurfaceFlinger::dumpWideColorInfo(std::string& result) const {
Peiyong Linff84a152019-05-17 18:36:19 -07004100 StringAppendF(&result, "Device has wide color built-in display: %d\n", hasWideColorDisplay);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004101 StringAppendF(&result, "Device uses color management: %d\n", useColorManagement);
4102 StringAppendF(&result, "DisplayColorSetting: %s\n",
4103 decodeDisplayColorSetting(mDisplayColorSetting).c_str());
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004104
4105 // TODO: print out if wide-color mode is active or not
4106
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004107 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004108 const auto displayId = display->getId();
4109 if (!displayId) {
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004110 continue;
4111 }
4112
Yiwei Zhang5434a782018-12-05 18:06:32 -08004113 StringAppendF(&result, "Display %s color modes:\n", to_string(*displayId).c_str());
Dominik Laskowski075d3172018-05-24 15:50:06 -07004114 std::vector<ColorMode> modes = getHwComposer().getColorModes(*displayId);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004115 for (auto&& mode : modes) {
Yiwei Zhang5434a782018-12-05 18:06:32 -08004116 StringAppendF(&result, " %s (%d)\n", decodeColorMode(mode).c_str(), mode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004117 }
4118
Lloyd Pique32cbe282018-10-19 13:09:22 -07004119 ColorMode currentMode = display->getCompositionDisplay()->getState().colorMode;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004120 StringAppendF(&result, " Current color mode: %s (%d)\n",
4121 decodeColorMode(currentMode).c_str(), currentMode);
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004122 }
4123 result.append("\n");
4124}
4125
Vishnu Nair8406fd72019-07-30 11:29:31 -07004126LayersProto SurfaceFlinger::dumpDrawingStateProto(uint32_t traceFlags) const {
chaviw1d044282017-09-27 12:19:28 -07004127 LayersProto layersProto;
Vishnu Nair8406fd72019-07-30 11:29:31 -07004128 mDrawingState.traverseInZOrder([&](Layer* layer) {
chaviw1d044282017-09-27 12:19:28 -07004129 LayerProto* layerProto = layersProto.add_layers();
Vishnu Nair8406fd72019-07-30 11:29:31 -07004130 layer->writeToProtoDrawingState(layerProto, traceFlags);
4131 layer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing, traceFlags);
chaviw1d044282017-09-27 12:19:28 -07004132 });
4133
4134 return layersProto;
4135}
4136
Vishnu Nair0f085c62019-08-30 08:49:12 -07004137void SurfaceFlinger::dumpOffscreenLayersProto(LayersProto& layersProto, uint32_t traceFlags) const {
4138 // Add a fake invisible root layer to the proto output and parent all the offscreen layers to
4139 // it.
4140 LayerProto* rootProto = layersProto.add_layers();
4141 const int32_t offscreenRootLayerId = INT32_MAX - 2;
4142 rootProto->set_id(offscreenRootLayerId);
4143 rootProto->set_name("Offscreen Root");
Vishnu Naird5aeb612019-09-20 14:39:39 -07004144 rootProto->set_parent(-1);
Vishnu Nair0f085c62019-08-30 08:49:12 -07004145
4146 for (Layer* offscreenLayer : mOffscreenLayers) {
4147 // Add layer as child of the fake root
4148 rootProto->add_children(offscreenLayer->sequence);
4149
4150 // Add layer
4151 LayerProto* layerProto = layersProto.add_layers();
4152 offscreenLayer->writeToProtoDrawingState(layerProto, traceFlags);
4153 offscreenLayer->writeToProtoCommonState(layerProto, LayerVector::StateSet::Drawing,
4154 traceFlags);
4155 layerProto->set_parent(offscreenRootLayerId);
4156
4157 // Add children
4158 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4159 if (layer == offscreenLayer) {
4160 return;
4161 }
4162 LayerProto* childProto = layersProto.add_layers();
4163 layer->writeToProtoDrawingState(childProto, traceFlags);
4164 layer->writeToProtoCommonState(childProto, LayerVector::StateSet::Drawing, traceFlags);
4165 });
4166 }
4167}
4168
Vishnu Nair8406fd72019-07-30 11:29:31 -07004169LayersProto SurfaceFlinger::dumpProtoFromMainThread(uint32_t traceFlags) {
4170 LayersProto layersProto;
4171 postMessageSync(new LambdaMessage([&]() { layersProto = dumpDrawingStateProto(traceFlags); }));
4172 return layersProto;
4173}
4174
Vishnu Nair0f085c62019-08-30 08:49:12 -07004175void SurfaceFlinger::dumpOffscreenLayers(std::string& result) {
4176 result.append("Offscreen Layers:\n");
4177 postMessageSync(new LambdaMessage([&]() {
4178 for (Layer* offscreenLayer : mOffscreenLayers) {
4179 offscreenLayer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
4180 layer->dumpCallingUidPid(result);
4181 });
4182 }
4183 }));
4184}
4185
Dominik Laskowskic2867142019-01-21 11:33:38 -08004186void SurfaceFlinger::dumpAllLocked(const DumpArgs& args, std::string& result) const {
4187 const bool colorize = !args.empty() && args[0] == String16("--color");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004188 Colorizer colorizer(colorize);
4189
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004190 // figure out if we're stuck somewhere
4191 const nsecs_t now = systemTime();
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004192 const nsecs_t inTransaction(mDebugInTransaction);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004193 nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
4194
4195 /*
Andy McFadden4803b742012-09-24 19:07:20 -07004196 * Dump library configuration.
4197 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004198
4199 colorizer.bold(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004200 result.append("Build configuration:");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004201 colorizer.reset(result);
Andy McFadden4803b742012-09-24 19:07:20 -07004202 appendSfConfigString(result);
4203 appendUiConfigString(result);
4204 appendGuiConfigString(result);
4205 result.append("\n");
4206
Dominik Laskowskie9ef7c42018-03-12 19:34:30 -07004207 result.append("\nDisplay identification data:\n");
4208 dumpDisplayIdentificationData(result);
4209
Courtney Goeltzenleuchterf3b2de12017-03-27 12:18:12 -06004210 result.append("\nWide-Color information:\n");
4211 dumpWideColorInfo(result);
4212
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004213 colorizer.bold(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004214 result.append("Sync configuration: ");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004215 colorizer.reset(result);
Mathias Agopianca088332013-03-28 17:44:13 -07004216 result.append(SyncFeatures::getInstance().toString());
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004217 result.append("\n\n");
Mathias Agopianca088332013-03-28 17:44:13 -07004218
Andy McFadden41d67d72014-04-25 16:58:34 -07004219 colorizer.bold(result);
Dominik Laskowski98041832019-08-01 18:35:59 -07004220 result.append("Scheduler:\n");
Andy McFadden41d67d72014-04-25 16:58:34 -07004221 colorizer.reset(result);
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004222 dumpVSync(result);
Dan Stozab90cf072015-03-05 11:05:59 -08004223 result.append("\n");
Dominik Laskowskid9e4de62019-01-21 14:23:01 -08004224
Dan Stozab90cf072015-03-05 11:05:59 -08004225 dumpStaticScreenStats(result);
4226 result.append("\n");
4227
Alec Mouri40189b02019-03-05 15:07:54 -08004228 StringAppendF(&result, "Total missed frame count: %u\n", mFrameMissedCount.load());
4229 StringAppendF(&result, "HWC missed frame count: %u\n", mHwcFrameMissedCount.load());
4230 StringAppendF(&result, "GPU missed frame count: %u\n\n", mGpuFrameMissedCount.load());
Marissa Wallcfcdaa52018-05-21 15:45:59 -07004231
Dan Stozae77c7662016-05-13 11:37:28 -07004232 dumpBufferingStats(result);
4233
Andy McFadden4803b742012-09-24 19:07:20 -07004234 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004235 * Dump the visible layer list
4236 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004237 colorizer.bold(result);
chaviweadf0d42019-08-12 13:28:29 -07004238 StringAppendF(&result, "Visible layers (count = %zu)\n", mNumLayers.load());
Yiwei Zhang5434a782018-12-05 18:06:32 -08004239 StringAppendF(&result, "GraphicBufferProducers: %zu, max %zu\n",
4240 mGraphicBufferProducerList.size(), mMaxGraphicBufferProducerListSize);
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004241 colorizer.reset(result);
chaviw1d044282017-09-27 12:19:28 -07004242
Chia-I Wu2f884132018-09-13 15:17:58 -07004243 {
Lloyd Pique207def92019-02-28 16:09:52 -08004244 StringAppendF(&result, "Composition layers\n");
4245 mDrawingState.traverseInZOrder([&](Layer* layer) {
4246 auto compositionLayer = layer->getCompositionLayer();
4247 if (compositionLayer) compositionLayer->dump(result);
4248 });
4249 }
4250
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004251 /*
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004252 * Dump Display state
4253 */
4254
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004255 colorizer.bold(result);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004256 StringAppendF(&result, "Displays (%zu entries)\n", mDisplays.size());
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004257 colorizer.reset(result);
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004258 for (const auto& [token, display] : mDisplays) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004259 display->dump(result);
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004260 }
Chia-I Wu1e043612018-03-01 09:45:09 -08004261 result.append("\n");
Mathias Agopian5f20e2d2012-08-10 18:50:38 -07004262
4263 /*
Lloyd Piquec3cb7292019-05-17 15:25:14 -07004264 * Dump CompositionEngine state
4265 */
4266
4267 mCompositionEngine->dump(result);
4268
4269 /*
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004270 * Dump SurfaceFlinger global state
4271 */
4272
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004273 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004274 result.append("SurfaceFlinger global state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004275 colorizer.reset(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004276
Lloyd Piqueb97e04f2018-10-18 17:07:05 -07004277 getRenderEngine().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004278
Ady Abrahama3b08ef2019-07-15 18:43:10 -07004279 DebugEGLImageTracker::getInstance()->dump(result);
4280
Dominik Laskowski075d3172018-05-24 15:50:06 -07004281 if (const auto display = getDefaultDisplayDeviceLocked()) {
Lloyd Pique32cbe282018-10-19 13:09:22 -07004282 display->getCompositionDisplay()->getState().undefinedRegion.dump(result,
4283 "undefinedRegion");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004284 StringAppendF(&result, " orientation=%d, isPoweredOn=%d\n", display->getOrientation(),
4285 display->isPoweredOn());
Lloyd Pique2ae2b3b2017-12-14 17:18:17 -08004286 }
Yiwei Zhang5434a782018-12-05 18:06:32 -08004287 StringAppendF(&result,
4288 " transaction-flags : %08x\n"
4289 " gpu_to_cpu_unsupported : %d\n",
4290 mTransactionFlags.load(), !mGpuToCpuSupported);
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004291
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004292 if (const auto displayId = getInternalDisplayIdLocked();
Dominik Laskowski075d3172018-05-24 15:50:06 -07004293 displayId && getHwComposer().isConnected(*displayId)) {
4294 const auto activeConfig = getHwComposer().getActiveConfig(*displayId);
Yiwei Zhang5434a782018-12-05 18:06:32 -08004295 StringAppendF(&result,
4296 " refresh-rate : %f fps\n"
4297 " x-dpi : %f\n"
4298 " y-dpi : %f\n",
4299 1e9 / activeConfig->getVsyncPeriod(), activeConfig->getDpiX(),
4300 activeConfig->getDpiY());
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004301 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004302
Yiwei Zhang5434a782018-12-05 18:06:32 -08004303 StringAppendF(&result, " transaction time: %f us\n", inTransactionDuration / 1000.0);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004304
Dan Stozae22aec72016-08-01 13:20:59 -07004305 /*
Yichi Chenadc69612018-09-15 14:51:18 +08004306 * Tracing state
4307 */
4308 mTracing.dump(result);
4309 result.append("\n");
4310
4311 /*
Dan Stozae22aec72016-08-01 13:20:59 -07004312 * HWC layer minidump
4313 */
Dominik Laskowski9fae1022018-05-29 13:17:40 -07004314 for (const auto& [token, display] : mDisplays) {
Dominik Laskowski075d3172018-05-24 15:50:06 -07004315 const auto displayId = display->getId();
4316 if (!displayId) {
Dan Stozae22aec72016-08-01 13:20:59 -07004317 continue;
4318 }
4319
Yiwei Zhang5434a782018-12-05 18:06:32 -08004320 StringAppendF(&result, "Display %s HWC layers:\n", to_string(*displayId).c_str());
Dan Stozae22aec72016-08-01 13:20:59 -07004321 Layer::miniDumpHeader(result);
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004322 const sp<DisplayDevice> displayDevice = display;
4323 mCurrentState.traverseInZOrder(
4324 [&](Layer* layer) { layer->miniDump(result, displayDevice); });
Dan Stozae22aec72016-08-01 13:20:59 -07004325 result.append("\n");
4326 }
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004327
4328 /*
4329 * Dump HWComposer state
4330 */
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004331 colorizer.bold(result);
Mathias Agopian74d211a2013-04-22 16:55:35 +02004332 result.append("h/w composer state:\n");
Mathias Agopian3e25fd82013-04-22 17:52:16 +02004333 colorizer.reset(result);
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004334 bool hwcDisabled = mDebugDisableHWC || mDebugRegion;
Yiwei Zhang5434a782018-12-05 18:06:32 -08004335 StringAppendF(&result, " h/w composer %s\n", hwcDisabled ? "disabled" : "enabled");
Dominik Laskowski075d3172018-05-24 15:50:06 -07004336 getHwComposer().dump(result);
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004337
4338 /*
4339 * Dump gralloc state
4340 */
4341 const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
4342 alloc.dump(result);
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004343
4344 /*
4345 * Dump VrFlinger state if in use.
4346 */
4347 if (mVrFlingerRequestsDisplay && mVrFlinger) {
4348 result.append("VrFlinger state:\n");
Yiwei Zhang5434a782018-12-05 18:06:32 -08004349 result.append(mVrFlinger->Dump());
Karthik Ravi Shankar171155a2017-06-28 15:40:24 -07004350 result.append("\n");
4351 }
Ana Krulecb43429d2019-01-09 14:28:51 -08004352
Yiwei Zhang7eb58b72019-04-22 19:00:02 -07004353 result.append(mTimeStats->miniDump());
4354 result.append("\n");
Mathias Agopian82d7ab62012-01-19 18:34:40 -08004355}
4356
Chia-I Wu28f320b2018-05-03 11:02:56 -07004357void SurfaceFlinger::updateColorMatrixLocked() {
4358 mat4 colorMatrix;
4359 if (mGlobalSaturationFactor != 1.0f) {
4360 // Rec.709 luma coefficients
4361 float3 luminance{0.213f, 0.715f, 0.072f};
4362 luminance *= 1.0f - mGlobalSaturationFactor;
4363 mat4 saturationMatrix = mat4(
4364 vec4{luminance.r + mGlobalSaturationFactor, luminance.r, luminance.r, 0.0f},
4365 vec4{luminance.g, luminance.g + mGlobalSaturationFactor, luminance.g, 0.0f},
4366 vec4{luminance.b, luminance.b, luminance.b + mGlobalSaturationFactor, 0.0f},
4367 vec4{0.0f, 0.0f, 0.0f, 1.0f}
4368 );
4369 colorMatrix = mClientColorMatrix * saturationMatrix * mDaltonizer();
4370 } else {
4371 colorMatrix = mClientColorMatrix * mDaltonizer();
4372 }
4373
4374 if (mCurrentState.colorMatrix != colorMatrix) {
4375 mCurrentState.colorMatrix = colorMatrix;
4376 mCurrentState.colorMatrixChanged = true;
4377 setTransactionFlags(eTransactionNeeded);
4378 }
4379}
4380
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004381status_t SurfaceFlinger::CheckTransactCodeCredentials(uint32_t code) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004382#pragma clang diagnostic push
4383#pragma clang diagnostic error "-Wswitch-enum"
4384 switch (static_cast<ISurfaceComposerTag>(code)) {
4385 // These methods should at minimum make sure that the client requested
4386 // access to SF.
Dan Stozae3344402018-08-20 19:53:42 +00004387 case BOOT_FINISHED:
4388 case CLEAR_ANIMATION_FRAME_STATS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004389 case CREATE_DISPLAY:
4390 case DESTROY_DISPLAY:
Dan Stozae3344402018-08-20 19:53:42 +00004391 case ENABLE_VSYNC_INJECTIONS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004392 case GET_ANIMATION_FRAME_STATS:
4393 case GET_HDR_CAPABILITIES:
4394 case SET_ACTIVE_CONFIG:
Ady Abraham838de062019-02-04 10:24:03 -08004395 case SET_ALLOWED_DISPLAY_CONFIGS:
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08004396 case GET_ALLOWED_DISPLAY_CONFIGS:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004397 case SET_ACTIVE_COLOR_MODE:
Chia-I Wu90f669f2017-10-05 14:24:41 -07004398 case INJECT_VSYNC:
Kevin DuBois9c0a1762018-10-16 13:32:31 -07004399 case SET_POWER_MODE:
Kevin DuBois74e53772018-11-19 10:52:38 -08004400 case GET_DISPLAYED_CONTENT_SAMPLING_ATTRIBUTES:
Kevin DuBois1d4249a2018-08-29 10:45:14 -07004401 case SET_DISPLAY_CONTENT_SAMPLING_ENABLED:
Ady Abraham8532d012019-05-08 14:50:56 -07004402 case GET_DISPLAYED_CONTENT_SAMPLE:
4403 case NOTIFY_POWER_HINT: {
Robert Carrd4ae7f32018-06-07 16:10:57 -07004404 if (!callingThreadHasUnscopedSurfaceFlingerAccess()) {
4405 IPCThreadState* ipc = IPCThreadState::self();
4406 ALOGE("Permission Denial: can't access SurfaceFlinger pid=%d, uid=%d",
4407 ipc->getCallingPid(), ipc->getCallingUid());
Mathias Agopian375f5632009-06-15 18:24:59 -07004408 return PERMISSION_DENIED;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004409 }
Robert Carr1db73f62016-12-21 12:58:51 -08004410 return OK;
4411 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004412 case GET_LAYER_DEBUG_INFO: {
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004413 IPCThreadState* ipc = IPCThreadState::self();
4414 const int pid = ipc->getCallingPid();
4415 const int uid = ipc->getCallingUid();
Ana Krulec13be8ad2018-08-21 02:43:56 +00004416 if ((uid != AID_SHELL) && !PermissionCache::checkPermission(sDump, pid, uid)) {
4417 ALOGE("Layer debug info permission denied for pid=%d, uid=%d", pid, uid);
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004418 return PERMISSION_DENIED;
4419 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004420 return OK;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004421 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004422 // Used by apps to hook Choreographer to SurfaceFlinger.
4423 case CREATE_DISPLAY_EVENT_CONNECTION:
4424 // The following calls are currently used by clients that do not
4425 // request necessary permissions. However, they do not expose any secret
4426 // information, so it is OK to pass them.
4427 case AUTHENTICATE_SURFACE:
Peiyong Lind1fedb42019-03-11 17:48:41 -07004428 case GET_ACTIVE_COLOR_MODE:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004429 case GET_ACTIVE_CONFIG:
Dominik Laskowskidcb38bb2019-01-25 02:35:50 -08004430 case GET_PHYSICAL_DISPLAY_IDS:
4431 case GET_PHYSICAL_DISPLAY_TOKEN:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004432 case GET_DISPLAY_COLOR_MODES:
Daniel Solomon42d04562019-01-20 21:03:19 -08004433 case GET_DISPLAY_NATIVE_PRIMARIES:
Ana Krulec13be8ad2018-08-21 02:43:56 +00004434 case GET_DISPLAY_CONFIGS:
4435 case GET_DISPLAY_STATS:
4436 case GET_SUPPORTED_FRAME_TIMESTAMPS:
4437 // Calling setTransactionState is safe, because you need to have been
4438 // granted a reference to Client* and Handle* to do anything with it.
4439 case SET_TRANSACTION_STATE:
Robert Carrb89ea9d2018-12-10 13:01:14 -08004440 case CREATE_CONNECTION:
Ady Abraham37965d42018-11-01 13:43:32 -07004441 case GET_COLOR_MANAGEMENT:
Peiyong Lin3c2791e2019-01-14 17:05:18 -08004442 case GET_COMPOSITION_PREFERENCE:
Marissa Wallebc2c052019-01-16 19:16:55 -08004443 case GET_PROTECTED_CONTENT_SUPPORT:
Dan Gittik57e63c52019-01-18 16:37:54 +00004444 case IS_WIDE_COLOR_DISPLAY:
4445 case GET_DISPLAY_BRIGHTNESS_SUPPORT:
4446 case SET_DISPLAY_BRIGHTNESS: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004447 return OK;
4448 }
Chong Zhangd1690d12019-10-04 17:47:13 +00004449 case CAPTURE_LAYERS:
Dan Stoza84ab9372018-12-17 15:27:57 -08004450 case CAPTURE_SCREEN:
4451 case ADD_REGION_SAMPLING_LISTENER:
4452 case REMOVE_REGION_SAMPLING_LISTENER: {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004453 // codes that require permission check
chaviwa76b2712017-09-20 12:02:26 -07004454 IPCThreadState* ipc = IPCThreadState::self();
4455 const int pid = ipc->getCallingPid();
4456 const int uid = ipc->getCallingUid();
4457 if ((uid != AID_GRAPHICS) &&
4458 !PermissionCache::checkPermission(sReadFramebuffer, pid, uid)) {
4459 ALOGE("Permission Denial: can't read framebuffer pid=%d, uid=%d", pid, uid);
4460 return PERMISSION_DENIED;
4461 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004462 return OK;
4463 }
4464 // The following codes are deprecated and should never be allowed to access SF.
4465 case CONNECT_DISPLAY_UNUSED:
4466 case CREATE_GRAPHIC_BUFFER_ALLOC_UNUSED: {
4467 ALOGE("Attempting to access SurfaceFlinger with unused code: %u", code);
4468 return PERMISSION_DENIED;
chaviwa76b2712017-09-20 12:02:26 -07004469 }
chaviw93df2ea2019-04-30 16:45:12 -07004470 case CAPTURE_SCREEN_BY_ID: {
4471 IPCThreadState* ipc = IPCThreadState::self();
4472 const int uid = ipc->getCallingUid();
Peiyong Lin96cfebc2019-05-15 11:36:13 -07004473 if (uid == AID_ROOT || uid == AID_GRAPHICS || uid == AID_SYSTEM || uid == AID_SHELL) {
chaviw93df2ea2019-04-30 16:45:12 -07004474 return OK;
4475 }
4476 return PERMISSION_DENIED;
4477 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004478 }
Ana Krulec13be8ad2018-08-21 02:43:56 +00004479
4480 // These codes are used for the IBinder protocol to either interrogate the recipient
4481 // side of the transaction for its canonical interface descriptor or to dump its state.
4482 // We let them pass by default.
4483 if (code == IBinder::INTERFACE_TRANSACTION || code == IBinder::DUMP_TRANSACTION ||
4484 code == IBinder::PING_TRANSACTION || code == IBinder::SHELL_COMMAND_TRANSACTION ||
4485 code == IBinder::SYSPROPS_TRANSACTION) {
4486 return OK;
4487 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004488 // Numbers from 1000 to 1034 are currently used for backdoors. The code
Ana Krulec13be8ad2018-08-21 02:43:56 +00004489 // in onTransact verifies that the user is root, and has access to use SF.
Ady Abraham34392f72019-04-10 11:29:27 -07004490 if (code >= 1000 && code <= 1035) {
Ana Krulec13be8ad2018-08-21 02:43:56 +00004491 ALOGV("Accessing SurfaceFlinger through backdoor code: %u", code);
4492 return OK;
4493 }
4494 ALOGE("Permission Denial: SurfaceFlinger did not recognize request code: %u", code);
4495 return PERMISSION_DENIED;
4496#pragma clang diagnostic pop
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004497}
4498
Ana Krulec13be8ad2018-08-21 02:43:56 +00004499status_t SurfaceFlinger::onTransact(uint32_t code, const Parcel& data, Parcel* reply,
4500 uint32_t flags) {
Fabien Sanglard6e8e98a2016-10-27 20:04:11 -07004501 status_t credentialCheck = CheckTransactCodeCredentials(code);
4502 if (credentialCheck != OK) {
4503 return credentialCheck;
4504 }
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07004505
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004506 status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
4507 if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
Mathias Agopianb8a55602009-06-26 19:06:36 -07004508 CHECK_INTERFACE(ISurfaceComposer, data, reply);
Romain Guy8c6bbd62017-06-05 13:51:43 -07004509 IPCThreadState* ipc = IPCThreadState::self();
4510 const int uid = ipc->getCallingUid();
4511 if (CC_UNLIKELY(uid != AID_SYSTEM
4512 && !PermissionCache::checkCallingPermission(sHardwareTest))) {
Mathias Agopian375f5632009-06-15 18:24:59 -07004513 const int pid = ipc->getCallingPid();
Steve Blocke6f43dd2012-01-06 19:20:56 +00004514 ALOGE("Permission Denial: "
Mathias Agopian375f5632009-06-15 18:24:59 -07004515 "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004516 return PERMISSION_DENIED;
4517 }
4518 int n;
4519 switch (code) {
Mathias Agopian01b76682009-04-16 20:04:08 -07004520 case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
Mathias Agopian35b48d12010-09-13 22:57:58 -07004521 case 1001: // SHOW_FPS, NOT SUPPORTED ANYMORE
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004522 return NO_ERROR;
4523 case 1002: // SHOW_UPDATES
4524 n = data.readInt32();
4525 mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
Mathias Agopian53331da2011-08-22 21:44:41 -07004526 invalidateHwcGeometry();
4527 repaintEverything();
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004528 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004529 case 1004:{ // repaint everything
Mathias Agopian53331da2011-08-22 21:44:41 -07004530 repaintEverything();
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004531 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004532 }
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004533 case 1005:{ // force transaction
Steven Thomas6d8110b2017-08-31 18:24:21 -07004534 Mutex::Autolock _l(mStateLock);
Mathias Agopiane57f2922012-08-09 16:29:12 -07004535 setTransactionFlags(
4536 eTransactionNeeded|
4537 eDisplayTransactionNeeded|
4538 eTraversalNeeded);
Mathias Agopiancbb288b2009-09-07 16:32:45 -07004539 return NO_ERROR;
4540 }
Mathias Agopian4d143ee2012-02-23 20:05:39 -08004541 case 1006:{ // send empty update
4542 signalRefresh();
4543 return NO_ERROR;
4544 }
Mathias Agopian53331da2011-08-22 21:44:41 -07004545 case 1008: // toggle use of hw composer
4546 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004547 mDebugDisableHWC = n != 0;
Mathias Agopian53331da2011-08-22 21:44:41 -07004548 invalidateHwcGeometry();
4549 repaintEverything();
4550 return NO_ERROR;
Mathias Agopiana4583642011-08-23 18:03:18 -07004551 case 1009: // toggle use of transform hint
4552 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004553 mDebugDisableTransformHint = n != 0;
Mathias Agopiana4583642011-08-23 18:03:18 -07004554 invalidateHwcGeometry();
4555 repaintEverything();
4556 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004557 case 1010: // interrogate.
Mathias Agopian01b76682009-04-16 20:04:08 -07004558 reply->writeInt32(0);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004559 reply->writeInt32(0);
4560 reply->writeInt32(mDebugRegion);
Mathias Agopianb9494d52012-04-18 02:28:45 -07004561 reply->writeInt32(0);
Dianne Hackborn12839be2012-02-06 21:21:05 -08004562 reply->writeInt32(mDebugDisableHWC);
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004563 return NO_ERROR;
4564 case 1013: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004565 const auto display = getDefaultDisplayDevice();
Dominik Laskowski45de9bd2018-06-11 17:44:10 -07004566 if (!display) {
4567 return NAME_NOT_FOUND;
4568 }
4569
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004570 reply->writeInt32(display->getPageFlipCount());
Mathias Agopianff2ed702013-09-01 21:36:12 -07004571 return NO_ERROR;
4572 }
4573 case 1014: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004574 Mutex::Autolock _l(mStateLock);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004575 // daltonize
4576 n = data.readInt32();
4577 switch (n % 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004578 case 1:
4579 mDaltonizer.setType(ColorBlindnessType::Protanomaly);
4580 break;
4581 case 2:
4582 mDaltonizer.setType(ColorBlindnessType::Deuteranomaly);
4583 break;
4584 case 3:
4585 mDaltonizer.setType(ColorBlindnessType::Tritanomaly);
4586 break;
4587 default:
4588 mDaltonizer.setType(ColorBlindnessType::None);
4589 break;
Mathias Agopianff2ed702013-09-01 21:36:12 -07004590 }
4591 if (n >= 10) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004592 mDaltonizer.setMode(ColorBlindnessMode::Correction);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004593 } else {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004594 mDaltonizer.setMode(ColorBlindnessMode::Simulation);
Mathias Agopianff2ed702013-09-01 21:36:12 -07004595 }
Chia-I Wu28f320b2018-05-03 11:02:56 -07004596
4597 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004598 return NO_ERROR;
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004599 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004600 case 1015: {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004601 Mutex::Autolock _l(mStateLock);
Alan Viverette9c5a3332013-09-12 20:04:35 -07004602 // apply a color matrix
4603 n = data.readInt32();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004604 if (n) {
Romain Guy0147a172017-06-01 13:53:56 -07004605 // color matrix is sent as a column-major mat4 matrix
Alan Viverette794c5ba2013-10-03 16:40:52 -07004606 for (size_t i = 0 ; i < 4; i++) {
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004607 for (size_t j = 0; j < 4; j++) {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004608 mClientColorMatrix[i][j] = data.readFloat();
Dan Stoza9f26a9c2016-06-22 14:51:09 -07004609 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004610 }
Alan Viverette9c5a3332013-09-12 20:04:35 -07004611 } else {
Chia-I Wu28f320b2018-05-03 11:02:56 -07004612 mClientColorMatrix = mat4();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004613 }
Romain Guy88d37dd2017-05-26 17:57:05 -07004614
4615 // Check that supplied matrix's last row is {0,0,0,1} so we can avoid
4616 // the division by w in the fragment shader
Chia-I Wu28f320b2018-05-03 11:02:56 -07004617 float4 lastRow(transpose(mClientColorMatrix)[3]);
Romain Guy88d37dd2017-05-26 17:57:05 -07004618 if (any(greaterThan(abs(lastRow - float4{0, 0, 0, 1}), float4{1e-4f}))) {
4619 ALOGE("The color transform's last row must be (0, 0, 0, 1)");
4620 }
4621
Chia-I Wu28f320b2018-05-03 11:02:56 -07004622 updateColorMatrixLocked();
Alan Viverette9c5a3332013-09-12 20:04:35 -07004623 return NO_ERROR;
4624 }
Dominik Laskowski8d32ddc2019-08-07 11:25:35 -07004625 case 1016: { // Unused.
4626 return NAME_NOT_FOUND;
Ruchi Kandoif52b3c82014-04-24 16:42:35 -07004627 }
Dan Stozaee44edd2015-03-23 15:50:23 -07004628 case 1017: {
4629 n = data.readInt32();
Dominik Laskowski9dab3432019-03-27 13:21:10 -07004630 mForceFullDamage = n != 0;
Dan Stozaee44edd2015-03-23 15:50:23 -07004631 return NO_ERROR;
4632 }
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004633 case 1018: { // Modify Choreographer's phase offset
4634 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004635 mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004636 return NO_ERROR;
4637 }
4638 case 1019: { // Modify SurfaceFlinger's phase offset
4639 n = data.readInt32();
Ana Krulecc2870422019-01-29 19:00:58 -08004640 mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
Dan Stozadb4ac3c2015-04-14 11:34:01 -07004641 return NO_ERROR;
4642 }
Irvel468051e2016-06-13 16:44:44 -07004643 case 1020: { // Layer updates interceptor
4644 n = data.readInt32();
4645 if (n) {
4646 ALOGV("Interceptor enabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004647 mInterceptor->enable(mDrawingState.layersSortedByZ, mDrawingState.displays);
Irvel468051e2016-06-13 16:44:44 -07004648 }
4649 else{
4650 ALOGV("Interceptor disabled");
Lloyd Pique4dccc412018-01-22 17:21:36 -08004651 mInterceptor->disable();
Irvel468051e2016-06-13 16:44:44 -07004652 }
4653 return NO_ERROR;
4654 }
Dan Stoza8cf150a2016-08-02 10:27:31 -07004655 case 1021: { // Disable HWC virtual displays
4656 n = data.readInt32();
4657 mUseHwcVirtualDisplays = !n;
4658 return NO_ERROR;
4659 }
Romain Guy0147a172017-06-01 13:53:56 -07004660 case 1022: { // Set saturation boost
Chia-I Wu28f320b2018-05-03 11:02:56 -07004661 Mutex::Autolock _l(mStateLock);
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004662 mGlobalSaturationFactor = std::max(0.0f, std::min(data.readFloat(), 2.0f));
Romain Guy0147a172017-06-01 13:53:56 -07004663
Chia-I Wu28f320b2018-05-03 11:02:56 -07004664 updateColorMatrixLocked();
Romain Guy0147a172017-06-01 13:53:56 -07004665 return NO_ERROR;
4666 }
Romain Guy54f154a2017-10-24 21:40:32 +01004667 case 1023: { // Set native mode
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004668 int32_t colorMode;
4669
Chia-I Wu0d711262018-05-21 15:19:35 -07004670 mDisplayColorSetting = static_cast<DisplayColorSetting>(data.readInt32());
Daniel Solomon7c7ede22019-07-11 16:35:40 -07004671 if (data.readInt32(&colorMode) == NO_ERROR) {
4672 mForceColorMode = static_cast<ColorMode>(colorMode);
4673 }
Romain Guy54f154a2017-10-24 21:40:32 +01004674 invalidateHwcGeometry();
4675 repaintEverything();
4676 return NO_ERROR;
4677 }
Peiyong Lin4bac91c2018-10-25 09:48:33 -07004678 // Deprecate, use 1030 to check whether the device is color managed.
4679 case 1024: {
4680 return NAME_NOT_FOUND;
Romain Guy54f154a2017-10-24 21:40:32 +01004681 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004682 case 1025: { // Set layer tracing
Adrian Roos1e1a1282017-11-01 19:05:31 +01004683 n = data.readInt32();
4684 if (n) {
Yichi Chenadc69612018-09-15 14:51:18 +08004685 ALOGD("LayerTracing enabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004686 Mutex::Autolock lock(mStateLock);
4687 mTracingEnabledChanged = true;
Adrian Roos1e1a1282017-11-01 19:05:31 +01004688 mTracing.enable();
Adrian Roos1e1a1282017-11-01 19:05:31 +01004689 reply->writeInt32(NO_ERROR);
4690 } else {
Yichi Chenadc69612018-09-15 14:51:18 +08004691 ALOGD("LayerTracing disabled");
Nataniel Borges2b796da2019-02-15 13:32:18 -08004692 bool writeFile = false;
4693 {
4694 Mutex::Autolock lock(mStateLock);
4695 mTracingEnabledChanged = true;
4696 writeFile = mTracing.disable();
4697 }
4698
4699 if (writeFile) {
4700 reply->writeInt32(mTracing.writeToFile());
4701 } else {
4702 reply->writeInt32(NO_ERROR);
4703 }
Adrian Roos1e1a1282017-11-01 19:05:31 +01004704 }
4705 return NO_ERROR;
4706 }
Vishnu Nair87704c92018-01-08 15:32:57 -08004707 case 1026: { // Get layer tracing status
4708 reply->writeBool(mTracing.isEnabled());
4709 return NO_ERROR;
4710 }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004711 // Is a DisplayColorSetting supported?
4712 case 1027: {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004713 const auto display = getDefaultDisplayDevice();
4714 if (!display) {
Chia-I Wu0d711262018-05-21 15:19:35 -07004715 return NAME_NOT_FOUND;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004716 }
Chia-I Wu0d711262018-05-21 15:19:35 -07004717
4718 DisplayColorSetting setting = static_cast<DisplayColorSetting>(data.readInt32());
4719 switch (setting) {
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004720 case DisplayColorSetting::kManaged:
Peiyong Lin13effd12018-07-24 17:01:47 -07004721 reply->writeBool(useColorManagement);
Chia-I Wu0d711262018-05-21 15:19:35 -07004722 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004723 case DisplayColorSetting::kUnmanaged:
Chia-I Wu0d711262018-05-21 15:19:35 -07004724 reply->writeBool(true);
4725 break;
Lloyd Pique6a3b4462019-03-07 20:58:12 -08004726 case DisplayColorSetting::kEnhanced:
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004727 reply->writeBool(display->hasRenderIntent(RenderIntent::ENHANCE));
Chia-I Wu0d711262018-05-21 15:19:35 -07004728 break;
4729 default: // vendor display color setting
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004730 reply->writeBool(
4731 display->hasRenderIntent(static_cast<RenderIntent>(setting)));
Chia-I Wu0d711262018-05-21 15:19:35 -07004732 break;
4733 }
4734 return NO_ERROR;
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004735 }
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004736 // Is VrFlinger active?
4737 case 1028: {
4738 Mutex::Autolock _l(mStateLock);
Lloyd Pique441d5042018-10-18 16:49:51 -07004739 reply->writeBool(getHwComposer().isUsingVrComposer());
Steven Thomas97f1f4c2018-06-01 12:04:16 -07004740 return NO_ERROR;
4741 }
Nataniel Borges2b796da2019-02-15 13:32:18 -08004742 // Set buffer size for SF tracing (value in KB)
4743 case 1029: {
4744 n = data.readInt32();
4745 if (n <= 0 || n > MAX_TRACING_MEMORY) {
4746 ALOGW("Invalid buffer size: %d KB", n);
4747 reply->writeInt32(BAD_VALUE);
4748 return BAD_VALUE;
4749 }
4750
4751 ALOGD("Updating trace buffer to %d KB", n);
4752 mTracing.setBufferSize(n * 1024);
4753 reply->writeInt32(NO_ERROR);
4754 return NO_ERROR;
4755 }
Peiyong Lin13effd12018-07-24 17:01:47 -07004756 // Is device color managed?
4757 case 1030: {
4758 reply->writeBool(useColorManagement);
4759 return NO_ERROR;
4760 }
Peiyong Lin9d846a52018-11-05 13:18:20 -08004761 // Override default composition data space
4762 // adb shell service call SurfaceFlinger 1031 i32 1 DATASPACE_NUMBER DATASPACE_NUMBER \
4763 // && adb shell stop zygote && adb shell start zygote
4764 // to restore: adb shell service call SurfaceFlinger 1031 i32 0 && \
4765 // adb shell stop zygote && adb shell start zygote
4766 case 1031: {
4767 Mutex::Autolock _l(mStateLock);
4768 n = data.readInt32();
4769 if (n) {
4770 n = data.readInt32();
4771 if (n) {
4772 Dataspace dataspace = static_cast<Dataspace>(n);
4773 if (!validateCompositionDataspace(dataspace)) {
4774 return BAD_VALUE;
4775 }
4776 mDefaultCompositionDataspace = dataspace;
4777 }
4778 n = data.readInt32();
4779 if (n) {
4780 Dataspace dataspace = static_cast<Dataspace>(n);
4781 if (!validateCompositionDataspace(dataspace)) {
4782 return BAD_VALUE;
4783 }
4784 mWideColorGamutCompositionDataspace = dataspace;
4785 }
4786 } else {
4787 // restore composition data space.
4788 mDefaultCompositionDataspace = defaultCompositionDataspace;
4789 mWideColorGamutCompositionDataspace = wideColorGamutCompositionDataspace;
4790 }
4791 return NO_ERROR;
4792 }
Vishnu Nair9245d3b2019-03-22 13:38:56 -07004793 // Set trace flags
4794 case 1033: {
4795 n = data.readUint32();
4796 ALOGD("Updating trace flags to 0x%x", n);
4797 mTracing.setTraceFlags(n);
4798 reply->writeInt32(NO_ERROR);
4799 return NO_ERROR;
4800 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004801 case 1034: {
4802 // TODO(b/129297325): expose this via developer menu option
4803 n = data.readInt32();
Steven Thomas2bbaabe2019-08-28 16:08:35 -07004804 if (n && !mRefreshRateOverlay &&
4805 mRefreshRateConfigs->refreshRateSwitchingSupported()) {
Ady Abrahamfed164b2019-05-10 17:12:54 -07004806 RefreshRateType type;
4807 {
4808 std::lock_guard<std::mutex> lock(mActiveConfigLock);
4809 type = mDesiredActiveConfig.type;
4810 }
Ady Abraham03b02dd2019-03-21 15:40:11 -07004811 mRefreshRateOverlay = std::make_unique<RefreshRateOverlay>(*this);
Ady Abrahamfed164b2019-05-10 17:12:54 -07004812 mRefreshRateOverlay->changeRefreshRate(type);
Ady Abraham03b02dd2019-03-21 15:40:11 -07004813 } else if (!n) {
4814 mRefreshRateOverlay.reset();
4815 }
4816 return NO_ERROR;
4817 }
Ady Abraham34392f72019-04-10 11:29:27 -07004818 case 1035: {
4819 n = data.readInt32();
4820 mDebugDisplayConfigSetByBackdoor = false;
4821 if (n >= 0) {
4822 const auto displayToken = getInternalDisplayToken();
4823 status_t result = setAllowedDisplayConfigs(displayToken, {n});
4824 if (result != NO_ERROR) {
4825 return result;
4826 }
4827 mDebugDisplayConfigSetByBackdoor = true;
4828 }
4829 return NO_ERROR;
4830 }
The Android Open Source Projectedbf3b62009-03-03 19:31:44 -08004831 }
4832 }
4833 return err;
4834}
4835
Steven Thomas6d8110b2017-08-31 18:24:21 -07004836void SurfaceFlinger::repaintEverything() {
Lloyd Piquef1c675b2018-09-12 20:45:39 -07004837 mRepaintEverything = true;
Dan Stozac7a25ad2018-04-12 11:45:09 -07004838 signalTransaction();
Steven Thomas6d8110b2017-08-31 18:24:21 -07004839}
4840
Ana Krulec7d1d6832018-12-27 11:10:09 -08004841void SurfaceFlinger::repaintEverythingForHWC() {
4842 mRepaintEverything = true;
Ady Abraham8532d012019-05-08 14:50:56 -07004843 mEventQueue->invalidate();
Ana Krulec7d1d6832018-12-27 11:10:09 -08004844}
4845
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004846// A simple RAII class to disconnect from an ANativeWindow* when it goes out of scope
4847class WindowDisconnector {
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004848public:
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004849 WindowDisconnector(ANativeWindow* window, int api) : mWindow(window), mApi(api) {}
4850 ~WindowDisconnector() {
4851 native_window_api_disconnect(mWindow, mApi);
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004852 }
4853
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004854private:
4855 ANativeWindow* mWindow;
4856 const int mApi;
Mathias Agopian2ed0fe52013-07-08 17:09:41 -07004857};
4858
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004859status_t SurfaceFlinger::captureScreen(const sp<IBinder>& displayToken,
Robert Carr108b2c72019-04-02 16:32:58 -07004860 sp<GraphicBuffer>* outBuffer, bool& outCapturedSecureLayers,
4861 const Dataspace reqDataspace,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004862 const ui::PixelFormat reqPixelFormat, Rect sourceCrop,
chaviw0e3479f2018-09-10 16:49:30 -07004863 uint32_t reqWidth, uint32_t reqHeight,
4864 bool useIdentityTransform,
Robert Carrfa8855f2019-02-19 10:05:00 -08004865 ISurfaceComposer::Rotation rotation,
4866 bool captureSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07004867 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08004868
Dominik Laskowskieecd6592018-05-29 10:25:41 -07004869 if (!displayToken) return BAD_VALUE;
chaviwa76b2712017-09-20 12:02:26 -07004870
Chia-I Wuc80dcbb2018-08-24 15:34:02 -07004871 auto renderAreaRotation = fromSurfaceComposerRotation(rotation);
4872
Chia-I Wu20261cb2018-08-23 12:55:44 -07004873 sp<DisplayDevice> display;
4874 {
4875 Mutex::Autolock _l(mStateLock);
Garfield Tan3b1b8af2018-03-16 17:37:33 -07004876
Chia-I Wu20261cb2018-08-23 12:55:44 -07004877 display = getDisplayDeviceLocked(displayToken);
4878 if (!display) return BAD_VALUE;
4879
Chia-I Wucb023152018-08-28 12:57:23 -07004880 // set the requested width/height to the logical display viewport size
4881 // by default
4882 if (reqWidth == 0 || reqHeight == 0) {
4883 reqWidth = uint32_t(display->getViewport().width());
4884 reqHeight = uint32_t(display->getViewport().height());
Chia-I Wu20261cb2018-08-23 12:55:44 -07004885 }
Yiwei Zhang06a58e22018-08-20 16:42:23 -07004886 }
4887
Peiyong Lin0e003c92018-09-17 11:09:51 -07004888 DisplayRenderArea renderArea(display, sourceCrop, reqWidth, reqHeight, reqDataspace,
Robert Carrfa8855f2019-02-19 10:05:00 -08004889 renderAreaRotation, captureSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004890
Dominik Laskowskiccf37d72019-02-01 16:47:58 -08004891 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4892 std::placeholders::_1);
Peiyong Lin0e003c92018-09-17 11:09:51 -07004893 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07004894 useIdentityTransform, outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07004895}
4896
chaviw93df2ea2019-04-30 16:45:12 -07004897static Dataspace pickDataspaceFromColorMode(const ColorMode colorMode) {
4898 switch (colorMode) {
4899 case ColorMode::DISPLAY_P3:
4900 case ColorMode::BT2100_PQ:
4901 case ColorMode::BT2100_HLG:
4902 case ColorMode::DISPLAY_BT2020:
4903 return Dataspace::DISPLAY_P3;
4904 default:
4905 return Dataspace::V0_SRGB;
4906 }
4907}
4908
4909const sp<DisplayDevice> SurfaceFlinger::getDisplayByIdOrLayerStack(uint64_t displayOrLayerStack) {
4910 const sp<IBinder> displayToken = getPhysicalDisplayTokenLocked(DisplayId{displayOrLayerStack});
4911 if (displayToken) {
4912 return getDisplayDeviceLocked(displayToken);
4913 }
4914 // Couldn't find display by displayId. Try to get display by layerStack since virtual displays
4915 // may not have a displayId.
4916 for (const auto& [token, display] : mDisplays) {
4917 if (display->getLayerStack() == displayOrLayerStack) {
4918 return display;
4919 }
4920 }
4921 return nullptr;
4922}
4923
4924status_t SurfaceFlinger::captureScreen(uint64_t displayOrLayerStack, Dataspace* outDataspace,
4925 sp<GraphicBuffer>* outBuffer) {
4926 sp<DisplayDevice> display;
4927 uint32_t width;
4928 uint32_t height;
4929 ui::Transform::orientation_flags captureOrientation;
4930 {
4931 Mutex::Autolock _l(mStateLock);
4932 display = getDisplayByIdOrLayerStack(displayOrLayerStack);
4933 if (!display) {
4934 return BAD_VALUE;
4935 }
4936
4937 width = uint32_t(display->getViewport().width());
4938 height = uint32_t(display->getViewport().height());
4939
4940 captureOrientation = fromSurfaceComposerRotation(
4941 static_cast<ISurfaceComposer::Rotation>(display->getOrientation()));
Alec Mouri21fab752019-06-20 14:12:17 -07004942 if (captureOrientation == ui::Transform::orientation_flags::ROT_90) {
4943 captureOrientation = ui::Transform::orientation_flags::ROT_270;
4944 } else if (captureOrientation == ui::Transform::orientation_flags::ROT_270) {
4945 captureOrientation = ui::Transform::orientation_flags::ROT_90;
4946 }
chaviw93df2ea2019-04-30 16:45:12 -07004947 *outDataspace =
4948 pickDataspaceFromColorMode(display->getCompositionDisplay()->getState().colorMode);
4949 }
4950
4951 DisplayRenderArea renderArea(display, Rect(), width, height, *outDataspace, captureOrientation,
4952 false /* captureSecureLayers */);
4953
4954 auto traverseLayers = std::bind(&SurfaceFlinger::traverseLayersInDisplay, this, display,
4955 std::placeholders::_1);
4956 bool ignored = false;
4957 return captureScreenCommon(renderArea, traverseLayers, outBuffer, ui::PixelFormat::RGBA_8888,
4958 false /* useIdentityTransform */,
4959 ignored /* outCapturedSecureLayers */);
4960}
4961
Robert Carr866455f2019-04-02 16:28:26 -07004962status_t SurfaceFlinger::captureLayers(
4963 const sp<IBinder>& layerHandleBinder, sp<GraphicBuffer>* outBuffer,
4964 const Dataspace reqDataspace, const ui::PixelFormat reqPixelFormat, const Rect& sourceCrop,
4965 const std::unordered_set<sp<IBinder>, ISurfaceComposer::SpHash<IBinder>>& excludeHandles,
4966 float frameScale, bool childrenOnly) {
chaviwa76b2712017-09-20 12:02:26 -07004967 ATRACE_CALL();
4968
4969 class LayerRenderArea : public RenderArea {
4970 public:
Robert Carr578038f2018-03-09 12:25:24 -08004971 LayerRenderArea(SurfaceFlinger* flinger, const sp<Layer>& layer, const Rect crop,
Peiyong Lin0e003c92018-09-17 11:09:51 -07004972 int32_t reqWidth, int32_t reqHeight, Dataspace reqDataSpace,
4973 bool childrenOnly)
4974 : RenderArea(reqWidth, reqHeight, CaptureFill::CLEAR, reqDataSpace),
Robert Carr578038f2018-03-09 12:25:24 -08004975 mLayer(layer),
4976 mCrop(crop),
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004977 mNeedsFiltering(false),
Robert Carr578038f2018-03-09 12:25:24 -08004978 mFlinger(flinger),
4979 mChildrenOnly(childrenOnly) {}
Peiyong Linefefaac2018-08-17 12:27:51 -07004980 const ui::Transform& getTransform() const override { return mTransform; }
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004981 Rect getBounds() const override {
4982 const Layer::State& layerState(mLayer->getDrawingState());
4983 return mLayer->getBufferSize(layerState);
4984 }
Marissa Wall61c58622018-07-18 10:12:20 -07004985 int getHeight() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004986 return mLayer->getBufferSize(mLayer->getDrawingState()).getHeight();
Marissa Wall61c58622018-07-18 10:12:20 -07004987 }
Vishnu Nair88a11f22018-11-28 18:30:57 -08004988 int getWidth() const override {
Lloyd Pique0449b0f2018-12-20 16:23:45 -08004989 return mLayer->getBufferSize(mLayer->getDrawingState()).getWidth();
Vishnu Nair88a11f22018-11-28 18:30:57 -08004990 }
chaviwa76b2712017-09-20 12:02:26 -07004991 bool isSecure() const override { return false; }
Chia-I Wu5f6664c2018-08-28 11:01:44 -07004992 bool needsFiltering() const override { return mNeedsFiltering; }
Lloyd Pique37c2c9b2018-12-04 17:25:10 -08004993 const sp<const DisplayDevice> getDisplayDevice() const override { return nullptr; }
Peiyong Lindd9b2ae2018-03-01 16:22:45 -08004994 Rect getSourceCrop() const override {
4995 if (mCrop.isEmpty()) {
4996 return getBounds();
4997 } else {
4998 return mCrop;
4999 }
5000 }
Robert Carr578038f2018-03-09 12:25:24 -08005001 class ReparentForDrawing {
5002 public:
5003 const sp<Layer>& oldParent;
5004 const sp<Layer>& newParent;
5005
Vishnu Nair4351ad52019-02-11 14:13:02 -08005006 ReparentForDrawing(const sp<Layer>& oldParent, const sp<Layer>& newParent,
5007 const Rect& drawingBounds)
Robert Carr578038f2018-03-09 12:25:24 -08005008 : oldParent(oldParent), newParent(newParent) {
Vishnu Nair4351ad52019-02-11 14:13:02 -08005009 // Compute and cache the bounds for the new parent layer.
Vishnu Nairc97b8db2019-10-29 18:19:35 -07005010 newParent->computeBounds(drawingBounds.toFloatRect(), ui::Transform(),
5011 0.f /* shadowRadius */);
Robert Carr15eae092018-03-23 13:43:53 -07005012 oldParent->setChildrenDrawingParent(newParent);
Robert Carr578038f2018-03-09 12:25:24 -08005013 }
Vishnu Nairbce6ffd2019-02-14 10:58:59 -08005014 ~ReparentForDrawing() { oldParent->setChildrenDrawingParent(oldParent); }
Robert Carr578038f2018-03-09 12:25:24 -08005015 };
5016
5017 void render(std::function<void()> drawLayers) override {
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005018 const Rect sourceCrop = getSourceCrop();
5019 // no need to check rotation because there is none
5020 mNeedsFiltering = sourceCrop.width() != getReqWidth() ||
5021 sourceCrop.height() != getReqHeight();
5022
Robert Carr578038f2018-03-09 12:25:24 -08005023 if (!mChildrenOnly) {
5024 mTransform = mLayer->getTransform().inverse();
5025 drawLayers();
5026 } else {
5027 Rect bounds = getBounds();
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005028 uint32_t w = static_cast<uint32_t>(bounds.getWidth());
5029 uint32_t h = static_cast<uint32_t>(bounds.getHeight());
chaviw32811fd2019-08-12 13:16:09 -07005030 // In the "childrenOnly" case we reparent the children to a screenshot
5031 // layer which has no properties set and which does not draw.
5032 sp<ContainerLayer> screenshotParentLayer =
Dominik Laskowski87a07e42019-10-10 20:38:02 -07005033 mFlinger->getFactory().createContainerLayer({mFlinger, nullptr,
5034 "Screenshot Parent"s, w, h, 0,
5035 LayerMetadata()});
Robert Carr578038f2018-03-09 12:25:24 -08005036
Vishnu Nair4351ad52019-02-11 14:13:02 -08005037 ReparentForDrawing reparent(mLayer, screenshotParentLayer, sourceCrop);
Robert Carr578038f2018-03-09 12:25:24 -08005038 drawLayers();
5039 }
5040 }
chaviwa76b2712017-09-20 12:02:26 -07005041
chaviwa76b2712017-09-20 12:02:26 -07005042 private:
chaviw7206d492017-11-10 16:16:12 -08005043 const sp<Layer> mLayer;
5044 const Rect mCrop;
Robert Carr578038f2018-03-09 12:25:24 -08005045
Peiyong Linefefaac2018-08-17 12:27:51 -07005046 ui::Transform mTransform;
Chia-I Wu5f6664c2018-08-28 11:01:44 -07005047 bool mNeedsFiltering;
Robert Carr578038f2018-03-09 12:25:24 -08005048
5049 SurfaceFlinger* mFlinger;
5050 const bool mChildrenOnly;
chaviwa76b2712017-09-20 12:02:26 -07005051 };
5052
Robert Carrc0df3122019-04-11 13:18:21 -07005053 int reqWidth = 0;
5054 int reqHeight = 0;
5055 sp<Layer> parent;
chaviw7206d492017-11-10 16:16:12 -08005056 Rect crop(sourceCrop);
Robert Carrc0df3122019-04-11 13:18:21 -07005057 std::unordered_set<sp<Layer>, ISurfaceComposer::SpHash<Layer>> excludeLayers;
chaviw7206d492017-11-10 16:16:12 -08005058
Robert Carrc0df3122019-04-11 13:18:21 -07005059 {
5060 Mutex::Autolock _l(mStateLock);
chaviw7206d492017-11-10 16:16:12 -08005061
Robert Carrc0df3122019-04-11 13:18:21 -07005062 parent = fromHandle(layerHandleBinder);
5063 if (parent == nullptr || parent->isRemovedFromCurrentState()) {
5064 ALOGE("captureLayers called with an invalid or removed parent");
5065 return NAME_NOT_FOUND;
5066 }
5067
5068 const int uid = IPCThreadState::self()->getCallingUid();
5069 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5070 if (!forSystem && parent->getCurrentState().flags & layer_state_t::eLayerSecure) {
5071 ALOGW("Attempting to capture secure layer: PERMISSION_DENIED");
5072 return PERMISSION_DENIED;
5073 }
5074
5075 if (sourceCrop.width() <= 0) {
5076 crop.left = 0;
5077 crop.right = parent->getBufferSize(parent->getCurrentState()).getWidth();
5078 }
5079
5080 if (sourceCrop.height() <= 0) {
5081 crop.top = 0;
5082 crop.bottom = parent->getBufferSize(parent->getCurrentState()).getHeight();
5083 }
5084 reqWidth = crop.width() * frameScale;
5085 reqHeight = crop.height() * frameScale;
5086
5087 for (const auto& handle : excludeHandles) {
5088 sp<Layer> excludeLayer = fromHandle(handle);
5089 if (excludeLayer != nullptr) {
5090 excludeLayers.emplace(excludeLayer);
5091 } else {
5092 ALOGW("Invalid layer handle passed as excludeLayer to captureLayers");
5093 return NAME_NOT_FOUND;
5094 }
5095 }
5096 } // mStateLock
chaviw7206d492017-11-10 16:16:12 -08005097
Chia-I Wu20261cb2018-08-23 12:55:44 -07005098 // really small crop or frameScale
5099 if (reqWidth <= 0) {
5100 reqWidth = 1;
5101 }
5102 if (reqHeight <= 0) {
5103 reqHeight = 1;
5104 }
5105
Robert Carr866455f2019-04-02 16:28:26 -07005106 LayerRenderArea renderArea(this, parent, crop, reqWidth, reqHeight, reqDataspace, childrenOnly);
5107 auto traverseLayers = [parent, childrenOnly,
5108 &excludeLayers](const LayerVector::Visitor& visitor) {
chaviwa76b2712017-09-20 12:02:26 -07005109 parent->traverseChildrenInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
5110 if (!layer->isVisible()) {
5111 return;
Robert Carr578038f2018-03-09 12:25:24 -08005112 } else if (childrenOnly && layer == parent.get()) {
5113 return;
chaviwa76b2712017-09-20 12:02:26 -07005114 }
Robert Carr866455f2019-04-02 16:28:26 -07005115
5116 sp<Layer> p = layer;
5117 while (p != nullptr) {
5118 if (excludeLayers.count(p) != 0) {
5119 return;
5120 }
5121 p = p->getParent();
5122 }
5123
chaviwa76b2712017-09-20 12:02:26 -07005124 visitor(layer);
5125 });
5126 };
Robert Carr108b2c72019-04-02 16:32:58 -07005127
5128 bool outCapturedSecureLayers = false;
5129 return captureScreenCommon(renderArea, traverseLayers, outBuffer, reqPixelFormat, false,
5130 outCapturedSecureLayers);
chaviwa76b2712017-09-20 12:02:26 -07005131}
5132
5133status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5134 TraverseLayersFunction traverseLayers,
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005135 sp<GraphicBuffer>* outBuffer,
Peiyong Lin0e003c92018-09-17 11:09:51 -07005136 const ui::PixelFormat reqPixelFormat,
Robert Carr108b2c72019-04-02 16:32:58 -07005137 bool useIdentityTransform,
5138 bool& outCapturedSecureLayers) {
chaviwa76b2712017-09-20 12:02:26 -07005139 ATRACE_CALL();
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005140
Peiyong Lin0e003c92018-09-17 11:09:51 -07005141 // TODO(b/116112787) Make buffer usage a parameter.
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005142 const uint32_t usage = GRALLOC_USAGE_SW_READ_OFTEN | GRALLOC_USAGE_SW_WRITE_OFTEN |
5143 GRALLOC_USAGE_HW_RENDER | GRALLOC_USAGE_HW_TEXTURE;
Lloyd Pique90c115d2018-09-18 21:39:42 -07005144 *outBuffer =
5145 getFactory().createGraphicBuffer(renderArea.getReqWidth(), renderArea.getReqHeight(),
5146 static_cast<android_pixel_format>(reqPixelFormat), 1,
5147 usage, "screenshot");
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005148
Robert Carr108b2c72019-04-02 16:32:58 -07005149 return captureScreenCommon(renderArea, traverseLayers, *outBuffer, useIdentityTransform,
5150 outCapturedSecureLayers);
Dan Stozaec460082018-12-17 15:35:09 -08005151}
5152
Kevin DuBois7cbcc372019-02-25 14:53:28 -08005153status_t SurfaceFlinger::captureScreenCommon(RenderArea& renderArea,
5154 TraverseLayersFunction traverseLayers,
5155 const sp<GraphicBuffer>& buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005156 bool useIdentityTransform,
5157 bool& outCapturedSecureLayers) {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005158 // This mutex protects syncFd and captureResult for communication of the return values from the
5159 // main thread back to this Binder thread
5160 std::mutex captureMutex;
5161 std::condition_variable captureCondition;
5162 std::unique_lock<std::mutex> captureLock(captureMutex);
5163 int syncFd = -1;
5164 std::optional<status_t> captureResult;
5165
Robert Carr03480e22018-01-04 16:02:06 -08005166 const int uid = IPCThreadState::self()->getCallingUid();
5167 const bool forSystem = uid == AID_GRAPHICS || uid == AID_SYSTEM;
5168
Dominik Laskowski8c001672018-05-30 16:52:06 -07005169 sp<LambdaMessage> message = new LambdaMessage([&] {
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005170 // If there is a refresh pending, bug out early and tell the binder thread to try again
5171 // after the refresh.
5172 if (mRefreshPending) {
5173 ATRACE_NAME("Skipping screenshot for now");
5174 std::unique_lock<std::mutex> captureLock(captureMutex);
5175 captureResult = std::make_optional<status_t>(EAGAIN);
5176 captureCondition.notify_one();
5177 return;
5178 }
5179
5180 status_t result = NO_ERROR;
5181 int fd = -1;
5182 {
5183 Mutex::Autolock _l(mStateLock);
Dominik Laskowski8c001672018-05-30 16:52:06 -07005184 renderArea.render([&] {
Dan Stozaec460082018-12-17 15:35:09 -08005185 result = captureScreenImplLocked(renderArea, traverseLayers, buffer.get(),
Robert Carr108b2c72019-04-02 16:32:58 -07005186 useIdentityTransform, forSystem, &fd,
5187 outCapturedSecureLayers);
Robert Carr578038f2018-03-09 12:25:24 -08005188 });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005189 }
5190
5191 {
5192 std::unique_lock<std::mutex> captureLock(captureMutex);
5193 syncFd = fd;
5194 captureResult = std::make_optional<status_t>(result);
5195 captureCondition.notify_one();
5196 }
5197 });
5198
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005199 status_t result = postMessageAsync(message);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005200 if (result == NO_ERROR) {
Dominik Laskowski8c001672018-05-30 16:52:06 -07005201 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005202 while (*captureResult == EAGAIN) {
5203 captureResult.reset();
5204 result = postMessageAsync(message);
5205 if (result != NO_ERROR) {
5206 return result;
5207 }
Dominik Laskowski8c001672018-05-30 16:52:06 -07005208 captureCondition.wait(captureLock, [&] { return captureResult; });
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005209 }
5210 result = *captureResult;
5211 }
5212
5213 if (result == NO_ERROR) {
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005214 sync_wait(syncFd, -1);
5215 close(syncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005216 }
Chavi Weingarten40482ff2017-11-30 01:51:40 +00005217
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005218 return result;
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005219}
5220
chaviwa76b2712017-09-20 12:02:26 -07005221void SurfaceFlinger::renderScreenImplLocked(const RenderArea& renderArea,
Chia-I Wu1be50b52018-08-29 10:44:48 -07005222 TraverseLayersFunction traverseLayers,
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005223 ANativeWindowBuffer* buffer, bool useIdentityTransform,
5224 int* outSyncFd) {
Mathias Agopian180f10d2013-04-10 22:55:41 -07005225 ATRACE_CALL();
chaviwa76b2712017-09-20 12:02:26 -07005226
chaviwa76b2712017-09-20 12:02:26 -07005227 const auto reqWidth = renderArea.getReqWidth();
5228 const auto reqHeight = renderArea.getReqHeight();
Chia-I Wuf2aa3112018-08-27 14:54:37 -07005229 const auto rotation = renderArea.getRotationFlags();
Alec Mouriadb75f42019-03-28 21:42:24 -07005230 const auto transform = renderArea.getTransform();
5231 const auto sourceCrop = renderArea.getSourceCrop();
Dan Stozac1879002014-05-22 15:59:05 -07005232
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005233 renderengine::DisplaySettings clientCompositionDisplay;
5234 std::vector<renderengine::LayerSettings> clientCompositionLayers;
Romain Guy88d37dd2017-05-26 17:57:05 -07005235
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005236 // assume that bounds are never offset, and that they are the same as the
5237 // buffer bounds.
5238 clientCompositionDisplay.physicalDisplay = Rect(reqWidth, reqHeight);
Alec Mouriadb75f42019-03-28 21:42:24 -07005239 clientCompositionDisplay.clip = sourceCrop;
Lloyd Pique7e06e7f2019-03-15 18:36:44 -07005240 clientCompositionDisplay.globalTransform = transform.asMatrix4();
Alec Mouriadb75f42019-03-28 21:42:24 -07005241
5242 // Now take into account the rotation flag. We append a transform that
5243 // rotates the layer stack about the origin, then translate by buffer
5244 // boundaries to be in the right quadrant.
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005245 mat4 rotMatrix;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005246 int displacementX = 0;
5247 int displacementY = 0;
5248 float rot90InRadians = 2.0f * static_cast<float>(M_PI) / 4.0f;
5249 switch (rotation) {
5250 case ui::Transform::ROT_90:
5251 rotMatrix = mat4::rotate(rot90InRadians, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005252 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005253 break;
5254 case ui::Transform::ROT_180:
5255 rotMatrix = mat4::rotate(rot90InRadians * 2.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005256 displacementY = renderArea.getBounds().getWidth();
5257 displacementX = renderArea.getBounds().getHeight();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005258 break;
5259 case ui::Transform::ROT_270:
5260 rotMatrix = mat4::rotate(rot90InRadians * 3.0f, vec3(0, 0, 1));
Alec Mouriadb75f42019-03-28 21:42:24 -07005261 displacementY = renderArea.getBounds().getWidth();
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005262 break;
5263 default:
5264 break;
5265 }
Alec Mouriadb75f42019-03-28 21:42:24 -07005266
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005267 // We need to transform the clipping window into the right spot.
5268 // First, rotate the clipping rectangle by the rotation hint to get the
5269 // right orientation
5270 const vec4 clipTL = vec4(sourceCrop.left, sourceCrop.top, 0, 1);
5271 const vec4 clipBR = vec4(sourceCrop.right, sourceCrop.bottom, 0, 1);
5272 const vec4 rotClipTL = rotMatrix * clipTL;
5273 const vec4 rotClipBR = rotMatrix * clipBR;
5274 const int newClipLeft = std::min(rotClipTL[0], rotClipBR[0]);
5275 const int newClipTop = std::min(rotClipTL[1], rotClipBR[1]);
5276 const int newClipRight = std::max(rotClipTL[0], rotClipBR[0]);
5277 const int newClipBottom = std::max(rotClipTL[1], rotClipBR[1]);
5278
5279 // Now reposition the clipping rectangle with the displacement vector
5280 // computed above.
5281 const mat4 displacementMat = mat4::translate(vec4(displacementX, displacementY, 0, 1));
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005282 clientCompositionDisplay.clip =
5283 Rect(newClipLeft + displacementX, newClipTop + displacementY,
5284 newClipRight + displacementX, newClipBottom + displacementY);
5285
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005286 mat4 clipTransform = displacementMat * rotMatrix;
Alec Mouriadb75f42019-03-28 21:42:24 -07005287 clientCompositionDisplay.globalTransform =
5288 clipTransform * clientCompositionDisplay.globalTransform;
5289
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005290 clientCompositionDisplay.outputDataspace = renderArea.getReqDataSpace();
5291 clientCompositionDisplay.maxLuminance = DisplayDevice::sDefaultMaxLumiance;
Mathias Agopian180f10d2013-04-10 22:55:41 -07005292
chaviw50da5042018-04-09 13:49:37 -07005293 const float alpha = RenderArea::getCaptureFillValue(renderArea.getCaptureFill());
Mathias Agopian180f10d2013-04-10 22:55:41 -07005294
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005295 renderengine::LayerSettings fillLayer;
5296 fillLayer.source.buffer.buffer = nullptr;
5297 fillLayer.source.solidColor = half3(0.0, 0.0, 0.0);
5298 fillLayer.geometry.boundaries = FloatRect(0.0, 0.0, 1.0, 1.0);
5299 fillLayer.alpha = half(alpha);
5300 clientCompositionLayers.push_back(fillLayer);
5301
5302 Region clearRegion = Region::INVALID_REGION;
chaviwa76b2712017-09-20 12:02:26 -07005303 traverseLayers([&](Layer* layer) {
Lloyd Piquef16688f2019-02-19 17:47:57 -08005304 const bool supportProtectedContent = false;
5305 Region clip(renderArea.getBounds());
5306 compositionengine::LayerFE::ClientCompositionTargetSettings targetSettings{
5307 clip,
5308 useIdentityTransform,
5309 layer->needsFiltering(renderArea.getDisplayDevice()) || renderArea.needsFiltering(),
5310 renderArea.isSecure(),
5311 supportProtectedContent,
5312 clearRegion,
5313 };
5314 auto result = layer->prepareClientComposition(targetSettings);
5315 if (result) {
5316 clientCompositionLayers.push_back(*result);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005317 }
chaviwa76b2712017-09-20 12:02:26 -07005318 });
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005319
5320 clientCompositionDisplay.clearRegion = clearRegion;
Alec Mouri6338c9d2019-02-07 16:57:51 -08005321 // Use an empty fence for the buffer fence, since we just created the buffer so
5322 // there is no need for synchronization with the GPU.
5323 base::unique_fd bufferFence;
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005324 base::unique_fd drawFence;
Peiyong Lin8f28a1d2019-02-07 17:25:12 -08005325 getRenderEngine().useProtectedContext(false);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005326 getRenderEngine().drawLayers(clientCompositionDisplay, clientCompositionLayers, buffer,
Alec Mourife0d72b2019-03-21 14:05:56 -07005327 /*useFramebufferCache=*/false, std::move(bufferFence), &drawFence);
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005328
5329 *outSyncFd = drawFence.release();
Mathias Agopian180f10d2013-04-10 22:55:41 -07005330}
5331
chaviwa76b2712017-09-20 12:02:26 -07005332status_t SurfaceFlinger::captureScreenImplLocked(const RenderArea& renderArea,
5333 TraverseLayersFunction traverseLayers,
5334 ANativeWindowBuffer* buffer,
Robert Carr108b2c72019-04-02 16:32:58 -07005335 bool useIdentityTransform, bool forSystem,
5336 int* outSyncFd, bool& outCapturedSecureLayers) {
Mathias Agopian2a9fc492013-03-01 13:42:57 -08005337 ATRACE_CALL();
5338
chaviwa76b2712017-09-20 12:02:26 -07005339 traverseLayers([&](Layer* layer) {
Robert Carr108b2c72019-04-02 16:32:58 -07005340 outCapturedSecureLayers =
5341 outCapturedSecureLayers || (layer->isVisible() && layer->isSecure());
chaviwa76b2712017-09-20 12:02:26 -07005342 });
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005343
Robert Carr03480e22018-01-04 16:02:06 -08005344 // We allow the system server to take screenshots of secure layers for
5345 // use in situations like the Screen-rotation animation and place
5346 // the impetus on WindowManager to not persist them.
Robert Carr108b2c72019-04-02 16:32:58 -07005347 if (outCapturedSecureLayers && !forSystem) {
Pablo Ceballosb5b35632016-02-23 11:18:51 -08005348 ALOGW("FB is protected: PERMISSION_DENIED");
5349 return PERMISSION_DENIED;
5350 }
Alec Mourie7d1d4a2019-02-05 01:13:46 +00005351 renderScreenImplLocked(renderArea, traverseLayers, buffer, useIdentityTransform, outSyncFd);
Dan Stoza2b6d38e2017-06-01 16:40:30 -07005352 return NO_ERROR;
Mathias Agopian74c40c02010-09-29 13:02:36 -07005353}
5354
chaviw95ef3c42019-02-14 10:55:09 -08005355void SurfaceFlinger::setInputWindowsFinished() {
5356 Mutex::Autolock _l(mStateLock);
5357
5358 mPendingSyncInputWindows = false;
5359 mTransactionCV.broadcast();
5360}
chaviw5f21a5e2019-02-14 10:00:34 -08005361
Mathias Agopian1b0b30d2010-09-24 11:26:58 -07005362// ---------------------------------------------------------------------------
5363
Dan Stoza412903f2017-04-27 13:42:17 -07005364void SurfaceFlinger::State::traverseInZOrder(const LayerVector::Visitor& visitor) const {
5365 layersSortedByZ.traverseInZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005366}
5367
Dan Stoza412903f2017-04-27 13:42:17 -07005368void SurfaceFlinger::State::traverseInReverseZOrder(const LayerVector::Visitor& visitor) const {
5369 layersSortedByZ.traverseInReverseZOrder(stateSet, visitor);
Mathias Agopian921e6ac2012-07-23 23:11:29 -07005370}
5371
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005372void SurfaceFlinger::traverseLayersInDisplay(const sp<const DisplayDevice>& display,
chaviwa76b2712017-09-20 12:02:26 -07005373 const LayerVector::Visitor& visitor) {
5374 // We loop through the first level of layers without traversing,
chaviw0e3479f2018-09-10 16:49:30 -07005375 // as we need to determine which layers belong to the requested display.
chaviwa76b2712017-09-20 12:02:26 -07005376 for (const auto& layer : mDrawingState.layersSortedByZ) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005377 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
chaviwa76b2712017-09-20 12:02:26 -07005378 continue;
5379 }
Chia-I Wuec2d9852017-11-21 09:21:01 -08005380 // relative layers are traversed in Layer::traverseInZOrder
chaviwa76b2712017-09-20 12:02:26 -07005381 layer->traverseInZOrder(LayerVector::StateSet::Drawing, [&](Layer* layer) {
Dominik Laskowskieecd6592018-05-29 10:25:41 -07005382 if (!layer->belongsToDisplay(display->getLayerStack(), false)) {
Adrian Roos8acf5a02018-01-17 21:28:19 +01005383 return;
5384 }
chaviwa76b2712017-09-20 12:02:26 -07005385 if (!layer->isVisible()) {
5386 return;
5387 }
5388 visitor(layer);
5389 });
5390 }
5391}
5392
Dominik Laskowski22488f62019-03-28 09:53:04 -07005393void SurfaceFlinger::setAllowedDisplayConfigsInternal(const sp<DisplayDevice>& display,
5394 const std::vector<int32_t>& allowedConfigs) {
5395 if (!display->isPrimary()) {
Ady Abraham838de062019-02-04 10:24:03 -08005396 return;
5397 }
5398
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005399 const auto allowedDisplayConfigs = DisplayConfigs(allowedConfigs.begin(),
5400 allowedConfigs.end());
5401 if (allowedDisplayConfigs == mAllowedDisplayConfigs) {
5402 return;
5403 }
5404
Ady Abraham838de062019-02-04 10:24:03 -08005405 ALOGV("Updating allowed configs");
Adrian Salidoab6ef6c2019-08-28 10:02:49 -07005406 mAllowedDisplayConfigs = std::move(allowedDisplayConfigs);
5407
5408 // TODO(b/140204874): This hack triggers a notification that something has changed, so
5409 // that listeners that care about a change in allowed configs can get the notification.
5410 // Giving current ActiveConfig so that most other listeners would just drop the event
5411 mScheduler->onConfigChanged(mAppConnectionHandle, display->getId()->value,
5412 display->getActiveConfig());
Ady Abraham838de062019-02-04 10:24:03 -08005413
Steven Thomas2bbaabe2019-08-28 16:08:35 -07005414 if (mRefreshRateConfigs->refreshRateSwitchingSupported()) {
5415 const auto& type = mScheduler->getPreferredRefreshRateType();
5416 const auto& config = mRefreshRateConfigs->getRefreshRateFromType(type);
5417 if (isDisplayConfigAllowed(config.configId)) {
5418 ALOGV("switching to Scheduler preferred config %d", config.configId);
5419 setDesiredActiveConfig({type, config.configId, Scheduler::ConfigEvent::Changed});
5420 } else {
5421 // Set the highest allowed config by iterating backwards on available refresh rates
5422 const auto& refreshRates = mRefreshRateConfigs->getRefreshRateMap();
5423 for (auto iter = refreshRates.crbegin(); iter != refreshRates.crend(); ++iter) {
5424 if (isDisplayConfigAllowed(iter->second.configId)) {
5425 ALOGV("switching to allowed config %d", iter->second.configId);
5426 setDesiredActiveConfig(
5427 {iter->first, iter->second.configId, Scheduler::ConfigEvent::Changed});
5428 break;
5429 }
5430 }
5431 }
5432 } else if (!allowedConfigs.empty()) {
5433 ALOGV("switching to config %d", allowedConfigs[0]);
5434 setDesiredActiveConfig(
5435 {RefreshRateType::DEFAULT, allowedConfigs[0], Scheduler::ConfigEvent::Changed});
5436 }
Ady Abraham838de062019-02-04 10:24:03 -08005437}
5438
Dominik Laskowski22488f62019-03-28 09:53:04 -07005439status_t SurfaceFlinger::setAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abraham838de062019-02-04 10:24:03 -08005440 const std::vector<int32_t>& allowedConfigs) {
5441 ATRACE_CALL();
5442
Dominik Laskowski22488f62019-03-28 09:53:04 -07005443 if (!displayToken || allowedConfigs.empty()) {
Ady Abraham838de062019-02-04 10:24:03 -08005444 return BAD_VALUE;
5445 }
5446
Ady Abraham34392f72019-04-10 11:29:27 -07005447 if (mDebugDisplayConfigSetByBackdoor) {
5448 // ignore this request as config is overridden by backdoor
5449 return NO_ERROR;
5450 }
5451
Ady Abrahama3129fb2019-10-18 14:17:23 -07005452 postMessageSync(new LambdaMessage([&]() {
Dominik Laskowski22488f62019-03-28 09:53:04 -07005453 const auto display = getDisplayDeviceLocked(displayToken);
5454 if (!display) {
5455 ALOGE("Attempt to set allowed display configs for invalid display token %p",
5456 displayToken.get());
5457 } else if (display->isVirtual()) {
5458 ALOGW("Attempt to set allowed display configs for virtual display");
5459 } else {
Ady Abrahama3129fb2019-10-18 14:17:23 -07005460 Mutex::Autolock lock(mStateLock);
Dominik Laskowski22488f62019-03-28 09:53:04 -07005461 setAllowedDisplayConfigsInternal(display, allowedConfigs);
5462 }
Ady Abraham838de062019-02-04 10:24:03 -08005463 }));
Dominik Laskowski22488f62019-03-28 09:53:04 -07005464
Ady Abraham838de062019-02-04 10:24:03 -08005465 return NO_ERROR;
5466}
5467
Dominik Laskowski22488f62019-03-28 09:53:04 -07005468status_t SurfaceFlinger::getAllowedDisplayConfigs(const sp<IBinder>& displayToken,
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005469 std::vector<int32_t>* outAllowedConfigs) {
5470 ATRACE_CALL();
5471
Dominik Laskowski22488f62019-03-28 09:53:04 -07005472 if (!displayToken || !outAllowedConfigs) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005473 return BAD_VALUE;
5474 }
5475
Dominik Laskowski22488f62019-03-28 09:53:04 -07005476 Mutex::Autolock lock(mStateLock);
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005477
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005478 const auto display = getDisplayDeviceLocked(displayToken);
5479 if (!display) {
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005480 return NAME_NOT_FOUND;
5481 }
5482
Dominik Laskowski4f1dd8c2019-04-17 15:54:30 -07005483 if (display->isPrimary()) {
5484 outAllowedConfigs->assign(mAllowedDisplayConfigs.begin(), mAllowedDisplayConfigs.end());
5485 }
5486
Ady Abrahamd9b3ea62019-02-26 14:08:03 -08005487 return NO_ERROR;
5488}
5489
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005490void SurfaceFlinger::SetInputWindowsListener::onSetInputWindowsFinished() {
chaviw291d88a2019-02-14 10:33:58 -08005491 mFlinger->setInputWindowsFinished();
5492}
5493
Robert Carrc0df3122019-04-11 13:18:21 -07005494sp<Layer> SurfaceFlinger::fromHandle(const sp<IBinder>& handle) {
5495 BBinder *b = handle->localBinder();
5496 if (b == nullptr) {
5497 return nullptr;
5498 }
5499 auto it = mLayersByLocalBinderToken.find(b);
5500 if (it != mLayersByLocalBinderToken.end()) {
5501 return it->second.promote();
5502 }
5503 return nullptr;
5504}
5505
Dominik Laskowski75848362019-11-11 17:57:20 -08005506void SurfaceFlinger::onLayerFirstRef(Layer* layer) {
Dominik Laskowskif7a09ed2019-10-07 13:54:18 -07005507 mNumLayers++;
5508 mScheduler->registerLayer(layer);
5509}
5510
5511void SurfaceFlinger::onLayerDestroyed(Layer* layer) {
5512 mNumLayers--;
5513 mOffscreenLayers.erase(layer);
5514}
5515
Alec Mouri4545a8a2019-08-08 20:05:32 -07005516void SurfaceFlinger::bufferErased(const client_cache_t& clientCacheId) {
5517 getRenderEngine().unbindExternalTextureBuffer(clientCacheId.id);
5518}
5519
Dominik Laskowski9dab3432019-03-27 13:21:10 -07005520} // namespace android
Lloyd Pique074e8122018-07-26 12:57:23 -07005521
Mathias Agopian3f844832013-08-07 21:24:32 -07005522#if defined(__gl_h_)
5523#error "don't include gl/gl.h in this file"
5524#endif
5525
5526#if defined(__gl2_h_)
5527#error "don't include gl2/gl2.h in this file"
Chia-I Wu767fcf72017-11-30 22:07:38 -08005528#endif