blob: b77153835a2892018c3ffe8968ac93de3daa9141 [file] [log] [blame]
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001#include "hardware_composer.h"
2
Steven Thomasdfde8fa2018-04-19 16:00:58 -07003#include <binder/IServiceManager.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08004#include <cutils/properties.h>
5#include <cutils/sched_policy.h>
6#include <fcntl.h>
Corey Tabaka2251d822017-04-20 16:04:07 -07007#include <log/log.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08008#include <poll.h>
Corey Tabakab3732f02017-09-16 00:58:54 -07009#include <stdint.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080010#include <sync/sync.h>
11#include <sys/eventfd.h>
12#include <sys/prctl.h>
13#include <sys/resource.h>
14#include <sys/system_properties.h>
15#include <sys/timerfd.h>
Corey Tabakab3732f02017-09-16 00:58:54 -070016#include <sys/types.h>
Corey Tabaka2251d822017-04-20 16:04:07 -070017#include <time.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080018#include <unistd.h>
19#include <utils/Trace.h>
20
21#include <algorithm>
Corey Tabaka2251d822017-04-20 16:04:07 -070022#include <chrono>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080023#include <functional>
24#include <map>
Corey Tabaka0b485c92017-05-19 12:02:58 -070025#include <sstream>
26#include <string>
John Bates954796e2017-05-11 11:00:31 -070027#include <tuple>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080028
Corey Tabaka2251d822017-04-20 16:04:07 -070029#include <dvr/dvr_display_types.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080030#include <dvr/performance_client_api.h>
31#include <private/dvr/clock_ns.h>
Corey Tabaka2251d822017-04-20 16:04:07 -070032#include <private/dvr/ion_buffer.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080033
Steven Thomasb02664d2017-07-26 18:48:28 -070034using android::hardware::Return;
35using android::hardware::Void;
Corey Tabakab3732f02017-09-16 00:58:54 -070036using android::pdx::ErrorStatus;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080037using android::pdx::LocalHandle;
Corey Tabakab3732f02017-09-16 00:58:54 -070038using android::pdx::Status;
Corey Tabaka2251d822017-04-20 16:04:07 -070039using android::pdx::rpc::EmptyVariant;
40using android::pdx::rpc::IfAnyOf;
41
42using namespace std::chrono_literals;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080043
44namespace android {
45namespace dvr {
46
47namespace {
48
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080049const char kDvrPerformanceProperty[] = "sys.dvr.performance";
Corey Tabaka451256f2017-08-22 11:59:15 -070050const char kDvrStandaloneProperty[] = "ro.boot.vr";
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080051
Luke Song4b788322017-03-24 14:17:31 -070052const char kRightEyeOffsetProperty[] = "dvr.right_eye_offset_ns";
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080053
Steven Thomasdfde8fa2018-04-19 16:00:58 -070054// Surface flinger uses "VSYNC-sf" and "VSYNC-app" for its version of these
55// events. Name ours similarly.
56const char kVsyncTraceEventName[] = "VSYNC-vrflinger";
57
Steven Thomasaf336272018-01-04 17:36:47 -080058// How long to wait after boot finishes before we turn the display off.
59constexpr int kBootFinishedDisplayOffTimeoutSec = 10;
60
Steven Thomasbfe46a02018-02-16 14:27:35 -080061constexpr int kDefaultDisplayWidth = 1920;
62constexpr int kDefaultDisplayHeight = 1080;
63constexpr int64_t kDefaultVsyncPeriodNs = 16666667;
64// Hardware composer reports dpi as dots per thousand inches (dpi * 1000).
65constexpr int kDefaultDpi = 400000;
66
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080067// Get time offset from a vsync to when the pose for that vsync should be
68// predicted out to. For example, if scanout gets halfway through the frame
69// at the halfway point between vsyncs, then this could be half the period.
70// With global shutter displays, this should be changed to the offset to when
71// illumination begins. Low persistence adds a frame of latency, so we predict
72// to the center of the next frame.
73inline int64_t GetPosePredictionTimeOffset(int64_t vsync_period_ns) {
74 return (vsync_period_ns * 150) / 100;
75}
76
Corey Tabaka2251d822017-04-20 16:04:07 -070077// Attempts to set the scheduler class and partiton for the current thread.
78// Returns true on success or false on failure.
79bool SetThreadPolicy(const std::string& scheduler_class,
80 const std::string& partition) {
81 int error = dvrSetSchedulerClass(0, scheduler_class.c_str());
82 if (error < 0) {
83 ALOGE(
84 "SetThreadPolicy: Failed to set scheduler class \"%s\" for "
85 "thread_id=%d: %s",
86 scheduler_class.c_str(), gettid(), strerror(-error));
87 return false;
88 }
89 error = dvrSetCpuPartition(0, partition.c_str());
90 if (error < 0) {
91 ALOGE(
92 "SetThreadPolicy: Failed to set cpu partiton \"%s\" for thread_id=%d: "
93 "%s",
94 partition.c_str(), gettid(), strerror(-error));
95 return false;
96 }
97 return true;
98}
99
Corey Tabakab3732f02017-09-16 00:58:54 -0700100// Utility to generate scoped tracers with arguments.
101// TODO(eieio): Move/merge this into utils/Trace.h?
102class TraceArgs {
103 public:
104 template <typename... Args>
Chih-Hung Hsieh79e7f1b2018-12-20 15:53:43 -0800105 explicit TraceArgs(const char* format, Args&&... args) {
Corey Tabakab3732f02017-09-16 00:58:54 -0700106 std::array<char, 1024> buffer;
107 snprintf(buffer.data(), buffer.size(), format, std::forward<Args>(args)...);
108 atrace_begin(ATRACE_TAG, buffer.data());
109 }
110
111 ~TraceArgs() { atrace_end(ATRACE_TAG); }
112
113 private:
114 TraceArgs(const TraceArgs&) = delete;
115 void operator=(const TraceArgs&) = delete;
116};
117
118// Macro to define a scoped tracer with arguments. Uses PASTE(x, y) macro
119// defined in utils/Trace.h.
120#define TRACE_FORMAT(format, ...) \
121 TraceArgs PASTE(__tracer, __LINE__) { format, ##__VA_ARGS__ }
122
Steven Thomasbfe46a02018-02-16 14:27:35 -0800123// Returns "primary" or "external". Useful for writing more readable logs.
124const char* GetDisplayName(bool is_primary) {
125 return is_primary ? "primary" : "external";
126}
127
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800128} // anonymous namespace
129
Corey Tabaka2251d822017-04-20 16:04:07 -0700130HardwareComposer::HardwareComposer()
Steven Thomasb02664d2017-07-26 18:48:28 -0700131 : initialized_(false), request_display_callback_(nullptr) {}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800132
133HardwareComposer::~HardwareComposer(void) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700134 UpdatePostThreadState(PostThreadState::Quit, true);
135 if (post_thread_.joinable())
Steven Thomas050b2c82017-03-06 11:45:16 -0800136 post_thread_.join();
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700137 composer_callback_->SetVsyncService(nullptr);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800138}
139
mamik913cc132019-09-13 14:58:43 -0700140void HardwareComposer::UpdateEdidData(Hwc2::Composer* composer,
141 hwc2_display_t hw_id) {
142 const auto error = composer->getDisplayIdentificationData(
143 hw_id, &display_port_, &display_identification_data_);
144 if (error != android::hardware::graphics::composer::V2_1::Error::NONE) {
145 if (error !=
146 android::hardware::graphics::composer::V2_1::Error::UNSUPPORTED) {
147 ALOGI("hardware_composer: identification data error\n");
148 } else {
149 ALOGI("hardware_composer: identification data unsupported\n");
150 }
151 }
152}
153
Steven Thomasb02664d2017-07-26 18:48:28 -0700154bool HardwareComposer::Initialize(
Steven Thomas6e8f7062017-11-22 14:15:29 -0800155 Hwc2::Composer* composer, hwc2_display_t primary_display_id,
156 RequestDisplayCallback request_display_callback) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800157 if (initialized_) {
158 ALOGE("HardwareComposer::Initialize: already initialized.");
159 return false;
160 }
161
Corey Tabaka451256f2017-08-22 11:59:15 -0700162 is_standalone_device_ = property_get_bool(kDvrStandaloneProperty, false);
163
Steven Thomasb02664d2017-07-26 18:48:28 -0700164 request_display_callback_ = request_display_callback;
165
Steven Thomasbfe46a02018-02-16 14:27:35 -0800166 primary_display_ = GetDisplayParams(composer, primary_display_id, true);
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700167
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700168 vsync_service_ = new VsyncService;
169 sp<IServiceManager> sm(defaultServiceManager());
170 auto result = sm->addService(String16(VsyncService::GetServiceName()),
171 vsync_service_, false);
172 LOG_ALWAYS_FATAL_IF(result != android::OK,
173 "addService(%s) failed", VsyncService::GetServiceName());
174
Corey Tabaka2251d822017-04-20 16:04:07 -0700175 post_thread_event_fd_.Reset(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
Steven Thomas050b2c82017-03-06 11:45:16 -0800176 LOG_ALWAYS_FATAL_IF(
Corey Tabaka2251d822017-04-20 16:04:07 -0700177 !post_thread_event_fd_,
Steven Thomas050b2c82017-03-06 11:45:16 -0800178 "HardwareComposer: Failed to create interrupt event fd : %s",
179 strerror(errno));
180
mamik913cc132019-09-13 14:58:43 -0700181 UpdateEdidData(composer, primary_display_id);
182
Steven Thomas050b2c82017-03-06 11:45:16 -0800183 post_thread_ = std::thread(&HardwareComposer::PostThread, this);
184
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800185 initialized_ = true;
186
187 return initialized_;
188}
189
Steven Thomas050b2c82017-03-06 11:45:16 -0800190void HardwareComposer::Enable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700191 UpdatePostThreadState(PostThreadState::Suspended, false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800192}
193
194void HardwareComposer::Disable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700195 UpdatePostThreadState(PostThreadState::Suspended, true);
Steven Thomas7f8761e2018-01-18 18:49:59 -0800196
197 std::unique_lock<std::mutex> lock(post_thread_mutex_);
198 post_thread_ready_.wait(lock, [this] {
199 return !post_thread_resumed_;
200 });
Steven Thomas050b2c82017-03-06 11:45:16 -0800201}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800202
Steven Thomasaf336272018-01-04 17:36:47 -0800203void HardwareComposer::OnBootFinished() {
204 std::lock_guard<std::mutex> lock(post_thread_mutex_);
205 if (boot_finished_)
206 return;
207 boot_finished_ = true;
208 post_thread_wait_.notify_one();
209 if (is_standalone_device_)
210 request_display_callback_(true);
211}
212
Corey Tabaka2251d822017-04-20 16:04:07 -0700213// Update the post thread quiescent state based on idle and suspended inputs.
214void HardwareComposer::UpdatePostThreadState(PostThreadStateType state,
215 bool suspend) {
216 std::unique_lock<std::mutex> lock(post_thread_mutex_);
217
218 // Update the votes in the state variable before evaluating the effective
219 // quiescent state. Any bits set in post_thread_state_ indicate that the post
220 // thread should be suspended.
221 if (suspend) {
222 post_thread_state_ |= state;
223 } else {
224 post_thread_state_ &= ~state;
225 }
226
227 const bool quit = post_thread_state_ & PostThreadState::Quit;
228 const bool effective_suspend = post_thread_state_ != PostThreadState::Active;
229 if (quit) {
230 post_thread_quiescent_ = true;
231 eventfd_write(post_thread_event_fd_.Get(), 1);
232 post_thread_wait_.notify_one();
233 } else if (effective_suspend && !post_thread_quiescent_) {
234 post_thread_quiescent_ = true;
235 eventfd_write(post_thread_event_fd_.Get(), 1);
236 } else if (!effective_suspend && post_thread_quiescent_) {
237 post_thread_quiescent_ = false;
238 eventfd_t value;
239 eventfd_read(post_thread_event_fd_.Get(), &value);
240 post_thread_wait_.notify_one();
241 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800242}
Steven Thomas282a5ed2017-02-07 18:07:01 -0800243
Steven Thomasbfe46a02018-02-16 14:27:35 -0800244void HardwareComposer::CreateComposer() {
245 if (composer_)
246 return;
247 composer_.reset(new Hwc2::impl::Composer("default"));
248 composer_callback_ = new ComposerCallback;
249 composer_->registerCallback(composer_callback_);
250 LOG_ALWAYS_FATAL_IF(!composer_callback_->GotFirstHotplug(),
251 "Registered composer callback but didn't get hotplug for primary"
252 " display");
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700253 composer_callback_->SetVsyncService(vsync_service_);
Steven Thomasbfe46a02018-02-16 14:27:35 -0800254}
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700255
Steven Thomasbfe46a02018-02-16 14:27:35 -0800256void HardwareComposer::OnPostThreadResumed() {
257 ALOGI("OnPostThreadResumed");
258 EnableDisplay(*target_display_, true);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800259
Steven Thomas050b2c82017-03-06 11:45:16 -0800260 // Trigger target-specific performance mode change.
261 property_set(kDvrPerformanceProperty, "performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800262}
263
Steven Thomas050b2c82017-03-06 11:45:16 -0800264void HardwareComposer::OnPostThreadPaused() {
Steven Thomasbfe46a02018-02-16 14:27:35 -0800265 ALOGI("OnPostThreadPaused");
Corey Tabaka2251d822017-04-20 16:04:07 -0700266 retire_fence_fds_.clear();
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700267 layers_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800268
Steven Thomasbfe46a02018-02-16 14:27:35 -0800269 // Phones create a new composer client on resume and destroy it on pause.
270 // Standalones only create the composer client once and then use SetPowerMode
271 // to control the screen on pause/resume.
Corey Tabaka451256f2017-08-22 11:59:15 -0700272 if (!is_standalone_device_) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700273 if (composer_callback_ != nullptr) {
274 composer_callback_->SetVsyncService(nullptr);
275 composer_callback_ = nullptr;
276 }
Corey Tabaka451256f2017-08-22 11:59:15 -0700277 composer_.reset(nullptr);
Corey Tabaka451256f2017-08-22 11:59:15 -0700278 } else {
Steven Thomasbfe46a02018-02-16 14:27:35 -0800279 EnableDisplay(*target_display_, false);
Corey Tabaka451256f2017-08-22 11:59:15 -0700280 }
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700281
Steven Thomas050b2c82017-03-06 11:45:16 -0800282 // Trigger target-specific performance mode change.
283 property_set(kDvrPerformanceProperty, "idle");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800284}
285
Steven Thomasaf336272018-01-04 17:36:47 -0800286bool HardwareComposer::PostThreadCondWait(std::unique_lock<std::mutex>& lock,
287 int timeout_sec,
288 const std::function<bool()>& pred) {
289 auto pred_with_quit = [&] {
290 return pred() || (post_thread_state_ & PostThreadState::Quit);
291 };
292 if (timeout_sec >= 0) {
293 post_thread_wait_.wait_for(lock, std::chrono::seconds(timeout_sec),
294 pred_with_quit);
295 } else {
296 post_thread_wait_.wait(lock, pred_with_quit);
297 }
298 if (post_thread_state_ & PostThreadState::Quit) {
299 ALOGI("HardwareComposer::PostThread: Quitting.");
300 return true;
301 }
302 return false;
303}
304
Corey Tabaka2251d822017-04-20 16:04:07 -0700305HWC::Error HardwareComposer::Validate(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800306 uint32_t num_types;
307 uint32_t num_requests;
Corey Tabaka2251d822017-04-20 16:04:07 -0700308 HWC::Error error =
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700309 composer_->validateDisplay(display, &num_types, &num_requests);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800310
311 if (error == HWC2_ERROR_HAS_CHANGES) {
Steven Thomasbfe46a02018-02-16 14:27:35 -0800312 ALOGE("Hardware composer has requested composition changes, "
313 "which we don't support.");
314 // Accept the changes anyway and see if we can get something on the screen.
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700315 error = composer_->acceptDisplayChanges(display);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800316 }
317
318 return error;
319}
320
Steven Thomasbfe46a02018-02-16 14:27:35 -0800321bool HardwareComposer::EnableVsync(const DisplayParams& display, bool enabled) {
322 HWC::Error error = composer_->setVsyncEnabled(display.id,
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800323 (Hwc2::IComposerClient::Vsync)(enabled ? HWC2_VSYNC_ENABLE
324 : HWC2_VSYNC_DISABLE));
Steven Thomasbfe46a02018-02-16 14:27:35 -0800325 if (error != HWC::Error::None) {
326 ALOGE("Error attempting to %s vsync on %s display: %s",
327 enabled ? "enable" : "disable", GetDisplayName(display.is_primary),
328 error.to_string().c_str());
329 }
330 return error == HWC::Error::None;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800331}
332
Steven Thomasbfe46a02018-02-16 14:27:35 -0800333bool HardwareComposer::SetPowerMode(const DisplayParams& display, bool active) {
334 ALOGI("Turning %s display %s", GetDisplayName(display.is_primary),
335 active ? "on" : "off");
Corey Tabaka451256f2017-08-22 11:59:15 -0700336 HWC::PowerMode power_mode = active ? HWC::PowerMode::On : HWC::PowerMode::Off;
Steven Thomasbfe46a02018-02-16 14:27:35 -0800337 HWC::Error error = composer_->setPowerMode(display.id,
Steven Thomas6e8f7062017-11-22 14:15:29 -0800338 power_mode.cast<Hwc2::IComposerClient::PowerMode>());
Steven Thomasbfe46a02018-02-16 14:27:35 -0800339 if (error != HWC::Error::None) {
340 ALOGE("Error attempting to turn %s display %s: %s",
341 GetDisplayName(display.is_primary), active ? "on" : "off",
342 error.to_string().c_str());
343 }
344 return error == HWC::Error::None;
345}
346
347bool HardwareComposer::EnableDisplay(const DisplayParams& display,
348 bool enabled) {
349 bool power_result;
350 bool vsync_result;
351 // When turning a display on, we set the power state then set vsync. When
352 // turning a display off we do it in the opposite order.
353 if (enabled) {
354 power_result = SetPowerMode(display, enabled);
355 vsync_result = EnableVsync(display, enabled);
356 } else {
357 vsync_result = EnableVsync(display, enabled);
358 power_result = SetPowerMode(display, enabled);
359 }
360 return power_result && vsync_result;
Corey Tabaka451256f2017-08-22 11:59:15 -0700361}
362
Corey Tabaka2251d822017-04-20 16:04:07 -0700363HWC::Error HardwareComposer::Present(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800364 int32_t present_fence;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700365 HWC::Error error = composer_->presentDisplay(display, &present_fence);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800366
367 // According to the documentation, this fence is signaled at the time of
368 // vsync/DMA for physical displays.
Corey Tabaka2251d822017-04-20 16:04:07 -0700369 if (error == HWC::Error::None) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800370 retire_fence_fds_.emplace_back(present_fence);
371 } else {
372 ATRACE_INT("HardwareComposer: PresentResult", error);
373 }
374
375 return error;
376}
377
Steven Thomasbfe46a02018-02-16 14:27:35 -0800378DisplayParams HardwareComposer::GetDisplayParams(
379 Hwc2::Composer* composer, hwc2_display_t display, bool is_primary) {
380 DisplayParams params;
381 params.id = display;
382 params.is_primary = is_primary;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800383
Steven Thomasbfe46a02018-02-16 14:27:35 -0800384 Hwc2::Config config;
385 HWC::Error error = composer->getActiveConfig(display, &config);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800386
Steven Thomasbfe46a02018-02-16 14:27:35 -0800387 if (error == HWC::Error::None) {
388 auto get_attr = [&](hwc2_attribute_t attr, const char* attr_name)
389 -> std::optional<int32_t> {
390 int32_t val;
391 HWC::Error error = composer->getDisplayAttribute(
392 display, config, (Hwc2::IComposerClient::Attribute)attr, &val);
393 if (error != HWC::Error::None) {
394 ALOGE("Failed to get %s display attr %s: %s",
395 GetDisplayName(is_primary), attr_name,
396 error.to_string().c_str());
397 return std::nullopt;
398 }
399 return val;
400 };
401
402 auto width = get_attr(HWC2_ATTRIBUTE_WIDTH, "width");
403 auto height = get_attr(HWC2_ATTRIBUTE_HEIGHT, "height");
404
405 if (width && height) {
406 params.width = *width;
407 params.height = *height;
408 } else {
409 ALOGI("Failed to get width and/or height for %s display. Using default"
410 " size %dx%d.", GetDisplayName(is_primary), kDefaultDisplayWidth,
411 kDefaultDisplayHeight);
412 params.width = kDefaultDisplayWidth;
413 params.height = kDefaultDisplayHeight;
414 }
415
416 auto vsync_period = get_attr(HWC2_ATTRIBUTE_VSYNC_PERIOD, "vsync period");
417 if (vsync_period) {
418 params.vsync_period_ns = *vsync_period;
419 } else {
420 ALOGI("Failed to get vsync period for %s display. Using default vsync"
421 " period %.2fms", GetDisplayName(is_primary),
422 static_cast<float>(kDefaultVsyncPeriodNs) / 1000000);
423 params.vsync_period_ns = kDefaultVsyncPeriodNs;
424 }
425
426 auto dpi_x = get_attr(HWC2_ATTRIBUTE_DPI_X, "DPI X");
427 auto dpi_y = get_attr(HWC2_ATTRIBUTE_DPI_Y, "DPI Y");
428 if (dpi_x && dpi_y) {
429 params.dpi.x = *dpi_x;
430 params.dpi.y = *dpi_y;
431 } else {
432 ALOGI("Failed to get dpi_x and/or dpi_y for %s display. Using default"
433 " dpi %d.", GetDisplayName(is_primary), kDefaultDpi);
434 params.dpi.x = kDefaultDpi;
435 params.dpi.y = kDefaultDpi;
436 }
437 } else {
438 ALOGE("HardwareComposer: Failed to get current %s display config: %d."
439 " Using default display values.",
440 GetDisplayName(is_primary), error.value);
441 params.width = kDefaultDisplayWidth;
442 params.height = kDefaultDisplayHeight;
443 params.dpi.x = kDefaultDpi;
444 params.dpi.y = kDefaultDpi;
445 params.vsync_period_ns = kDefaultVsyncPeriodNs;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800446 }
447
Steven Thomasbfe46a02018-02-16 14:27:35 -0800448 ALOGI(
449 "HardwareComposer: %s display attributes: width=%d height=%d "
450 "vsync_period_ns=%d DPI=%dx%d",
451 GetDisplayName(is_primary),
452 params.width,
453 params.height,
454 params.vsync_period_ns,
455 params.dpi.x,
456 params.dpi.y);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800457
Steven Thomasbfe46a02018-02-16 14:27:35 -0800458 return params;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800459}
460
Corey Tabaka0b485c92017-05-19 12:02:58 -0700461std::string HardwareComposer::Dump() {
462 std::unique_lock<std::mutex> lock(post_thread_mutex_);
463 std::ostringstream stream;
464
Steven Thomasbfe46a02018-02-16 14:27:35 -0800465 auto print_display_metrics = [&](const DisplayParams& params) {
466 stream << GetDisplayName(params.is_primary)
467 << " display metrics: " << params.width << "x"
468 << params.height << " " << (params.dpi.x / 1000.0)
469 << "x" << (params.dpi.y / 1000.0) << " dpi @ "
470 << (1000000000.0 / params.vsync_period_ns) << " Hz"
471 << std::endl;
472 };
473
474 print_display_metrics(primary_display_);
475 if (external_display_)
476 print_display_metrics(*external_display_);
Corey Tabaka0b485c92017-05-19 12:02:58 -0700477
478 stream << "Post thread resumed: " << post_thread_resumed_ << std::endl;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700479 stream << "Active layers: " << layers_.size() << std::endl;
Corey Tabaka0b485c92017-05-19 12:02:58 -0700480 stream << std::endl;
481
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700482 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700483 stream << "Layer " << i << ":";
484 stream << " type=" << layers_[i].GetCompositionType().to_string();
485 stream << " surface_id=" << layers_[i].GetSurfaceId();
486 stream << " buffer_id=" << layers_[i].GetBufferId();
487 stream << std::endl;
488 }
489 stream << std::endl;
490
491 if (post_thread_resumed_) {
492 stream << "Hardware Composer Debug Info:" << std::endl;
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700493 stream << composer_->dumpDebugInfo();
Corey Tabaka0b485c92017-05-19 12:02:58 -0700494 }
495
496 return stream.str();
497}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800498
Steven Thomasbfe46a02018-02-16 14:27:35 -0800499void HardwareComposer::PostLayers(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800500 ATRACE_NAME("HardwareComposer::PostLayers");
501
502 // Setup the hardware composer layers with current buffers.
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700503 for (auto& layer : layers_) {
504 layer.Prepare();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800505 }
506
507 // Now that we have taken in a frame from the application, we have a chance
508 // to drop the frame before passing the frame along to HWC.
509 // If the display driver has become backed up, we detect it here and then
510 // react by skipping this frame to catch up latency.
511 while (!retire_fence_fds_.empty() &&
512 (!retire_fence_fds_.front() ||
513 sync_wait(retire_fence_fds_.front().Get(), 0) == 0)) {
514 // There are only 2 fences in here, no performance problem to shift the
515 // array of ints.
516 retire_fence_fds_.erase(retire_fence_fds_.begin());
517 }
518
George Burgess IV353a6f62017-06-26 17:13:09 -0700519 const bool is_fence_pending = static_cast<int32_t>(retire_fence_fds_.size()) >
John Bates954796e2017-05-11 11:00:31 -0700520 post_thread_config_.allowed_pending_fence_count;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800521
Corey Tabakab3732f02017-09-16 00:58:54 -0700522 if (is_fence_pending) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800523 ATRACE_INT("frame_skip_count", ++frame_skip_count_);
524
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800525 ALOGW_IF(is_fence_pending,
526 "Warning: dropping a frame to catch up with HWC (pending = %zd)",
527 retire_fence_fds_.size());
528
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700529 for (auto& layer : layers_) {
530 layer.Drop();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800531 }
532 return;
533 } else {
534 // Make the transition more obvious in systrace when the frame skip happens
535 // above.
536 ATRACE_INT("frame_skip_count", 0);
537 }
538
Corey Tabaka89bbefc2017-06-06 16:14:21 -0700539#if TRACE > 1
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700540 for (size_t i = 0; i < layers_.size(); i++) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700541 ALOGI("HardwareComposer::PostLayers: layer=%zu buffer_id=%d composition=%s",
542 i, layers_[i].GetBufferId(),
Corey Tabaka2251d822017-04-20 16:04:07 -0700543 layers_[i].GetCompositionType().to_string().c_str());
Corey Tabaka0b485c92017-05-19 12:02:58 -0700544 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800545#endif
546
Steven Thomasbfe46a02018-02-16 14:27:35 -0800547 HWC::Error error = Validate(display);
John Bates46684842017-12-13 15:26:50 -0800548 if (error != HWC::Error::None) {
Steven Thomasbfe46a02018-02-16 14:27:35 -0800549 ALOGE("HardwareComposer::PostLayers: Validate failed: %s display=%" PRIu64,
550 error.to_string().c_str(), display);
John Bates46684842017-12-13 15:26:50 -0800551 return;
552 }
553
Steven Thomasbfe46a02018-02-16 14:27:35 -0800554 error = Present(display);
Corey Tabaka2251d822017-04-20 16:04:07 -0700555 if (error != HWC::Error::None) {
556 ALOGE("HardwareComposer::PostLayers: Present failed: %s",
557 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800558 return;
559 }
560
561 std::vector<Hwc2::Layer> out_layers;
562 std::vector<int> out_fences;
Steven Thomasbfe46a02018-02-16 14:27:35 -0800563 error = composer_->getReleaseFences(display,
Steven Thomas6e8f7062017-11-22 14:15:29 -0800564 &out_layers, &out_fences);
Corey Tabaka2251d822017-04-20 16:04:07 -0700565 ALOGE_IF(error != HWC::Error::None,
566 "HardwareComposer::PostLayers: Failed to get release fences: %s",
567 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800568
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700569 // Perform post-frame bookkeeping.
Corey Tabaka2251d822017-04-20 16:04:07 -0700570 uint32_t num_elements = out_layers.size();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800571 for (size_t i = 0; i < num_elements; ++i) {
Corey Tabaka2c4aea32017-08-31 20:01:15 -0700572 for (auto& layer : layers_) {
573 if (layer.GetLayerHandle() == out_layers[i]) {
574 layer.Finish(out_fences[i]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800575 }
576 }
577 }
578}
579
Steven Thomas050b2c82017-03-06 11:45:16 -0800580void HardwareComposer::SetDisplaySurfaces(
Corey Tabaka2251d822017-04-20 16:04:07 -0700581 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces) {
Jin Qian7480c062017-03-21 00:04:15 +0000582 ALOGI("HardwareComposer::SetDisplaySurfaces: surface count=%zd",
583 surfaces.size());
Corey Tabaka2251d822017-04-20 16:04:07 -0700584 const bool display_idle = surfaces.size() == 0;
585 {
586 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Steven Thomasbfe46a02018-02-16 14:27:35 -0800587 surfaces_ = std::move(surfaces);
588 surfaces_changed_ = true;
Corey Tabaka2251d822017-04-20 16:04:07 -0700589 }
590
Steven Thomasaf336272018-01-04 17:36:47 -0800591 if (request_display_callback_ && !is_standalone_device_)
Steven Thomas2ddf5672017-06-15 11:38:40 -0700592 request_display_callback_(!display_idle);
593
Corey Tabaka2251d822017-04-20 16:04:07 -0700594 // Set idle state based on whether there are any surfaces to handle.
595 UpdatePostThreadState(PostThreadState::Idle, display_idle);
Steven Thomas050b2c82017-03-06 11:45:16 -0800596}
Jin Qian7480c062017-03-21 00:04:15 +0000597
John Bates954796e2017-05-11 11:00:31 -0700598int HardwareComposer::OnNewGlobalBuffer(DvrGlobalBufferKey key,
599 IonBuffer& ion_buffer) {
Okan Arikan822b7102017-05-08 13:31:34 -0700600 if (key == DvrGlobalBuffers::kVsyncBuffer) {
601 vsync_ring_ = std::make_unique<CPUMappedBroadcastRing<DvrVsyncRing>>(
602 &ion_buffer, CPUUsageMode::WRITE_OFTEN);
603
604 if (vsync_ring_->IsMapped() == false) {
605 return -EPERM;
606 }
607 }
608
609 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700610 return MapConfigBuffer(ion_buffer);
611 }
612
613 return 0;
614}
615
616void HardwareComposer::OnDeletedGlobalBuffer(DvrGlobalBufferKey key) {
Okan Arikan822b7102017-05-08 13:31:34 -0700617 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700618 ConfigBufferDeleted();
619 }
620}
621
622int HardwareComposer::MapConfigBuffer(IonBuffer& ion_buffer) {
623 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700624 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700625
Okan Arikan6f468c62017-05-31 14:48:30 -0700626 if (ion_buffer.width() < DvrConfigRing::MemorySize()) {
John Bates954796e2017-05-11 11:00:31 -0700627 ALOGE("HardwareComposer::MapConfigBuffer: invalid buffer size.");
628 return -EINVAL;
629 }
630
631 void* buffer_base = 0;
632 int result = ion_buffer.Lock(ion_buffer.usage(), 0, 0, ion_buffer.width(),
633 ion_buffer.height(), &buffer_base);
634 if (result != 0) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700635 ALOGE(
636 "HardwareComposer::MapConfigBuffer: Failed to map vrflinger config "
637 "buffer.");
John Bates954796e2017-05-11 11:00:31 -0700638 return -EPERM;
639 }
640
Okan Arikan6f468c62017-05-31 14:48:30 -0700641 shared_config_ring_ = DvrConfigRing::Create(buffer_base, ion_buffer.width());
John Bates954796e2017-05-11 11:00:31 -0700642 ion_buffer.Unlock();
643
644 return 0;
645}
646
647void HardwareComposer::ConfigBufferDeleted() {
648 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700649 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700650}
651
652void HardwareComposer::UpdateConfigBuffer() {
653 std::lock_guard<std::mutex> lock(shared_config_mutex_);
654 if (!shared_config_ring_.is_valid())
655 return;
656 // Copy from latest record in shared_config_ring_ to local copy.
Okan Arikan6f468c62017-05-31 14:48:30 -0700657 DvrConfig record;
John Bates954796e2017-05-11 11:00:31 -0700658 if (shared_config_ring_.GetNewest(&shared_config_ring_sequence_, &record)) {
John Batescc65c3c2017-09-28 14:43:19 -0700659 ALOGI("DvrConfig updated: sequence %u, post offset %d",
660 shared_config_ring_sequence_, record.frame_post_offset_ns);
661 ++shared_config_ring_sequence_;
John Bates954796e2017-05-11 11:00:31 -0700662 post_thread_config_ = record;
663 }
664}
665
Corey Tabaka2251d822017-04-20 16:04:07 -0700666int HardwareComposer::PostThreadPollInterruptible(
Steven Thomasb02664d2017-07-26 18:48:28 -0700667 const pdx::LocalHandle& event_fd, int requested_events, int timeout_ms) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800668 pollfd pfd[2] = {
669 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700670 .fd = event_fd.Get(),
Steven Thomas66747c12017-03-22 18:45:31 -0700671 .events = static_cast<short>(requested_events),
672 .revents = 0,
Steven Thomas050b2c82017-03-06 11:45:16 -0800673 },
674 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700675 .fd = post_thread_event_fd_.Get(),
Steven Thomas050b2c82017-03-06 11:45:16 -0800676 .events = POLLPRI | POLLIN,
677 .revents = 0,
678 },
679 };
680 int ret, error;
681 do {
Steven Thomasb02664d2017-07-26 18:48:28 -0700682 ret = poll(pfd, 2, timeout_ms);
Steven Thomas050b2c82017-03-06 11:45:16 -0800683 error = errno;
684 ALOGW_IF(ret < 0,
685 "HardwareComposer::PostThreadPollInterruptible: Error during "
686 "poll(): %s (%d)",
687 strerror(error), error);
688 } while (ret < 0 && error == EINTR);
689
690 if (ret < 0) {
691 return -error;
Steven Thomasb02664d2017-07-26 18:48:28 -0700692 } else if (ret == 0) {
693 return -ETIMEDOUT;
Steven Thomas050b2c82017-03-06 11:45:16 -0800694 } else if (pfd[0].revents != 0) {
695 return 0;
696 } else if (pfd[1].revents != 0) {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -0700697 ALOGI("VrHwcPost thread interrupted: revents=%x", pfd[1].revents);
Steven Thomas050b2c82017-03-06 11:45:16 -0800698 return kPostThreadInterrupted;
699 } else {
700 return 0;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800701 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800702}
703
Steven Thomasbfe46a02018-02-16 14:27:35 -0800704// Sleep until the next predicted vsync, returning the predicted vsync
705// timestamp.
706Status<int64_t> HardwareComposer::WaitForPredictedVSync() {
707 const int64_t predicted_vsync_time = last_vsync_timestamp_ +
708 (target_display_->vsync_period_ns * vsync_prediction_interval_);
Corey Tabakab3732f02017-09-16 00:58:54 -0700709 const int error = SleepUntil(predicted_vsync_time);
710 if (error < 0) {
711 ALOGE("HardwareComposer::WaifForVSync:: Failed to sleep: %s",
712 strerror(-error));
Steven Thomasb02664d2017-07-26 18:48:28 -0700713 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800714 }
Corey Tabakab3732f02017-09-16 00:58:54 -0700715 return {predicted_vsync_time};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800716}
717
718int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) {
719 const int timer_fd = vsync_sleep_timer_fd_.Get();
720 const itimerspec wakeup_itimerspec = {
721 .it_interval = {.tv_sec = 0, .tv_nsec = 0},
722 .it_value = NsToTimespec(wakeup_timestamp),
723 };
724 int ret =
725 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr);
726 int error = errno;
727 if (ret < 0) {
728 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s",
729 strerror(error));
730 return -error;
731 }
732
Corey Tabaka451256f2017-08-22 11:59:15 -0700733 return PostThreadPollInterruptible(vsync_sleep_timer_fd_, POLLIN,
734 /*timeout_ms*/ -1);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800735}
736
737void HardwareComposer::PostThread() {
738 // NOLINTNEXTLINE(runtime/int)
Steven Thomas050b2c82017-03-06 11:45:16 -0800739 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("VrHwcPost"), 0, 0, 0);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800740
Corey Tabaka2251d822017-04-20 16:04:07 -0700741 // Set the scheduler to SCHED_FIFO with high priority. If this fails here
742 // there may have been a startup timing issue between this thread and
743 // performanced. Try again later when this thread becomes active.
744 bool thread_policy_setup =
745 SetThreadPolicy("graphics:high", "/system/performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800746
Steven Thomas050b2c82017-03-06 11:45:16 -0800747 // Create a timerfd based on CLOCK_MONOTINIC.
748 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
749 LOG_ALWAYS_FATAL_IF(
750 !vsync_sleep_timer_fd_,
751 "HardwareComposer: Failed to create vsync sleep timerfd: %s",
752 strerror(errno));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800753
Steven Thomasbfe46a02018-02-16 14:27:35 -0800754 struct VsyncEyeOffsets { int64_t left_ns, right_ns; };
Steven Thomas050b2c82017-03-06 11:45:16 -0800755 bool was_running = false;
756
Steven Thomasbfe46a02018-02-16 14:27:35 -0800757 auto get_vsync_eye_offsets = [this]() -> VsyncEyeOffsets {
758 VsyncEyeOffsets offsets;
759 offsets.left_ns =
760 GetPosePredictionTimeOffset(target_display_->vsync_period_ns);
761
762 // TODO(jbates) Query vblank time from device, when such an API is
763 // available. This value (6.3%) was measured on A00 in low persistence mode.
764 int64_t vblank_ns = target_display_->vsync_period_ns * 63 / 1000;
765 offsets.right_ns = (target_display_->vsync_period_ns - vblank_ns) / 2;
766
767 // Check property for overriding right eye offset value.
768 offsets.right_ns =
769 property_get_int64(kRightEyeOffsetProperty, offsets.right_ns);
770
771 return offsets;
772 };
773
774 VsyncEyeOffsets vsync_eye_offsets = get_vsync_eye_offsets();
775
Steven Thomasaf336272018-01-04 17:36:47 -0800776 if (is_standalone_device_) {
777 // First, wait until boot finishes.
778 std::unique_lock<std::mutex> lock(post_thread_mutex_);
779 if (PostThreadCondWait(lock, -1, [this] { return boot_finished_; })) {
780 return;
781 }
782
783 // Then, wait until we're either leaving the quiescent state, or the boot
784 // finished display off timeout expires.
785 if (PostThreadCondWait(lock, kBootFinishedDisplayOffTimeoutSec,
786 [this] { return !post_thread_quiescent_; })) {
787 return;
788 }
789
790 LOG_ALWAYS_FATAL_IF(post_thread_state_ & PostThreadState::Suspended,
791 "Vr flinger should own the display by now.");
792 post_thread_resumed_ = true;
793 post_thread_ready_.notify_all();
Steven Thomasbfe46a02018-02-16 14:27:35 -0800794 if (!composer_)
795 CreateComposer();
Steven Thomasaf336272018-01-04 17:36:47 -0800796 }
797
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800798 while (1) {
799 ATRACE_NAME("HardwareComposer::PostThread");
800
John Bates954796e2017-05-11 11:00:31 -0700801 // Check for updated config once per vsync.
802 UpdateConfigBuffer();
803
Corey Tabaka2251d822017-04-20 16:04:07 -0700804 while (post_thread_quiescent_) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800805 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -0700806 ALOGI("HardwareComposer::PostThread: Entering quiescent state.");
807
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700808 if (was_running) {
809 vsync_trace_parity_ = false;
810 ATRACE_INT(kVsyncTraceEventName, 0);
811 }
812
Steven Thomasbfe46a02018-02-16 14:27:35 -0800813 // Tear down resources.
814 OnPostThreadPaused();
Corey Tabaka2251d822017-04-20 16:04:07 -0700815 was_running = false;
816 post_thread_resumed_ = false;
817 post_thread_ready_.notify_all();
818
Steven Thomasaf336272018-01-04 17:36:47 -0800819 if (PostThreadCondWait(lock, -1,
820 [this] { return !post_thread_quiescent_; })) {
821 // A true return value means we've been asked to quit.
Corey Tabaka2251d822017-04-20 16:04:07 -0700822 return;
Steven Thomas282a5ed2017-02-07 18:07:01 -0800823 }
Corey Tabaka2251d822017-04-20 16:04:07 -0700824
Corey Tabaka2251d822017-04-20 16:04:07 -0700825 post_thread_resumed_ = true;
826 post_thread_ready_.notify_all();
827
828 ALOGI("HardwareComposer::PostThread: Exiting quiescent state.");
Steven Thomas050b2c82017-03-06 11:45:16 -0800829 }
830
Steven Thomasbfe46a02018-02-16 14:27:35 -0800831 if (!composer_)
832 CreateComposer();
833
834 bool target_display_changed = UpdateTargetDisplay();
835 bool just_resumed_running = !was_running;
836 was_running = true;
837
838 if (target_display_changed)
839 vsync_eye_offsets = get_vsync_eye_offsets();
840
841 if (just_resumed_running) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800842 OnPostThreadResumed();
Corey Tabaka2251d822017-04-20 16:04:07 -0700843
844 // Try to setup the scheduler policy if it failed during startup. Only
845 // attempt to do this on transitions from inactive to active to avoid
846 // spamming the system with RPCs and log messages.
847 if (!thread_policy_setup) {
848 thread_policy_setup =
849 SetThreadPolicy("graphics:high", "/system/performance");
850 }
Steven Thomasbfe46a02018-02-16 14:27:35 -0800851 }
Corey Tabakab3732f02017-09-16 00:58:54 -0700852
Steven Thomasbfe46a02018-02-16 14:27:35 -0800853 if (target_display_changed || just_resumed_running) {
Corey Tabakab3732f02017-09-16 00:58:54 -0700854 // Initialize the last vsync timestamp with the current time. The
855 // predictor below uses this time + the vsync interval in absolute time
856 // units for the initial delay. Once the driver starts reporting vsync the
857 // predictor will sync up with the real vsync.
858 last_vsync_timestamp_ = GetSystemClockNs();
Steven Thomasbfe46a02018-02-16 14:27:35 -0800859 vsync_prediction_interval_ = 1;
860 retire_fence_fds_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800861 }
862
863 int64_t vsync_timestamp = 0;
864 {
Corey Tabakab3732f02017-09-16 00:58:54 -0700865 TRACE_FORMAT("wait_vsync|vsync=%u;last_timestamp=%" PRId64
866 ";prediction_interval=%d|",
867 vsync_count_ + 1, last_vsync_timestamp_,
868 vsync_prediction_interval_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800869
Steven Thomasbfe46a02018-02-16 14:27:35 -0800870 auto status = WaitForPredictedVSync();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800871 ALOGE_IF(
Corey Tabakab3732f02017-09-16 00:58:54 -0700872 !status,
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800873 "HardwareComposer::PostThread: Failed to wait for vsync event: %s",
Corey Tabakab3732f02017-09-16 00:58:54 -0700874 status.GetErrorMessage().c_str());
875
876 // If there was an error either sleeping was interrupted due to pausing or
877 // there was an error getting the latest timestamp.
878 if (!status)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800879 continue;
Corey Tabakab3732f02017-09-16 00:58:54 -0700880
881 // Predicted vsync timestamp for this interval. This is stable because we
882 // use absolute time for the wakeup timer.
883 vsync_timestamp = status.get();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800884 }
885
Steven Thomasdfde8fa2018-04-19 16:00:58 -0700886 vsync_trace_parity_ = !vsync_trace_parity_;
887 ATRACE_INT(kVsyncTraceEventName, vsync_trace_parity_ ? 1 : 0);
888
Corey Tabakab3732f02017-09-16 00:58:54 -0700889 // Advance the vsync counter only if the system is keeping up with hardware
890 // vsync to give clients an indication of the delays.
891 if (vsync_prediction_interval_ == 1)
892 ++vsync_count_;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800893
Steven Thomasbfe46a02018-02-16 14:27:35 -0800894 UpdateLayerConfig();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800895
Okan Arikan822b7102017-05-08 13:31:34 -0700896 // Publish the vsync event.
897 if (vsync_ring_) {
898 DvrVsync vsync;
899 vsync.vsync_count = vsync_count_;
900 vsync.vsync_timestamp_ns = vsync_timestamp;
Steven Thomasbfe46a02018-02-16 14:27:35 -0800901 vsync.vsync_left_eye_offset_ns = vsync_eye_offsets.left_ns;
902 vsync.vsync_right_eye_offset_ns = vsync_eye_offsets.right_ns;
903 vsync.vsync_period_ns = target_display_->vsync_period_ns;
Okan Arikan822b7102017-05-08 13:31:34 -0700904
905 vsync_ring_->Publish(vsync);
906 }
907
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800908 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700909 // Sleep until shortly before vsync.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800910 ATRACE_NAME("sleep");
911
Steven Thomasbfe46a02018-02-16 14:27:35 -0800912 const int64_t display_time_est_ns =
913 vsync_timestamp + target_display_->vsync_period_ns;
Corey Tabaka2251d822017-04-20 16:04:07 -0700914 const int64_t now_ns = GetSystemClockNs();
John Bates954796e2017-05-11 11:00:31 -0700915 const int64_t sleep_time_ns = display_time_est_ns - now_ns -
916 post_thread_config_.frame_post_offset_ns;
917 const int64_t wakeup_time_ns =
918 display_time_est_ns - post_thread_config_.frame_post_offset_ns;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800919
920 ATRACE_INT64("sleep_time_ns", sleep_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800921 if (sleep_time_ns > 0) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700922 int error = SleepUntil(wakeup_time_ns);
John Bates46684842017-12-13 15:26:50 -0800923 ALOGE_IF(error < 0 && error != kPostThreadInterrupted,
924 "HardwareComposer::PostThread: Failed to sleep: %s",
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800925 strerror(-error));
John Bates46684842017-12-13 15:26:50 -0800926 // If the sleep was interrupted (error == kPostThreadInterrupted),
927 // we still go through and present this frame because we may have set
928 // layers earlier and we want to flush the Composer's internal command
929 // buffer by continuing through to validate and present.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800930 }
931 }
932
Corey Tabakab3732f02017-09-16 00:58:54 -0700933 {
Steven Thomasbfe46a02018-02-16 14:27:35 -0800934 auto status = composer_callback_->GetVsyncTime(target_display_->id);
Corey Tabakab3732f02017-09-16 00:58:54 -0700935
936 // If we failed to read vsync there might be a problem with the driver.
937 // Since there's nothing we can do just behave as though we didn't get an
938 // updated vsync time and let the prediction continue.
939 const int64_t current_vsync_timestamp =
940 status ? status.get() : last_vsync_timestamp_;
941
942 const bool vsync_delayed =
943 last_vsync_timestamp_ == current_vsync_timestamp;
944 ATRACE_INT("vsync_delayed", vsync_delayed);
945
946 // If vsync was delayed advance the prediction interval and allow the
947 // fence logic in PostLayers() to skip the frame.
948 if (vsync_delayed) {
949 ALOGW(
950 "HardwareComposer::PostThread: VSYNC timestamp did not advance "
951 "since last frame: timestamp=%" PRId64 " prediction_interval=%d",
952 current_vsync_timestamp, vsync_prediction_interval_);
953 vsync_prediction_interval_++;
954 } else {
955 // We have an updated vsync timestamp, reset the prediction interval.
956 last_vsync_timestamp_ = current_vsync_timestamp;
957 vsync_prediction_interval_ = 1;
958 }
959 }
960
Steven Thomasbfe46a02018-02-16 14:27:35 -0800961 PostLayers(target_display_->id);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800962 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800963}
964
Steven Thomasbfe46a02018-02-16 14:27:35 -0800965bool HardwareComposer::UpdateTargetDisplay() {
966 bool target_display_changed = false;
967 auto displays = composer_callback_->GetDisplays();
968 if (displays.external_display_was_hotplugged) {
969 bool was_using_external_display = !target_display_->is_primary;
970 if (was_using_external_display) {
971 // The external display was hotplugged, so make sure to ignore any bad
972 // display errors as we destroy the layers.
973 for (auto& layer: layers_)
974 layer.IgnoreBadDisplayErrorsOnDestroy(true);
975 }
976
977 if (displays.external_display) {
978 // External display was connected
979 external_display_ = GetDisplayParams(composer_.get(),
980 *displays.external_display, /*is_primary*/ false);
981
mamika4f14de2019-08-30 07:27:14 -0700982 ALOGI("External display connected. Switching to external display.");
983 target_display_ = &(*external_display_);
984 target_display_changed = true;
Steven Thomasbfe46a02018-02-16 14:27:35 -0800985 } else {
986 // External display was disconnected
987 external_display_ = std::nullopt;
988 if (was_using_external_display) {
989 ALOGI("External display disconnected. Switching to primary display.");
990 target_display_ = &primary_display_;
991 target_display_changed = true;
992 }
993 }
994 }
995
996 if (target_display_changed) {
997 // If we're switching to the external display, turn the primary display off.
998 if (!target_display_->is_primary) {
999 EnableDisplay(primary_display_, false);
1000 }
1001 // If we're switching to the primary display, and the external display is
1002 // still connected, turn the external display off.
1003 else if (target_display_->is_primary && external_display_) {
1004 EnableDisplay(*external_display_, false);
1005 }
1006
mamik913cc132019-09-13 14:58:43 -07001007 // Update the cached edid data for the current display.
1008 UpdateEdidData(composer_.get(), target_display_->id);
1009
Steven Thomasbfe46a02018-02-16 14:27:35 -08001010 // Turn the new target display on.
1011 EnableDisplay(*target_display_, true);
1012
1013 // When we switch displays we need to recreate all the layers, so clear the
1014 // current list, which will trigger layer recreation.
1015 layers_.clear();
1016 }
1017
1018 return target_display_changed;
1019}
1020
Corey Tabaka2251d822017-04-20 16:04:07 -07001021// Checks for changes in the surface stack and updates the layer config to
1022// accomodate the new stack.
Steven Thomasbfe46a02018-02-16 14:27:35 -08001023void HardwareComposer::UpdateLayerConfig() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001024 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
Steven Thomas050b2c82017-03-06 11:45:16 -08001025 {
Corey Tabaka2251d822017-04-20 16:04:07 -07001026 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -07001027
Steven Thomasbfe46a02018-02-16 14:27:35 -08001028 if (!surfaces_changed_ && (!layers_.empty() || surfaces_.empty()))
1029 return;
1030
1031 surfaces = surfaces_;
1032 surfaces_changed_ = false;
Steven Thomas050b2c82017-03-06 11:45:16 -08001033 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001034
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001035 ATRACE_NAME("UpdateLayerConfig_HwLayers");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001036
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001037 // Sort the new direct surface list by z-order to determine the relative order
1038 // of the surfaces. This relative order is used for the HWC z-order value to
1039 // insulate VrFlinger and HWC z-order semantics from each other.
1040 std::sort(surfaces.begin(), surfaces.end(), [](const auto& a, const auto& b) {
1041 return a->z_order() < b->z_order();
1042 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001043
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001044 // Prepare a new layer stack, pulling in layers from the previous
1045 // layer stack that are still active and updating their attributes.
1046 std::vector<Layer> layers;
1047 size_t layer_index = 0;
1048 for (const auto& surface : surfaces) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001049 // The bottom layer is opaque, other layers blend.
1050 HWC::BlendMode blending =
1051 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001052
1053 // Try to find a layer for this surface in the set of active layers.
1054 auto search =
1055 std::lower_bound(layers_.begin(), layers_.end(), surface->surface_id());
1056 const bool found = search != layers_.end() &&
1057 search->GetSurfaceId() == surface->surface_id();
1058 if (found) {
1059 // Update the attributes of the layer that may have changed.
1060 search->SetBlending(blending);
1061 search->SetZOrder(layer_index); // Relative z-order.
1062
1063 // Move the existing layer to the new layer set and remove the empty layer
1064 // object from the current set.
1065 layers.push_back(std::move(*search));
1066 layers_.erase(search);
1067 } else {
1068 // Insert a layer for the new surface.
Steven Thomasbfe46a02018-02-16 14:27:35 -08001069 layers.emplace_back(composer_.get(), *target_display_, surface, blending,
1070 HWC::Composition::Device, layer_index);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001071 }
1072
1073 ALOGI_IF(
1074 TRACE,
1075 "HardwareComposer::UpdateLayerConfig: layer_index=%zu surface_id=%d",
1076 layer_index, layers[layer_index].GetSurfaceId());
1077
1078 layer_index++;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001079 }
1080
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001081 // Sort the new layer stack by ascending surface id.
1082 std::sort(layers.begin(), layers.end());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001083
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001084 // Replace the previous layer set with the new layer set. The destructor of
1085 // the previous set will clean up the remaining Layers that are not moved to
1086 // the new layer set.
1087 layers_ = std::move(layers);
1088
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001089 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001090 layers_.size());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001091}
1092
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001093std::vector<sp<IVsyncCallback>>::const_iterator
1094HardwareComposer::VsyncService::FindCallback(
1095 const sp<IVsyncCallback>& callback) const {
1096 sp<IBinder> binder = IInterface::asBinder(callback);
1097 return std::find_if(callbacks_.cbegin(), callbacks_.cend(),
1098 [&](const sp<IVsyncCallback>& callback) {
1099 return IInterface::asBinder(callback) == binder;
1100 });
1101}
1102
1103status_t HardwareComposer::VsyncService::registerCallback(
1104 const sp<IVsyncCallback> callback) {
1105 std::lock_guard<std::mutex> autolock(mutex_);
1106 if (FindCallback(callback) == callbacks_.cend()) {
1107 callbacks_.push_back(callback);
1108 }
Tianyu Jiang932fb4f2018-11-15 11:09:58 -08001109 return OK;
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001110}
1111
1112status_t HardwareComposer::VsyncService::unregisterCallback(
1113 const sp<IVsyncCallback> callback) {
1114 std::lock_guard<std::mutex> autolock(mutex_);
1115 auto iter = FindCallback(callback);
1116 if (iter != callbacks_.cend()) {
1117 callbacks_.erase(iter);
1118 }
Tianyu Jiang932fb4f2018-11-15 11:09:58 -08001119 return OK;
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001120}
1121
1122void HardwareComposer::VsyncService::OnVsync(int64_t vsync_timestamp) {
1123 ATRACE_NAME("VsyncService::OnVsync");
1124 std::lock_guard<std::mutex> autolock(mutex_);
1125 for (auto iter = callbacks_.begin(); iter != callbacks_.end();) {
1126 if ((*iter)->onVsync(vsync_timestamp) == android::DEAD_OBJECT) {
1127 iter = callbacks_.erase(iter);
1128 } else {
1129 ++iter;
1130 }
1131 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001132}
1133
Steven Thomasb02664d2017-07-26 18:48:28 -07001134Return<void> HardwareComposer::ComposerCallback::onHotplug(
Steven Thomas6e8f7062017-11-22 14:15:29 -08001135 Hwc2::Display display, IComposerCallback::Connection conn) {
Steven Thomasbfe46a02018-02-16 14:27:35 -08001136 std::lock_guard<std::mutex> lock(mutex_);
1137 ALOGI("onHotplug display=%" PRIu64 " conn=%d", display, conn);
1138
1139 bool is_primary = !got_first_hotplug_ || display == primary_display_.id;
1140
Steven Thomas6e8f7062017-11-22 14:15:29 -08001141 // Our first onHotplug callback is always for the primary display.
Steven Thomasbfe46a02018-02-16 14:27:35 -08001142 if (!got_first_hotplug_) {
Steven Thomas6e8f7062017-11-22 14:15:29 -08001143 LOG_ALWAYS_FATAL_IF(conn != IComposerCallback::Connection::CONNECTED,
1144 "Initial onHotplug callback should be primary display connected");
Steven Thomasbfe46a02018-02-16 14:27:35 -08001145 got_first_hotplug_ = true;
1146 } else if (is_primary) {
1147 ALOGE("Ignoring unexpected onHotplug() call for primary display");
1148 return Void();
1149 }
1150
1151 if (conn == IComposerCallback::Connection::CONNECTED) {
1152 if (!is_primary)
1153 external_display_ = DisplayInfo();
1154 DisplayInfo& display_info = is_primary ?
1155 primary_display_ : *external_display_;
1156 display_info.id = display;
Steven Thomas6e8f7062017-11-22 14:15:29 -08001157
Corey Tabakab3732f02017-09-16 00:58:54 -07001158 std::array<char, 1024> buffer;
1159 snprintf(buffer.data(), buffer.size(),
1160 "/sys/class/graphics/fb%" PRIu64 "/vsync_event", display);
1161 if (LocalHandle handle{buffer.data(), O_RDONLY}) {
1162 ALOGI(
1163 "HardwareComposer::ComposerCallback::onHotplug: Driver supports "
1164 "vsync_event node for display %" PRIu64,
1165 display);
Steven Thomasbfe46a02018-02-16 14:27:35 -08001166 display_info.driver_vsync_event_fd = std::move(handle);
Corey Tabakab3732f02017-09-16 00:58:54 -07001167 } else {
1168 ALOGI(
1169 "HardwareComposer::ComposerCallback::onHotplug: Driver does not "
1170 "support vsync_event node for display %" PRIu64,
1171 display);
1172 }
Steven Thomasbfe46a02018-02-16 14:27:35 -08001173 } else if (conn == IComposerCallback::Connection::DISCONNECTED) {
1174 external_display_ = std::nullopt;
Corey Tabakab3732f02017-09-16 00:58:54 -07001175 }
1176
Steven Thomasbfe46a02018-02-16 14:27:35 -08001177 if (!is_primary)
1178 external_display_was_hotplugged_ = true;
1179
Steven Thomasb02664d2017-07-26 18:48:28 -07001180 return Void();
1181}
1182
1183Return<void> HardwareComposer::ComposerCallback::onRefresh(
1184 Hwc2::Display /*display*/) {
1185 return hardware::Void();
1186}
1187
Corey Tabaka451256f2017-08-22 11:59:15 -07001188Return<void> HardwareComposer::ComposerCallback::onVsync(Hwc2::Display display,
1189 int64_t timestamp) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001190 TRACE_FORMAT("vsync_callback|display=%" PRIu64 ";timestamp=%" PRId64 "|",
1191 display, timestamp);
1192 std::lock_guard<std::mutex> lock(mutex_);
Steven Thomasbfe46a02018-02-16 14:27:35 -08001193 DisplayInfo* display_info = GetDisplayInfo(display);
1194 if (display_info) {
Steven Thomasbfe46a02018-02-16 14:27:35 -08001195 display_info->callback_vsync_timestamp = timestamp;
Steven Thomasb02664d2017-07-26 18:48:28 -07001196 }
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001197 if (primary_display_.id == display && vsync_service_ != nullptr) {
1198 vsync_service_->OnVsync(timestamp);
1199 }
Steven Thomasbfe46a02018-02-16 14:27:35 -08001200
Steven Thomasb02664d2017-07-26 18:48:28 -07001201 return Void();
1202}
1203
Ady Abraham7159f572019-10-11 11:10:18 -07001204Return<void> HardwareComposer::ComposerCallback::onVsync_2_4(
1205 Hwc2::Display /*display*/, int64_t /*timestamp*/,
1206 Hwc2::VsyncPeriodNanos /*vsyncPeriodNanos*/) {
1207 LOG_ALWAYS_FATAL("Unexpected onVsync_2_4 callback");
1208 return Void();
1209}
1210
1211Return<void> HardwareComposer::ComposerCallback::onVsyncPeriodTimingChanged(
1212 Hwc2::Display /*display*/,
1213 const Hwc2::VsyncPeriodChangeTimeline& /*updatedTimeline*/) {
1214 LOG_ALWAYS_FATAL("Unexpected onVsyncPeriodTimingChanged callback");
1215 return Void();
1216}
1217
Ady Abrahamb0433bc2020-01-08 17:31:06 -08001218Return<void> HardwareComposer::ComposerCallback::onSeamlessPossible(
1219 Hwc2::Display /*display*/) {
1220 LOG_ALWAYS_FATAL("Unexpected onSeamlessPossible callback");
1221 return Void();
1222}
1223
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001224void HardwareComposer::ComposerCallback::SetVsyncService(
1225 const sp<VsyncService>& vsync_service) {
1226 std::lock_guard<std::mutex> lock(mutex_);
1227 vsync_service_ = vsync_service;
1228}
1229
Steven Thomasbfe46a02018-02-16 14:27:35 -08001230HardwareComposer::ComposerCallback::Displays
1231HardwareComposer::ComposerCallback::GetDisplays() {
1232 std::lock_guard<std::mutex> lock(mutex_);
1233 Displays displays;
1234 displays.primary_display = primary_display_.id;
1235 if (external_display_)
1236 displays.external_display = external_display_->id;
1237 if (external_display_was_hotplugged_) {
1238 external_display_was_hotplugged_ = false;
1239 displays.external_display_was_hotplugged = true;
1240 }
1241 return displays;
1242}
1243
1244Status<int64_t> HardwareComposer::ComposerCallback::GetVsyncTime(
1245 hwc2_display_t display) {
Steven Thomasdfde8fa2018-04-19 16:00:58 -07001246 std::lock_guard<std::mutex> autolock(mutex_);
Steven Thomasbfe46a02018-02-16 14:27:35 -08001247 DisplayInfo* display_info = GetDisplayInfo(display);
1248 if (!display_info) {
1249 ALOGW("Attempt to get vsync time for unknown display %" PRIu64, display);
1250 return ErrorStatus(EINVAL);
1251 }
1252
Corey Tabakab3732f02017-09-16 00:58:54 -07001253 // See if the driver supports direct vsync events.
Steven Thomasbfe46a02018-02-16 14:27:35 -08001254 LocalHandle& event_fd = display_info->driver_vsync_event_fd;
Corey Tabakab3732f02017-09-16 00:58:54 -07001255 if (!event_fd) {
1256 // Fall back to returning the last timestamp returned by the vsync
1257 // callback.
Steven Thomasbfe46a02018-02-16 14:27:35 -08001258 return display_info->callback_vsync_timestamp;
Corey Tabakab3732f02017-09-16 00:58:54 -07001259 }
1260
1261 // When the driver supports the vsync_event sysfs node we can use it to
1262 // determine the latest vsync timestamp, even if the HWC callback has been
1263 // delayed.
1264
1265 // The driver returns data in the form "VSYNC=<timestamp ns>".
1266 std::array<char, 32> data;
1267 data.fill('\0');
1268
1269 // Seek back to the beginning of the event file.
1270 int ret = lseek(event_fd.Get(), 0, SEEK_SET);
1271 if (ret < 0) {
1272 const int error = errno;
1273 ALOGE(
1274 "HardwareComposer::ComposerCallback::GetVsyncTime: Failed to seek "
1275 "vsync event fd: %s",
1276 strerror(error));
1277 return ErrorStatus(error);
1278 }
1279
1280 // Read the vsync event timestamp.
1281 ret = read(event_fd.Get(), data.data(), data.size());
1282 if (ret < 0) {
1283 const int error = errno;
1284 ALOGE_IF(error != EAGAIN,
1285 "HardwareComposer::ComposerCallback::GetVsyncTime: Error "
1286 "while reading timestamp: %s",
1287 strerror(error));
1288 return ErrorStatus(error);
1289 }
1290
1291 int64_t timestamp;
1292 ret = sscanf(data.data(), "VSYNC=%" PRIu64,
1293 reinterpret_cast<uint64_t*>(&timestamp));
1294 if (ret < 0) {
1295 const int error = errno;
1296 ALOGE(
1297 "HardwareComposer::ComposerCallback::GetVsyncTime: Error while "
1298 "parsing timestamp: %s",
1299 strerror(error));
1300 return ErrorStatus(error);
1301 }
1302
1303 return {timestamp};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001304}
1305
Steven Thomasbfe46a02018-02-16 14:27:35 -08001306HardwareComposer::ComposerCallback::DisplayInfo*
1307HardwareComposer::ComposerCallback::GetDisplayInfo(hwc2_display_t display) {
1308 if (display == primary_display_.id) {
1309 return &primary_display_;
1310 } else if (external_display_ && display == external_display_->id) {
1311 return &(*external_display_);
1312 }
1313 return nullptr;
1314}
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001315
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001316void Layer::Reset() {
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001317 if (hardware_composer_layer_) {
Steven Thomasbfe46a02018-02-16 14:27:35 -08001318 HWC::Error error =
1319 composer_->destroyLayer(display_params_.id, hardware_composer_layer_);
1320 if (error != HWC::Error::None &&
1321 (!ignore_bad_display_errors_on_destroy_ ||
1322 error != HWC::Error::BadDisplay)) {
1323 ALOGE("destroyLayer() failed for display %" PRIu64 ", layer %" PRIu64
1324 ". error: %s", display_params_.id, hardware_composer_layer_,
1325 error.to_string().c_str());
1326 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001327 hardware_composer_layer_ = 0;
1328 }
1329
Corey Tabaka2251d822017-04-20 16:04:07 -07001330 z_order_ = 0;
1331 blending_ = HWC::BlendMode::None;
Corey Tabaka2251d822017-04-20 16:04:07 -07001332 composition_type_ = HWC::Composition::Invalid;
1333 target_composition_type_ = composition_type_;
1334 source_ = EmptyVariant{};
1335 acquire_fence_.Close();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001336 surface_rect_functions_applied_ = false;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001337 pending_visibility_settings_ = true;
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001338 cached_buffer_map_.clear();
Steven Thomasbfe46a02018-02-16 14:27:35 -08001339 ignore_bad_display_errors_on_destroy_ = false;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001340}
1341
Steven Thomasbfe46a02018-02-16 14:27:35 -08001342Layer::Layer(Hwc2::Composer* composer, const DisplayParams& display_params,
1343 const std::shared_ptr<DirectDisplaySurface>& surface,
1344 HWC::BlendMode blending, HWC::Composition composition_type,
1345 size_t z_order)
1346 : composer_(composer),
1347 display_params_(display_params),
1348 z_order_{z_order},
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001349 blending_{blending},
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001350 target_composition_type_{composition_type},
1351 source_{SourceSurface{surface}} {
1352 CommonLayerSetup();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001353}
1354
Steven Thomasbfe46a02018-02-16 14:27:35 -08001355Layer::Layer(Hwc2::Composer* composer, const DisplayParams& display_params,
1356 const std::shared_ptr<IonBuffer>& buffer, HWC::BlendMode blending,
1357 HWC::Composition composition_type, size_t z_order)
1358 : composer_(composer),
1359 display_params_(display_params),
1360 z_order_{z_order},
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001361 blending_{blending},
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001362 target_composition_type_{composition_type},
1363 source_{SourceBuffer{buffer}} {
1364 CommonLayerSetup();
1365}
1366
1367Layer::~Layer() { Reset(); }
1368
Chih-Hung Hsieh5bc849f2018-09-25 14:21:50 -07001369Layer::Layer(Layer&& other) noexcept { *this = std::move(other); }
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001370
Chih-Hung Hsieh5bc849f2018-09-25 14:21:50 -07001371Layer& Layer::operator=(Layer&& other) noexcept {
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001372 if (this != &other) {
1373 Reset();
1374 using std::swap;
Steven Thomasbfe46a02018-02-16 14:27:35 -08001375 swap(composer_, other.composer_);
1376 swap(display_params_, other.display_params_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001377 swap(hardware_composer_layer_, other.hardware_composer_layer_);
1378 swap(z_order_, other.z_order_);
1379 swap(blending_, other.blending_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001380 swap(composition_type_, other.composition_type_);
1381 swap(target_composition_type_, other.target_composition_type_);
1382 swap(source_, other.source_);
1383 swap(acquire_fence_, other.acquire_fence_);
1384 swap(surface_rect_functions_applied_,
1385 other.surface_rect_functions_applied_);
1386 swap(pending_visibility_settings_, other.pending_visibility_settings_);
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001387 swap(cached_buffer_map_, other.cached_buffer_map_);
Steven Thomasbfe46a02018-02-16 14:27:35 -08001388 swap(ignore_bad_display_errors_on_destroy_,
1389 other.ignore_bad_display_errors_on_destroy_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001390 }
1391 return *this;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001392}
1393
Corey Tabaka2251d822017-04-20 16:04:07 -07001394void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
1395 if (source_.is<SourceBuffer>())
1396 std::get<SourceBuffer>(source_) = {buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001397}
1398
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001399void Layer::SetBlending(HWC::BlendMode blending) {
1400 if (blending_ != blending) {
1401 blending_ = blending;
1402 pending_visibility_settings_ = true;
1403 }
1404}
1405
1406void Layer::SetZOrder(size_t z_order) {
1407 if (z_order_ != z_order) {
1408 z_order_ = z_order;
1409 pending_visibility_settings_ = true;
1410 }
1411}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001412
1413IonBuffer* Layer::GetBuffer() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001414 struct Visitor {
1415 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
1416 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
1417 IonBuffer* operator()(EmptyVariant) { return nullptr; }
1418 };
1419 return source_.Visit(Visitor{});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001420}
1421
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001422void Layer::UpdateVisibilitySettings() {
1423 if (pending_visibility_settings_) {
1424 pending_visibility_settings_ = false;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001425
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001426 HWC::Error error;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001427
1428 error = composer_->setLayerBlendMode(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001429 display_params_.id, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001430 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1431 ALOGE_IF(error != HWC::Error::None,
1432 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1433 error.to_string().c_str());
1434
Steven Thomasbfe46a02018-02-16 14:27:35 -08001435 error = composer_->setLayerZOrder(display_params_.id,
1436 hardware_composer_layer_, z_order_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001437 ALOGE_IF(error != HWC::Error::None,
1438 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1439 error.to_string().c_str());
1440 }
1441}
1442
1443void Layer::UpdateLayerSettings() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001444 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001445
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001446 UpdateVisibilitySettings();
1447
Corey Tabaka2251d822017-04-20 16:04:07 -07001448 // TODO(eieio): Use surface attributes or some other mechanism to control
1449 // the layer display frame.
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001450 error = composer_->setLayerDisplayFrame(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001451 display_params_.id, hardware_composer_layer_,
1452 {0, 0, display_params_.width, display_params_.height});
Corey Tabaka2251d822017-04-20 16:04:07 -07001453 ALOGE_IF(error != HWC::Error::None,
1454 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1455 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001456
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001457 error = composer_->setLayerVisibleRegion(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001458 display_params_.id, hardware_composer_layer_,
1459 {{0, 0, display_params_.width, display_params_.height}});
Corey Tabaka2251d822017-04-20 16:04:07 -07001460 ALOGE_IF(error != HWC::Error::None,
1461 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1462 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001463
Steven Thomasbfe46a02018-02-16 14:27:35 -08001464 error = composer_->setLayerPlaneAlpha(display_params_.id,
1465 hardware_composer_layer_, 1.0f);
Corey Tabaka2251d822017-04-20 16:04:07 -07001466 ALOGE_IF(error != HWC::Error::None,
1467 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1468 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001469}
1470
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001471void Layer::CommonLayerSetup() {
Steven Thomasbfe46a02018-02-16 14:27:35 -08001472 HWC::Error error = composer_->createLayer(display_params_.id,
Steven Thomas6e8f7062017-11-22 14:15:29 -08001473 &hardware_composer_layer_);
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001474 ALOGE_IF(error != HWC::Error::None,
1475 "Layer::CommonLayerSetup: Failed to create layer on primary "
1476 "display: %s",
1477 error.to_string().c_str());
1478 UpdateLayerSettings();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001479}
1480
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001481bool Layer::CheckAndUpdateCachedBuffer(std::size_t slot, int buffer_id) {
1482 auto search = cached_buffer_map_.find(slot);
1483 if (search != cached_buffer_map_.end() && search->second == buffer_id)
1484 return true;
1485
1486 // Assign or update the buffer slot.
1487 if (buffer_id >= 0)
1488 cached_buffer_map_[slot] = buffer_id;
1489 return false;
1490}
1491
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001492void Layer::Prepare() {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001493 int right, bottom, id;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -04001494 sp<GraphicBuffer> handle;
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001495 std::size_t slot;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001496
Corey Tabaka2251d822017-04-20 16:04:07 -07001497 // Acquire the next buffer according to the type of source.
1498 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001499 std::tie(right, bottom, id, handle, acquire_fence_, slot) =
1500 source.Acquire();
Corey Tabaka2251d822017-04-20 16:04:07 -07001501 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001502
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001503 TRACE_FORMAT("Layer::Prepare|buffer_id=%d;slot=%zu|", id, slot);
1504
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001505 // Update any visibility (blending, z-order) changes that occurred since
1506 // last prepare.
1507 UpdateVisibilitySettings();
1508
1509 // When a layer is first setup there may be some time before the first
1510 // buffer arrives. Setup the HWC layer as a solid color to stall for time
1511 // until the first buffer arrives. Once the first buffer arrives there will
1512 // always be a buffer for the frame even if it is old.
Corey Tabaka2251d822017-04-20 16:04:07 -07001513 if (!handle.get()) {
1514 if (composition_type_ == HWC::Composition::Invalid) {
1515 composition_type_ = HWC::Composition::SolidColor;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001516 composer_->setLayerCompositionType(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001517 display_params_.id, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001518 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1519 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
Steven Thomasbfe46a02018-02-16 14:27:35 -08001520 composer_->setLayerColor(display_params_.id, hardware_composer_layer_,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001521 layer_color);
Corey Tabaka2251d822017-04-20 16:04:07 -07001522 } else {
1523 // The composition type is already set. Nothing else to do until a
1524 // buffer arrives.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001525 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001526 } else {
Corey Tabaka2251d822017-04-20 16:04:07 -07001527 if (composition_type_ != target_composition_type_) {
1528 composition_type_ = target_composition_type_;
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001529 composer_->setLayerCompositionType(
Steven Thomasbfe46a02018-02-16 14:27:35 -08001530 display_params_.id, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001531 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1532 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001533
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001534 // See if the HWC cache already has this buffer.
1535 const bool cached = CheckAndUpdateCachedBuffer(slot, id);
1536 if (cached)
1537 handle = nullptr;
1538
Corey Tabaka2251d822017-04-20 16:04:07 -07001539 HWC::Error error{HWC::Error::None};
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001540 error =
Steven Thomasbfe46a02018-02-16 14:27:35 -08001541 composer_->setLayerBuffer(display_params_.id, hardware_composer_layer_,
Corey Tabaka0d07cdd2017-09-28 11:15:50 -07001542 slot, handle, acquire_fence_.Get());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001543
Corey Tabaka2251d822017-04-20 16:04:07 -07001544 ALOGE_IF(error != HWC::Error::None,
1545 "Layer::Prepare: Error setting layer buffer: %s",
1546 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001547
Corey Tabaka2251d822017-04-20 16:04:07 -07001548 if (!surface_rect_functions_applied_) {
1549 const float float_right = right;
1550 const float float_bottom = bottom;
Steven Thomasbfe46a02018-02-16 14:27:35 -08001551 error = composer_->setLayerSourceCrop(display_params_.id,
Corey Tabaka2c4aea32017-08-31 20:01:15 -07001552 hardware_composer_layer_,
1553 {0, 0, float_right, float_bottom});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001554
Corey Tabaka2251d822017-04-20 16:04:07 -07001555 ALOGE_IF(error != HWC::Error::None,
1556 "Layer::Prepare: Error setting layer source crop: %s",
1557 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001558
Corey Tabaka2251d822017-04-20 16:04:07 -07001559 surface_rect_functions_applied_ = true;
1560 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001561 }
1562}
1563
1564void Layer::Finish(int release_fence_fd) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001565 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1566 &source_, [release_fence_fd](auto& source) {
1567 source.Finish(LocalHandle(release_fence_fd));
1568 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001569}
1570
Corey Tabaka2251d822017-04-20 16:04:07 -07001571void Layer::Drop() { acquire_fence_.Close(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001572
1573} // namespace dvr
1574} // namespace android