blob: 9a9054db29660f484dabed5845554db1968a2bac [file] [log] [blame]
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001#include "hardware_composer.h"
2
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08003#include <cutils/properties.h>
4#include <cutils/sched_policy.h>
5#include <fcntl.h>
Corey Tabaka2251d822017-04-20 16:04:07 -07006#include <log/log.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08007#include <poll.h>
8#include <sync/sync.h>
9#include <sys/eventfd.h>
10#include <sys/prctl.h>
11#include <sys/resource.h>
12#include <sys/system_properties.h>
13#include <sys/timerfd.h>
Corey Tabaka2251d822017-04-20 16:04:07 -070014#include <time.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080015#include <unistd.h>
16#include <utils/Trace.h>
17
18#include <algorithm>
Corey Tabaka2251d822017-04-20 16:04:07 -070019#include <chrono>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080020#include <functional>
21#include <map>
Corey Tabaka0b485c92017-05-19 12:02:58 -070022#include <sstream>
23#include <string>
John Bates954796e2017-05-11 11:00:31 -070024#include <tuple>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080025
Corey Tabaka2251d822017-04-20 16:04:07 -070026#include <dvr/dvr_display_types.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080027#include <dvr/performance_client_api.h>
28#include <private/dvr/clock_ns.h>
Corey Tabaka2251d822017-04-20 16:04:07 -070029#include <private/dvr/ion_buffer.h>
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080030
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080031using android::pdx::LocalHandle;
Corey Tabaka2251d822017-04-20 16:04:07 -070032using android::pdx::rpc::EmptyVariant;
33using android::pdx::rpc::IfAnyOf;
34
35using namespace std::chrono_literals;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080036
37namespace android {
38namespace dvr {
39
40namespace {
41
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080042const char kBacklightBrightnessSysFile[] =
43 "/sys/class/leds/lcd-backlight/brightness";
44
45const char kPrimaryDisplayVSyncEventFile[] =
46 "/sys/class/graphics/fb0/vsync_event";
47
48const char kPrimaryDisplayWaitPPEventFile[] = "/sys/class/graphics/fb0/wait_pp";
49
50const char kDvrPerformanceProperty[] = "sys.dvr.performance";
51
Luke Song4b788322017-03-24 14:17:31 -070052const char kRightEyeOffsetProperty[] = "dvr.right_eye_offset_ns";
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080053
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080054// Get time offset from a vsync to when the pose for that vsync should be
55// predicted out to. For example, if scanout gets halfway through the frame
56// at the halfway point between vsyncs, then this could be half the period.
57// With global shutter displays, this should be changed to the offset to when
58// illumination begins. Low persistence adds a frame of latency, so we predict
59// to the center of the next frame.
60inline int64_t GetPosePredictionTimeOffset(int64_t vsync_period_ns) {
61 return (vsync_period_ns * 150) / 100;
62}
63
Corey Tabaka2251d822017-04-20 16:04:07 -070064// Attempts to set the scheduler class and partiton for the current thread.
65// Returns true on success or false on failure.
66bool SetThreadPolicy(const std::string& scheduler_class,
67 const std::string& partition) {
68 int error = dvrSetSchedulerClass(0, scheduler_class.c_str());
69 if (error < 0) {
70 ALOGE(
71 "SetThreadPolicy: Failed to set scheduler class \"%s\" for "
72 "thread_id=%d: %s",
73 scheduler_class.c_str(), gettid(), strerror(-error));
74 return false;
75 }
76 error = dvrSetCpuPartition(0, partition.c_str());
77 if (error < 0) {
78 ALOGE(
79 "SetThreadPolicy: Failed to set cpu partiton \"%s\" for thread_id=%d: "
80 "%s",
81 partition.c_str(), gettid(), strerror(-error));
82 return false;
83 }
84 return true;
85}
86
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080087} // anonymous namespace
88
Corey Tabaka2251d822017-04-20 16:04:07 -070089// Layer static data.
90Hwc2::Composer* Layer::hwc2_hidl_;
91const HWCDisplayMetrics* Layer::display_metrics_;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -080092
Corey Tabaka2251d822017-04-20 16:04:07 -070093// HardwareComposer static data;
94constexpr size_t HardwareComposer::kMaxHardwareLayers;
95
96HardwareComposer::HardwareComposer()
97 : HardwareComposer(nullptr, RequestDisplayCallback()) {}
98
99HardwareComposer::HardwareComposer(
100 Hwc2::Composer* hwc2_hidl, RequestDisplayCallback request_display_callback)
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800101 : initialized_(false),
102 hwc2_hidl_(hwc2_hidl),
Corey Tabaka2251d822017-04-20 16:04:07 -0700103 request_display_callback_(request_display_callback),
104 callbacks_(new ComposerCallback) {}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800105
106HardwareComposer::~HardwareComposer(void) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700107 UpdatePostThreadState(PostThreadState::Quit, true);
108 if (post_thread_.joinable())
Steven Thomas050b2c82017-03-06 11:45:16 -0800109 post_thread_.join();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800110}
111
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800112bool HardwareComposer::Initialize() {
113 if (initialized_) {
114 ALOGE("HardwareComposer::Initialize: already initialized.");
115 return false;
116 }
117
Corey Tabaka2251d822017-04-20 16:04:07 -0700118 HWC::Error error = HWC::Error::None;
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800119
120 Hwc2::Config config;
Corey Tabaka2251d822017-04-20 16:04:07 -0700121 error = hwc2_hidl_->getActiveConfig(HWC_DISPLAY_PRIMARY, &config);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800122
Corey Tabaka2251d822017-04-20 16:04:07 -0700123 if (error != HWC::Error::None) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800124 ALOGE("HardwareComposer: Failed to get current display config : %d",
125 config);
126 return false;
127 }
128
Corey Tabaka2251d822017-04-20 16:04:07 -0700129 error =
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800130 GetDisplayMetrics(HWC_DISPLAY_PRIMARY, config, &native_display_metrics_);
131
Corey Tabaka2251d822017-04-20 16:04:07 -0700132 if (error != HWC::Error::None) {
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800133 ALOGE(
134 "HardwareComposer: Failed to get display attributes for current "
135 "configuration : %d",
Corey Tabaka2251d822017-04-20 16:04:07 -0700136 error.value);
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800137 return false;
138 }
139
140 ALOGI(
141 "HardwareComposer: primary display attributes: width=%d height=%d "
142 "vsync_period_ns=%d DPI=%dx%d",
143 native_display_metrics_.width, native_display_metrics_.height,
144 native_display_metrics_.vsync_period_ns, native_display_metrics_.dpi.x,
145 native_display_metrics_.dpi.y);
146
147 // Set the display metrics but never use rotation to avoid the long latency of
148 // rotation processing in hwc.
149 display_transform_ = HWC_TRANSFORM_NONE;
150 display_metrics_ = native_display_metrics_;
151
Corey Tabaka2251d822017-04-20 16:04:07 -0700152 // Pass hwc instance and metrics to setup globals for Layer.
153 Layer::InitializeGlobals(hwc2_hidl_, &native_display_metrics_);
154
155 post_thread_event_fd_.Reset(eventfd(0, EFD_CLOEXEC | EFD_NONBLOCK));
Steven Thomas050b2c82017-03-06 11:45:16 -0800156 LOG_ALWAYS_FATAL_IF(
Corey Tabaka2251d822017-04-20 16:04:07 -0700157 !post_thread_event_fd_,
Steven Thomas050b2c82017-03-06 11:45:16 -0800158 "HardwareComposer: Failed to create interrupt event fd : %s",
159 strerror(errno));
160
161 post_thread_ = std::thread(&HardwareComposer::PostThread, this);
162
Stephen Kiazyk016e5e32017-02-21 17:09:22 -0800163 initialized_ = true;
164
165 return initialized_;
166}
167
Steven Thomas050b2c82017-03-06 11:45:16 -0800168void HardwareComposer::Enable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700169 UpdatePostThreadState(PostThreadState::Suspended, false);
Steven Thomas050b2c82017-03-06 11:45:16 -0800170}
171
172void HardwareComposer::Disable() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700173 UpdatePostThreadState(PostThreadState::Suspended, true);
Steven Thomas050b2c82017-03-06 11:45:16 -0800174}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800175
Corey Tabaka2251d822017-04-20 16:04:07 -0700176// Update the post thread quiescent state based on idle and suspended inputs.
177void HardwareComposer::UpdatePostThreadState(PostThreadStateType state,
178 bool suspend) {
179 std::unique_lock<std::mutex> lock(post_thread_mutex_);
180
181 // Update the votes in the state variable before evaluating the effective
182 // quiescent state. Any bits set in post_thread_state_ indicate that the post
183 // thread should be suspended.
184 if (suspend) {
185 post_thread_state_ |= state;
186 } else {
187 post_thread_state_ &= ~state;
188 }
189
190 const bool quit = post_thread_state_ & PostThreadState::Quit;
191 const bool effective_suspend = post_thread_state_ != PostThreadState::Active;
192 if (quit) {
193 post_thread_quiescent_ = true;
194 eventfd_write(post_thread_event_fd_.Get(), 1);
195 post_thread_wait_.notify_one();
196 } else if (effective_suspend && !post_thread_quiescent_) {
197 post_thread_quiescent_ = true;
198 eventfd_write(post_thread_event_fd_.Get(), 1);
199 } else if (!effective_suspend && post_thread_quiescent_) {
200 post_thread_quiescent_ = false;
201 eventfd_t value;
202 eventfd_read(post_thread_event_fd_.Get(), &value);
203 post_thread_wait_.notify_one();
204 }
205
206 // Wait until the post thread is in the requested state.
207 post_thread_ready_.wait(lock, [this, effective_suspend] {
208 return effective_suspend != post_thread_resumed_;
209 });
Steven Thomas050b2c82017-03-06 11:45:16 -0800210}
Steven Thomas282a5ed2017-02-07 18:07:01 -0800211
Steven Thomas050b2c82017-03-06 11:45:16 -0800212void HardwareComposer::OnPostThreadResumed() {
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700213 hwc2_hidl_->resetCommands();
214
Corey Tabaka2251d822017-04-20 16:04:07 -0700215 // HIDL HWC seems to have an internal race condition. If we submit a frame too
216 // soon after turning on VSync we don't get any VSync signals. Give poor HWC
217 // implementations a chance to enable VSync before we continue.
218 EnableVsync(false);
219 std::this_thread::sleep_for(100ms);
Steven Thomas050b2c82017-03-06 11:45:16 -0800220 EnableVsync(true);
Corey Tabaka2251d822017-04-20 16:04:07 -0700221 std::this_thread::sleep_for(100ms);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800222
Steven Thomas050b2c82017-03-06 11:45:16 -0800223 // TODO(skiazyk): We need to do something about accessing this directly,
224 // supposedly there is a backlight service on the way.
225 // TODO(steventhomas): When we change the backlight setting, will surface
226 // flinger (or something else) set it back to its original value once we give
227 // control of the display back to surface flinger?
228 SetBacklightBrightness(255);
Steven Thomas282a5ed2017-02-07 18:07:01 -0800229
Steven Thomas050b2c82017-03-06 11:45:16 -0800230 // Trigger target-specific performance mode change.
231 property_set(kDvrPerformanceProperty, "performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800232}
233
Steven Thomas050b2c82017-03-06 11:45:16 -0800234void HardwareComposer::OnPostThreadPaused() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700235 retire_fence_fds_.clear();
Steven Thomas050b2c82017-03-06 11:45:16 -0800236 display_surfaces_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800237
Corey Tabaka2251d822017-04-20 16:04:07 -0700238 for (size_t i = 0; i < kMaxHardwareLayers; ++i) {
239 layers_[i].Reset();
240 }
241 active_layer_count_ = 0;
Steven Thomas050b2c82017-03-06 11:45:16 -0800242
Steven Thomas050b2c82017-03-06 11:45:16 -0800243 EnableVsync(false);
244
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700245 hwc2_hidl_->resetCommands();
246
Steven Thomas050b2c82017-03-06 11:45:16 -0800247 // Trigger target-specific performance mode change.
248 property_set(kDvrPerformanceProperty, "idle");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800249}
250
Corey Tabaka2251d822017-04-20 16:04:07 -0700251HWC::Error HardwareComposer::Validate(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800252 uint32_t num_types;
253 uint32_t num_requests;
Corey Tabaka2251d822017-04-20 16:04:07 -0700254 HWC::Error error =
255 hwc2_hidl_->validateDisplay(display, &num_types, &num_requests);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800256
257 if (error == HWC2_ERROR_HAS_CHANGES) {
258 // TODO(skiazyk): We might need to inspect the requested changes first, but
259 // so far it seems like we shouldn't ever hit a bad state.
260 // error = hwc2_funcs_.accept_display_changes_fn_(hardware_composer_device_,
261 // display);
Corey Tabaka2251d822017-04-20 16:04:07 -0700262 error = hwc2_hidl_->acceptDisplayChanges(display);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800263 }
264
265 return error;
266}
267
268int32_t HardwareComposer::EnableVsync(bool enabled) {
269 return (int32_t)hwc2_hidl_->setVsyncEnabled(
270 HWC_DISPLAY_PRIMARY,
271 (Hwc2::IComposerClient::Vsync)(enabled ? HWC2_VSYNC_ENABLE
272 : HWC2_VSYNC_DISABLE));
273}
274
Corey Tabaka2251d822017-04-20 16:04:07 -0700275HWC::Error HardwareComposer::Present(hwc2_display_t display) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800276 int32_t present_fence;
Corey Tabaka2251d822017-04-20 16:04:07 -0700277 HWC::Error error = hwc2_hidl_->presentDisplay(display, &present_fence);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800278
279 // According to the documentation, this fence is signaled at the time of
280 // vsync/DMA for physical displays.
Corey Tabaka2251d822017-04-20 16:04:07 -0700281 if (error == HWC::Error::None) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800282 ATRACE_INT("HardwareComposer: VsyncFence", present_fence);
283 retire_fence_fds_.emplace_back(present_fence);
284 } else {
285 ATRACE_INT("HardwareComposer: PresentResult", error);
286 }
287
288 return error;
289}
290
Corey Tabaka2251d822017-04-20 16:04:07 -0700291HWC::Error HardwareComposer::GetDisplayAttribute(hwc2_display_t display,
292 hwc2_config_t config,
293 hwc2_attribute_t attribute,
294 int32_t* out_value) const {
295 return hwc2_hidl_->getDisplayAttribute(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800296 display, config, (Hwc2::IComposerClient::Attribute)attribute, out_value);
297}
298
Corey Tabaka2251d822017-04-20 16:04:07 -0700299HWC::Error HardwareComposer::GetDisplayMetrics(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800300 hwc2_display_t display, hwc2_config_t config,
301 HWCDisplayMetrics* out_metrics) const {
Corey Tabaka2251d822017-04-20 16:04:07 -0700302 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800303
Corey Tabaka2251d822017-04-20 16:04:07 -0700304 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_WIDTH,
305 &out_metrics->width);
306 if (error != HWC::Error::None) {
307 ALOGE(
308 "HardwareComposer::GetDisplayMetrics: Failed to get display width: %s",
309 error.to_string().c_str());
310 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800311 }
312
Corey Tabaka2251d822017-04-20 16:04:07 -0700313 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_HEIGHT,
314 &out_metrics->height);
315 if (error != HWC::Error::None) {
316 ALOGE(
317 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
318 error.to_string().c_str());
319 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800320 }
321
Corey Tabaka2251d822017-04-20 16:04:07 -0700322 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_VSYNC_PERIOD,
323 &out_metrics->vsync_period_ns);
324 if (error != HWC::Error::None) {
325 ALOGE(
326 "HardwareComposer::GetDisplayMetrics: Failed to get display height: %s",
327 error.to_string().c_str());
328 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800329 }
330
Corey Tabaka2251d822017-04-20 16:04:07 -0700331 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_DPI_X,
332 &out_metrics->dpi.x);
333 if (error != HWC::Error::None) {
334 ALOGE(
335 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI X: %s",
336 error.to_string().c_str());
337 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800338 }
339
Corey Tabaka2251d822017-04-20 16:04:07 -0700340 error = GetDisplayAttribute(display, config, HWC2_ATTRIBUTE_DPI_Y,
341 &out_metrics->dpi.y);
342 if (error != HWC::Error::None) {
343 ALOGE(
344 "HardwareComposer::GetDisplayMetrics: Failed to get display DPI Y: %s",
345 error.to_string().c_str());
346 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800347 }
348
Corey Tabaka2251d822017-04-20 16:04:07 -0700349 return HWC::Error::None;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800350}
351
Corey Tabaka0b485c92017-05-19 12:02:58 -0700352std::string HardwareComposer::Dump() {
353 std::unique_lock<std::mutex> lock(post_thread_mutex_);
354 std::ostringstream stream;
355
356 stream << "Display metrics: " << display_metrics_.width << "x"
357 << display_metrics_.height << " " << (display_metrics_.dpi.x / 1000.0)
358 << "x" << (display_metrics_.dpi.y / 1000.0) << " dpi @ "
359 << (1000000000.0 / display_metrics_.vsync_period_ns) << " Hz"
360 << std::endl;
361
362 stream << "Post thread resumed: " << post_thread_resumed_ << std::endl;
363 stream << "Active layers: " << active_layer_count_ << std::endl;
364 stream << std::endl;
365
366 for (size_t i = 0; i < active_layer_count_; i++) {
367 stream << "Layer " << i << ":";
368 stream << " type=" << layers_[i].GetCompositionType().to_string();
369 stream << " surface_id=" << layers_[i].GetSurfaceId();
370 stream << " buffer_id=" << layers_[i].GetBufferId();
371 stream << std::endl;
372 }
373 stream << std::endl;
374
375 if (post_thread_resumed_) {
376 stream << "Hardware Composer Debug Info:" << std::endl;
377 stream << hwc2_hidl_->dumpDebugInfo();
378 }
379
380 return stream.str();
381}
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800382
Corey Tabaka2251d822017-04-20 16:04:07 -0700383void HardwareComposer::PostLayers() {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800384 ATRACE_NAME("HardwareComposer::PostLayers");
385
386 // Setup the hardware composer layers with current buffers.
387 for (size_t i = 0; i < active_layer_count_; i++) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700388 layers_[i].Prepare();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800389 }
390
Corey Tabaka2251d822017-04-20 16:04:07 -0700391 HWC::Error error = Validate(HWC_DISPLAY_PRIMARY);
392 if (error != HWC::Error::None) {
393 ALOGE("HardwareComposer::PostLayers: Validate failed: %s",
394 error.to_string().c_str());
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700395 return;
396 }
397
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800398 // Now that we have taken in a frame from the application, we have a chance
399 // to drop the frame before passing the frame along to HWC.
400 // If the display driver has become backed up, we detect it here and then
401 // react by skipping this frame to catch up latency.
402 while (!retire_fence_fds_.empty() &&
403 (!retire_fence_fds_.front() ||
404 sync_wait(retire_fence_fds_.front().Get(), 0) == 0)) {
405 // There are only 2 fences in here, no performance problem to shift the
406 // array of ints.
407 retire_fence_fds_.erase(retire_fence_fds_.begin());
408 }
409
410 const bool is_frame_pending = IsFramePendingInDriver();
John Bates954796e2017-05-11 11:00:31 -0700411 const bool is_fence_pending = retire_fence_fds_.size() >
412 post_thread_config_.allowed_pending_fence_count;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800413
414 if (is_fence_pending || is_frame_pending) {
415 ATRACE_INT("frame_skip_count", ++frame_skip_count_);
416
417 ALOGW_IF(is_frame_pending, "Warning: frame already queued, dropping frame");
418 ALOGW_IF(is_fence_pending,
419 "Warning: dropping a frame to catch up with HWC (pending = %zd)",
420 retire_fence_fds_.size());
421
422 for (size_t i = 0; i < active_layer_count_; i++) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700423 layers_[i].Drop();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800424 }
425 return;
426 } else {
427 // Make the transition more obvious in systrace when the frame skip happens
428 // above.
429 ATRACE_INT("frame_skip_count", 0);
430 }
431
432#if TRACE
Corey Tabaka0b485c92017-05-19 12:02:58 -0700433 for (size_t i = 0; i < active_layer_count_; i++) {
434 ALOGI("HardwareComposer::PostLayers: layer=%zu buffer_id=%d composition=%s",
435 i, layers_[i].GetBufferId(),
Corey Tabaka2251d822017-04-20 16:04:07 -0700436 layers_[i].GetCompositionType().to_string().c_str());
Corey Tabaka0b485c92017-05-19 12:02:58 -0700437 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800438#endif
439
Corey Tabaka2251d822017-04-20 16:04:07 -0700440 error = Present(HWC_DISPLAY_PRIMARY);
441 if (error != HWC::Error::None) {
442 ALOGE("HardwareComposer::PostLayers: Present failed: %s",
443 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800444 return;
445 }
446
447 std::vector<Hwc2::Layer> out_layers;
448 std::vector<int> out_fences;
Corey Tabaka2251d822017-04-20 16:04:07 -0700449 error = hwc2_hidl_->getReleaseFences(HWC_DISPLAY_PRIMARY, &out_layers,
450 &out_fences);
451 ALOGE_IF(error != HWC::Error::None,
452 "HardwareComposer::PostLayers: Failed to get release fences: %s",
453 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800454
455 // Perform post-frame bookkeeping. Unused layers are a no-op.
Corey Tabaka2251d822017-04-20 16:04:07 -0700456 uint32_t num_elements = out_layers.size();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800457 for (size_t i = 0; i < num_elements; ++i) {
458 for (size_t j = 0; j < active_layer_count_; ++j) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700459 if (layers_[j].GetLayerHandle() == out_layers[i]) {
460 layers_[j].Finish(out_fences[i]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800461 }
462 }
463 }
464}
465
Steven Thomas050b2c82017-03-06 11:45:16 -0800466void HardwareComposer::SetDisplaySurfaces(
Corey Tabaka2251d822017-04-20 16:04:07 -0700467 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces) {
Jin Qian7480c062017-03-21 00:04:15 +0000468 ALOGI("HardwareComposer::SetDisplaySurfaces: surface count=%zd",
469 surfaces.size());
Corey Tabaka2251d822017-04-20 16:04:07 -0700470 const bool display_idle = surfaces.size() == 0;
471 {
472 std::unique_lock<std::mutex> lock(post_thread_mutex_);
473 pending_surfaces_ = std::move(surfaces);
474 }
475
476 // Set idle state based on whether there are any surfaces to handle.
477 UpdatePostThreadState(PostThreadState::Idle, display_idle);
478
479 // XXX: TEMPORARY
480 // Request control of the display based on whether there are any surfaces to
481 // handle. This callback sets the post thread active state once the transition
482 // is complete in SurfaceFlinger.
483 // TODO(eieio): Unify the control signal used to move SurfaceFlinger into VR
484 // mode. Currently this is hooked up to persistent VR mode, but perhaps this
485 // makes more sense to control it from VrCore, which could in turn base its
486 // decision on persistent VR mode.
487 if (request_display_callback_)
488 request_display_callback_(!display_idle);
Steven Thomas050b2c82017-03-06 11:45:16 -0800489}
Jin Qian7480c062017-03-21 00:04:15 +0000490
John Bates954796e2017-05-11 11:00:31 -0700491int HardwareComposer::OnNewGlobalBuffer(DvrGlobalBufferKey key,
492 IonBuffer& ion_buffer) {
Okan Arikan822b7102017-05-08 13:31:34 -0700493 if (key == DvrGlobalBuffers::kVsyncBuffer) {
494 vsync_ring_ = std::make_unique<CPUMappedBroadcastRing<DvrVsyncRing>>(
495 &ion_buffer, CPUUsageMode::WRITE_OFTEN);
496
497 if (vsync_ring_->IsMapped() == false) {
498 return -EPERM;
499 }
500 }
501
502 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700503 return MapConfigBuffer(ion_buffer);
504 }
505
506 return 0;
507}
508
509void HardwareComposer::OnDeletedGlobalBuffer(DvrGlobalBufferKey key) {
Okan Arikan822b7102017-05-08 13:31:34 -0700510 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700511 ConfigBufferDeleted();
512 }
513}
514
515int HardwareComposer::MapConfigBuffer(IonBuffer& ion_buffer) {
516 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700517 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700518
Okan Arikan6f468c62017-05-31 14:48:30 -0700519 if (ion_buffer.width() < DvrConfigRing::MemorySize()) {
John Bates954796e2017-05-11 11:00:31 -0700520 ALOGE("HardwareComposer::MapConfigBuffer: invalid buffer size.");
521 return -EINVAL;
522 }
523
524 void* buffer_base = 0;
525 int result = ion_buffer.Lock(ion_buffer.usage(), 0, 0, ion_buffer.width(),
526 ion_buffer.height(), &buffer_base);
527 if (result != 0) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700528 ALOGE(
529 "HardwareComposer::MapConfigBuffer: Failed to map vrflinger config "
530 "buffer.");
John Bates954796e2017-05-11 11:00:31 -0700531 return -EPERM;
532 }
533
Okan Arikan6f468c62017-05-31 14:48:30 -0700534 shared_config_ring_ = DvrConfigRing::Create(buffer_base, ion_buffer.width());
John Bates954796e2017-05-11 11:00:31 -0700535 ion_buffer.Unlock();
536
537 return 0;
538}
539
540void HardwareComposer::ConfigBufferDeleted() {
541 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700542 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700543}
544
545void HardwareComposer::UpdateConfigBuffer() {
546 std::lock_guard<std::mutex> lock(shared_config_mutex_);
547 if (!shared_config_ring_.is_valid())
548 return;
549 // Copy from latest record in shared_config_ring_ to local copy.
Okan Arikan6f468c62017-05-31 14:48:30 -0700550 DvrConfig record;
John Bates954796e2017-05-11 11:00:31 -0700551 if (shared_config_ring_.GetNewest(&shared_config_ring_sequence_, &record)) {
552 post_thread_config_ = record;
553 }
554}
555
Corey Tabaka2251d822017-04-20 16:04:07 -0700556int HardwareComposer::PostThreadPollInterruptible(
557 const pdx::LocalHandle& event_fd, int requested_events) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800558 pollfd pfd[2] = {
559 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700560 .fd = event_fd.Get(),
Steven Thomas66747c12017-03-22 18:45:31 -0700561 .events = static_cast<short>(requested_events),
562 .revents = 0,
Steven Thomas050b2c82017-03-06 11:45:16 -0800563 },
564 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700565 .fd = post_thread_event_fd_.Get(),
Steven Thomas050b2c82017-03-06 11:45:16 -0800566 .events = POLLPRI | POLLIN,
567 .revents = 0,
568 },
569 };
570 int ret, error;
571 do {
572 ret = poll(pfd, 2, -1);
573 error = errno;
574 ALOGW_IF(ret < 0,
575 "HardwareComposer::PostThreadPollInterruptible: Error during "
576 "poll(): %s (%d)",
577 strerror(error), error);
578 } while (ret < 0 && error == EINTR);
579
580 if (ret < 0) {
581 return -error;
582 } else if (pfd[0].revents != 0) {
583 return 0;
584 } else if (pfd[1].revents != 0) {
585 ALOGI("VrHwcPost thread interrupted");
586 return kPostThreadInterrupted;
587 } else {
588 return 0;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800589 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800590}
591
592// Reads the value of the display driver wait_pingpong state. Returns 0 or 1
593// (the value of the state) on success or a negative error otherwise.
594// TODO(eieio): This is pretty driver specific, this should be moved to a
595// separate class eventually.
596int HardwareComposer::ReadWaitPPState() {
597 // Gracefully handle when the kernel does not support this feature.
598 if (!primary_display_wait_pp_fd_)
599 return 0;
600
601 const int wait_pp_fd = primary_display_wait_pp_fd_.Get();
602 int ret, error;
603
604 ret = lseek(wait_pp_fd, 0, SEEK_SET);
605 if (ret < 0) {
606 error = errno;
607 ALOGE("HardwareComposer::ReadWaitPPState: Failed to seek wait_pp fd: %s",
608 strerror(error));
609 return -error;
610 }
611
612 char data = -1;
613 ret = read(wait_pp_fd, &data, sizeof(data));
614 if (ret < 0) {
615 error = errno;
616 ALOGE("HardwareComposer::ReadWaitPPState: Failed to read wait_pp state: %s",
617 strerror(error));
618 return -error;
619 }
620
621 switch (data) {
622 case '0':
623 return 0;
624 case '1':
625 return 1;
626 default:
627 ALOGE(
628 "HardwareComposer::ReadWaitPPState: Unexpected value for wait_pp: %d",
629 data);
630 return -EINVAL;
631 }
632}
633
634// Reads the timestamp of the last vsync from the display driver.
635// TODO(eieio): This is pretty driver specific, this should be moved to a
636// separate class eventually.
637int HardwareComposer::ReadVSyncTimestamp(int64_t* timestamp) {
638 const int event_fd = primary_display_vsync_event_fd_.Get();
639 int ret, error;
640
641 // The driver returns data in the form "VSYNC=<timestamp ns>".
642 std::array<char, 32> data;
643 data.fill('\0');
644
645 // Seek back to the beginning of the event file.
646 ret = lseek(event_fd, 0, SEEK_SET);
647 if (ret < 0) {
648 error = errno;
649 ALOGE(
650 "HardwareComposer::ReadVSyncTimestamp: Failed to seek vsync event fd: "
651 "%s",
652 strerror(error));
653 return -error;
654 }
655
656 // Read the vsync event timestamp.
657 ret = read(event_fd, data.data(), data.size());
658 if (ret < 0) {
659 error = errno;
660 ALOGE_IF(
661 error != EAGAIN,
662 "HardwareComposer::ReadVSyncTimestamp: Error while reading timestamp: "
663 "%s",
664 strerror(error));
665 return -error;
666 }
667
668 ret = sscanf(data.data(), "VSYNC=%" PRIu64,
669 reinterpret_cast<uint64_t*>(timestamp));
670 if (ret < 0) {
671 error = errno;
672 ALOGE(
673 "HardwareComposer::ReadVSyncTimestamp: Error while parsing timestamp: "
674 "%s",
675 strerror(error));
676 return -error;
677 }
678
679 return 0;
680}
681
682// Blocks until the next vsync event is signaled by the display driver.
683// TODO(eieio): This is pretty driver specific, this should be moved to a
684// separate class eventually.
Steven Thomas050b2c82017-03-06 11:45:16 -0800685int HardwareComposer::BlockUntilVSync() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700686 // Vsync is signaled by POLLPRI on the fb vsync node.
687 return PostThreadPollInterruptible(primary_display_vsync_event_fd_, POLLPRI);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800688}
689
690// Waits for the next vsync and returns the timestamp of the vsync event. If
691// vsync already passed since the last call, returns the latest vsync timestamp
692// instead of blocking. This method updates the last_vsync_timeout_ in the
693// process.
694//
695// TODO(eieio): This is pretty driver specific, this should be moved to a
696// separate class eventually.
697int HardwareComposer::WaitForVSync(int64_t* timestamp) {
698 int error;
699
700 // Get the current timestamp and decide what to do.
701 while (true) {
702 int64_t current_vsync_timestamp;
703 error = ReadVSyncTimestamp(&current_vsync_timestamp);
704 if (error < 0 && error != -EAGAIN)
705 return error;
706
707 if (error == -EAGAIN) {
708 // Vsync was turned off, wait for the next vsync event.
Steven Thomas050b2c82017-03-06 11:45:16 -0800709 error = BlockUntilVSync();
710 if (error < 0 || error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800711 return error;
712
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800713 // Try again to get the timestamp for this new vsync interval.
714 continue;
715 }
716
717 // Check that we advanced to a later vsync interval.
718 if (TimestampGT(current_vsync_timestamp, last_vsync_timestamp_)) {
719 *timestamp = last_vsync_timestamp_ = current_vsync_timestamp;
720 return 0;
721 }
722
723 // See how close we are to the next expected vsync. If we're within 1ms,
724 // sleep for 1ms and try again.
725 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
Corey Tabaka2251d822017-04-20 16:04:07 -0700726 const int64_t threshold_ns = 1000000; // 1ms
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800727
728 const int64_t next_vsync_est = last_vsync_timestamp_ + ns_per_frame;
729 const int64_t distance_to_vsync_est = next_vsync_est - GetSystemClockNs();
730
731 if (distance_to_vsync_est > threshold_ns) {
732 // Wait for vsync event notification.
Steven Thomas050b2c82017-03-06 11:45:16 -0800733 error = BlockUntilVSync();
734 if (error < 0 || error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800735 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800736 } else {
Steven Thomas050b2c82017-03-06 11:45:16 -0800737 // Sleep for a short time (1 millisecond) before retrying.
Corey Tabaka2251d822017-04-20 16:04:07 -0700738 error = SleepUntil(GetSystemClockNs() + threshold_ns);
Steven Thomas050b2c82017-03-06 11:45:16 -0800739 if (error < 0 || error == kPostThreadInterrupted)
740 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800741 }
742 }
743}
744
745int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) {
746 const int timer_fd = vsync_sleep_timer_fd_.Get();
747 const itimerspec wakeup_itimerspec = {
748 .it_interval = {.tv_sec = 0, .tv_nsec = 0},
749 .it_value = NsToTimespec(wakeup_timestamp),
750 };
751 int ret =
752 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr);
753 int error = errno;
754 if (ret < 0) {
755 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s",
756 strerror(error));
757 return -error;
758 }
759
Corey Tabaka2251d822017-04-20 16:04:07 -0700760 return PostThreadPollInterruptible(vsync_sleep_timer_fd_, POLLIN);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800761}
762
763void HardwareComposer::PostThread() {
764 // NOLINTNEXTLINE(runtime/int)
Steven Thomas050b2c82017-03-06 11:45:16 -0800765 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("VrHwcPost"), 0, 0, 0);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800766
Corey Tabaka2251d822017-04-20 16:04:07 -0700767 // Set the scheduler to SCHED_FIFO with high priority. If this fails here
768 // there may have been a startup timing issue between this thread and
769 // performanced. Try again later when this thread becomes active.
770 bool thread_policy_setup =
771 SetThreadPolicy("graphics:high", "/system/performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800772
Steven Thomas050b2c82017-03-06 11:45:16 -0800773#if ENABLE_BACKLIGHT_BRIGHTNESS
774 // TODO(hendrikw): This isn't required at the moment. It's possible that there
775 // is another method to access this when needed.
776 // Open the backlight brightness control sysfs node.
777 backlight_brightness_fd_ = LocalHandle(kBacklightBrightnessSysFile, O_RDWR);
778 ALOGW_IF(!backlight_brightness_fd_,
779 "HardwareComposer: Failed to open backlight brightness control: %s",
780 strerror(errno));
Corey Tabaka2251d822017-04-20 16:04:07 -0700781#endif // ENABLE_BACKLIGHT_BRIGHTNESS
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800782
Steven Thomas050b2c82017-03-06 11:45:16 -0800783 // Open the vsync event node for the primary display.
784 // TODO(eieio): Move this into a platform-specific class.
785 primary_display_vsync_event_fd_ =
786 LocalHandle(kPrimaryDisplayVSyncEventFile, O_RDONLY);
787 ALOGE_IF(!primary_display_vsync_event_fd_,
788 "HardwareComposer: Failed to open vsync event node for primary "
789 "display: %s",
790 strerror(errno));
791
792 // Open the wait pingpong status node for the primary display.
793 // TODO(eieio): Move this into a platform-specific class.
794 primary_display_wait_pp_fd_ =
795 LocalHandle(kPrimaryDisplayWaitPPEventFile, O_RDONLY);
796 ALOGW_IF(
797 !primary_display_wait_pp_fd_,
798 "HardwareComposer: Failed to open wait_pp node for primary display: %s",
799 strerror(errno));
800
801 // Create a timerfd based on CLOCK_MONOTINIC.
802 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
803 LOG_ALWAYS_FATAL_IF(
804 !vsync_sleep_timer_fd_,
805 "HardwareComposer: Failed to create vsync sleep timerfd: %s",
806 strerror(errno));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800807
808 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
809 const int64_t photon_offset_ns = GetPosePredictionTimeOffset(ns_per_frame);
810
811 // TODO(jbates) Query vblank time from device, when such an API is available.
812 // This value (6.3%) was measured on A00 in low persistence mode.
813 int64_t vblank_ns = ns_per_frame * 63 / 1000;
814 int64_t right_eye_photon_offset_ns = (ns_per_frame - vblank_ns) / 2;
815
816 // Check property for overriding right eye offset value.
817 right_eye_photon_offset_ns =
818 property_get_int64(kRightEyeOffsetProperty, right_eye_photon_offset_ns);
819
Steven Thomas050b2c82017-03-06 11:45:16 -0800820 bool was_running = false;
821
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800822 while (1) {
823 ATRACE_NAME("HardwareComposer::PostThread");
824
John Bates954796e2017-05-11 11:00:31 -0700825 // Check for updated config once per vsync.
826 UpdateConfigBuffer();
827
Corey Tabaka2251d822017-04-20 16:04:07 -0700828 while (post_thread_quiescent_) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800829 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -0700830 ALOGI("HardwareComposer::PostThread: Entering quiescent state.");
831
832 // Tear down resources.
833 OnPostThreadPaused();
834
835 was_running = false;
836 post_thread_resumed_ = false;
837 post_thread_ready_.notify_all();
838
839 if (post_thread_state_ & PostThreadState::Quit) {
840 ALOGI("HardwareComposer::PostThread: Quitting.");
841 return;
Steven Thomas282a5ed2017-02-07 18:07:01 -0800842 }
Corey Tabaka2251d822017-04-20 16:04:07 -0700843
844 post_thread_wait_.wait(lock, [this] { return !post_thread_quiescent_; });
845
846 post_thread_resumed_ = true;
847 post_thread_ready_.notify_all();
848
849 ALOGI("HardwareComposer::PostThread: Exiting quiescent state.");
Steven Thomas050b2c82017-03-06 11:45:16 -0800850 }
851
852 if (!was_running) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700853 // Setup resources.
Steven Thomas050b2c82017-03-06 11:45:16 -0800854 OnPostThreadResumed();
855 was_running = true;
Corey Tabaka2251d822017-04-20 16:04:07 -0700856
857 // Try to setup the scheduler policy if it failed during startup. Only
858 // attempt to do this on transitions from inactive to active to avoid
859 // spamming the system with RPCs and log messages.
860 if (!thread_policy_setup) {
861 thread_policy_setup =
862 SetThreadPolicy("graphics:high", "/system/performance");
863 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800864 }
865
866 int64_t vsync_timestamp = 0;
867 {
868 std::array<char, 128> buf;
869 snprintf(buf.data(), buf.size(), "wait_vsync|vsync=%d|",
870 vsync_count_ + 1);
871 ATRACE_NAME(buf.data());
872
Corey Tabaka2251d822017-04-20 16:04:07 -0700873 const int error = WaitForVSync(&vsync_timestamp);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800874 ALOGE_IF(
875 error < 0,
876 "HardwareComposer::PostThread: Failed to wait for vsync event: %s",
877 strerror(-error));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800878 // Don't bother processing this frame if a pause was requested
Steven Thomas050b2c82017-03-06 11:45:16 -0800879 if (error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800880 continue;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800881 }
882
883 ++vsync_count_;
884
Corey Tabaka2251d822017-04-20 16:04:07 -0700885 const bool layer_config_changed = UpdateLayerConfig();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800886
Okan Arikan822b7102017-05-08 13:31:34 -0700887 // Publish the vsync event.
888 if (vsync_ring_) {
889 DvrVsync vsync;
890 vsync.vsync_count = vsync_count_;
891 vsync.vsync_timestamp_ns = vsync_timestamp;
892 vsync.vsync_left_eye_offset_ns = photon_offset_ns;
893 vsync.vsync_right_eye_offset_ns = right_eye_photon_offset_ns;
894 vsync.vsync_period_ns = ns_per_frame;
895
896 vsync_ring_->Publish(vsync);
897 }
898
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800899 // Signal all of the vsync clients. Because absolute time is used for the
900 // wakeup time below, this can take a little time if necessary.
901 if (vsync_callback_)
Corey Tabaka2251d822017-04-20 16:04:07 -0700902 vsync_callback_(HWC_DISPLAY_PRIMARY, vsync_timestamp,
903 /*frame_time_estimate*/ 0, vsync_count_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800904
905 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700906 // Sleep until shortly before vsync.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800907 ATRACE_NAME("sleep");
908
Corey Tabaka2251d822017-04-20 16:04:07 -0700909 const int64_t display_time_est_ns = vsync_timestamp + ns_per_frame;
910 const int64_t now_ns = GetSystemClockNs();
John Bates954796e2017-05-11 11:00:31 -0700911 const int64_t sleep_time_ns = display_time_est_ns - now_ns -
912 post_thread_config_.frame_post_offset_ns;
913 const int64_t wakeup_time_ns =
914 display_time_est_ns - post_thread_config_.frame_post_offset_ns;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800915
916 ATRACE_INT64("sleep_time_ns", sleep_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800917 if (sleep_time_ns > 0) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700918 int error = SleepUntil(wakeup_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800919 ALOGE_IF(error < 0, "HardwareComposer::PostThread: Failed to sleep: %s",
920 strerror(-error));
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700921 if (error == kPostThreadInterrupted) {
922 if (layer_config_changed) {
923 // If the layer config changed we need to validateDisplay() even if
924 // we're going to drop the frame, to flush the Composer object's
925 // internal command buffer and apply our layer changes.
926 Validate(HWC_DISPLAY_PRIMARY);
927 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800928 continue;
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700929 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800930 }
931 }
932
Corey Tabaka2251d822017-04-20 16:04:07 -0700933 PostLayers();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800934 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800935}
936
Corey Tabaka2251d822017-04-20 16:04:07 -0700937// Checks for changes in the surface stack and updates the layer config to
938// accomodate the new stack.
Steven Thomas050b2c82017-03-06 11:45:16 -0800939bool HardwareComposer::UpdateLayerConfig() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700940 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
Steven Thomas050b2c82017-03-06 11:45:16 -0800941 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700942 std::unique_lock<std::mutex> lock(post_thread_mutex_);
943 if (pending_surfaces_.empty())
Steven Thomas050b2c82017-03-06 11:45:16 -0800944 return false;
Corey Tabaka2251d822017-04-20 16:04:07 -0700945
946 surfaces = std::move(pending_surfaces_);
Steven Thomas050b2c82017-03-06 11:45:16 -0800947 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800948
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800949 ATRACE_NAME("UpdateLayerConfig_HwLayers");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800950
Corey Tabaka2251d822017-04-20 16:04:07 -0700951 display_surfaces_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800952
Corey Tabaka2251d822017-04-20 16:04:07 -0700953 Layer* target_layer;
954 size_t layer_index;
955 for (layer_index = 0;
956 layer_index < std::min(surfaces.size(), kMaxHardwareLayers);
957 layer_index++) {
958 // The bottom layer is opaque, other layers blend.
959 HWC::BlendMode blending =
960 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
961 layers_[layer_index].Setup(surfaces[layer_index], blending,
962 display_transform_, HWC::Composition::Device,
963 layer_index);
964 display_surfaces_.push_back(surfaces[layer_index]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800965 }
966
Corey Tabaka2251d822017-04-20 16:04:07 -0700967 // Clear unused layers.
968 for (size_t i = layer_index; i < kMaxHardwareLayers; i++)
969 layers_[i].Reset();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800970
Corey Tabaka2251d822017-04-20 16:04:07 -0700971 active_layer_count_ = layer_index;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800972 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
973 active_layer_count_);
974
Corey Tabaka2251d822017-04-20 16:04:07 -0700975 // Any surfaces left over could not be assigned a hardware layer and will
976 // not be displayed.
977 ALOGW_IF(surfaces.size() != display_surfaces_.size(),
978 "HardwareComposer::UpdateLayerConfig: More surfaces than layers: "
979 "pending_surfaces=%zu display_surfaces=%zu",
980 surfaces.size(), display_surfaces_.size());
981
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800982 return true;
983}
984
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800985void HardwareComposer::SetVSyncCallback(VSyncCallback callback) {
986 vsync_callback_ = callback;
987}
988
989void HardwareComposer::HwcRefresh(hwc2_callback_data_t /*data*/,
990 hwc2_display_t /*display*/) {
991 // TODO(eieio): implement invalidate callbacks.
992}
993
994void HardwareComposer::HwcVSync(hwc2_callback_data_t /*data*/,
995 hwc2_display_t /*display*/,
996 int64_t /*timestamp*/) {
997 ATRACE_NAME(__PRETTY_FUNCTION__);
998 // Intentionally empty. HWC may require a callback to be set to enable vsync
999 // signals. We bypass this callback thread by monitoring the vsync event
1000 // directly, but signals still need to be enabled.
1001}
1002
1003void HardwareComposer::HwcHotplug(hwc2_callback_data_t /*callbackData*/,
1004 hwc2_display_t /*display*/,
1005 hwc2_connection_t /*connected*/) {
1006 // TODO(eieio): implement display hotplug callbacks.
1007}
1008
Steven Thomas3cfac282017-02-06 12:29:30 -08001009void HardwareComposer::OnHardwareComposerRefresh() {
1010 // TODO(steventhomas): Handle refresh.
1011}
1012
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001013void HardwareComposer::SetBacklightBrightness(int brightness) {
1014 if (backlight_brightness_fd_) {
1015 std::array<char, 32> text;
1016 const int length = snprintf(text.data(), text.size(), "%d", brightness);
1017 write(backlight_brightness_fd_.Get(), text.data(), length);
1018 }
1019}
1020
Corey Tabaka2251d822017-04-20 16:04:07 -07001021void Layer::InitializeGlobals(Hwc2::Composer* hwc2_hidl,
1022 const HWCDisplayMetrics* metrics) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001023 hwc2_hidl_ = hwc2_hidl;
1024 display_metrics_ = metrics;
1025}
1026
1027void Layer::Reset() {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001028 if (hwc2_hidl_ != nullptr && hardware_composer_layer_) {
1029 hwc2_hidl_->destroyLayer(HWC_DISPLAY_PRIMARY, hardware_composer_layer_);
1030 hardware_composer_layer_ = 0;
1031 }
1032
Corey Tabaka2251d822017-04-20 16:04:07 -07001033 z_order_ = 0;
1034 blending_ = HWC::BlendMode::None;
1035 transform_ = HWC::Transform::None;
1036 composition_type_ = HWC::Composition::Invalid;
1037 target_composition_type_ = composition_type_;
1038 source_ = EmptyVariant{};
1039 acquire_fence_.Close();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001040 surface_rect_functions_applied_ = false;
1041}
1042
Corey Tabaka2251d822017-04-20 16:04:07 -07001043void Layer::Setup(const std::shared_ptr<DirectDisplaySurface>& surface,
1044 HWC::BlendMode blending, HWC::Transform transform,
1045 HWC::Composition composition_type, size_t z_order) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001046 Reset();
Corey Tabaka2251d822017-04-20 16:04:07 -07001047 z_order_ = z_order;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001048 blending_ = blending;
1049 transform_ = transform;
Corey Tabaka2251d822017-04-20 16:04:07 -07001050 composition_type_ = HWC::Composition::Invalid;
1051 target_composition_type_ = composition_type;
1052 source_ = SourceSurface{surface};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001053 CommonLayerSetup();
1054}
1055
1056void Layer::Setup(const std::shared_ptr<IonBuffer>& buffer,
Corey Tabaka2251d822017-04-20 16:04:07 -07001057 HWC::BlendMode blending, HWC::Transform transform,
1058 HWC::Composition composition_type, size_t z_order) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001059 Reset();
Corey Tabaka2251d822017-04-20 16:04:07 -07001060 z_order_ = z_order;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001061 blending_ = blending;
1062 transform_ = transform;
Corey Tabaka2251d822017-04-20 16:04:07 -07001063 composition_type_ = HWC::Composition::Invalid;
1064 target_composition_type_ = composition_type;
1065 source_ = SourceBuffer{buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001066 CommonLayerSetup();
1067}
1068
Corey Tabaka2251d822017-04-20 16:04:07 -07001069void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
1070 if (source_.is<SourceBuffer>())
1071 std::get<SourceBuffer>(source_) = {buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001072}
1073
Corey Tabaka2251d822017-04-20 16:04:07 -07001074void Layer::SetBlending(HWC::BlendMode blending) { blending_ = blending; }
1075void Layer::SetZOrder(size_t z_order) { z_order_ = z_order; }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001076
1077IonBuffer* Layer::GetBuffer() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001078 struct Visitor {
1079 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
1080 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
1081 IonBuffer* operator()(EmptyVariant) { return nullptr; }
1082 };
1083 return source_.Visit(Visitor{});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001084}
1085
1086void Layer::UpdateLayerSettings() {
1087 if (!IsLayerSetup()) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001088 ALOGE(
1089 "HardwareComposer::Layer::UpdateLayerSettings: Attempt to update "
1090 "unused Layer!");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001091 return;
1092 }
1093
Corey Tabaka2251d822017-04-20 16:04:07 -07001094 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001095 hwc2_display_t display = HWC_DISPLAY_PRIMARY;
1096
Corey Tabaka2251d822017-04-20 16:04:07 -07001097 error = hwc2_hidl_->setLayerCompositionType(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001098 display, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001099 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1100 ALOGE_IF(
1101 error != HWC::Error::None,
1102 "Layer::UpdateLayerSettings: Error setting layer composition type: %s",
1103 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001104
Corey Tabaka2251d822017-04-20 16:04:07 -07001105 error = hwc2_hidl_->setLayerBlendMode(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001106 display, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001107 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1108 ALOGE_IF(error != HWC::Error::None,
1109 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1110 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001111
Corey Tabaka2251d822017-04-20 16:04:07 -07001112 // TODO(eieio): Use surface attributes or some other mechanism to control
1113 // the layer display frame.
1114 error = hwc2_hidl_->setLayerDisplayFrame(
1115 display, hardware_composer_layer_,
1116 {0, 0, display_metrics_->width, display_metrics_->height});
1117 ALOGE_IF(error != HWC::Error::None,
1118 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1119 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001120
Corey Tabaka2251d822017-04-20 16:04:07 -07001121 error = hwc2_hidl_->setLayerVisibleRegion(
1122 display, hardware_composer_layer_,
1123 {{0, 0, display_metrics_->width, display_metrics_->height}});
1124 ALOGE_IF(error != HWC::Error::None,
1125 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1126 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001127
Corey Tabaka2251d822017-04-20 16:04:07 -07001128 error =
1129 hwc2_hidl_->setLayerPlaneAlpha(display, hardware_composer_layer_, 1.0f);
1130 ALOGE_IF(error != HWC::Error::None,
1131 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1132 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001133
Corey Tabaka2251d822017-04-20 16:04:07 -07001134 error =
1135 hwc2_hidl_->setLayerZOrder(display, hardware_composer_layer_, z_order_);
1136 ALOGE_IF(error != HWC::Error::None,
1137 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1138 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001139}
1140
1141void Layer::CommonLayerSetup() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001142 HWC::Error error =
1143 hwc2_hidl_->createLayer(HWC_DISPLAY_PRIMARY, &hardware_composer_layer_);
1144 ALOGE_IF(
1145 error != HWC::Error::None,
1146 "Layer::CommonLayerSetup: Failed to create layer on primary display: %s",
1147 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001148 UpdateLayerSettings();
1149}
1150
1151void Layer::Prepare() {
1152 int right, bottom;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -04001153 sp<GraphicBuffer> handle;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001154
Corey Tabaka2251d822017-04-20 16:04:07 -07001155 // Acquire the next buffer according to the type of source.
1156 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
1157 std::tie(right, bottom, handle, acquire_fence_) = source.Acquire();
1158 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001159
Corey Tabaka2251d822017-04-20 16:04:07 -07001160 // When a layer is first setup there may be some time before the first buffer
1161 // arrives. Setup the HWC layer as a solid color to stall for time until the
1162 // first buffer arrives. Once the first buffer arrives there will always be a
1163 // buffer for the frame even if it is old.
1164 if (!handle.get()) {
1165 if (composition_type_ == HWC::Composition::Invalid) {
1166 composition_type_ = HWC::Composition::SolidColor;
1167 hwc2_hidl_->setLayerCompositionType(
1168 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1169 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1170 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
1171 hwc2_hidl_->setLayerColor(HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1172 layer_color);
1173 } else {
1174 // The composition type is already set. Nothing else to do until a
1175 // buffer arrives.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001176 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001177 } else {
Corey Tabaka2251d822017-04-20 16:04:07 -07001178 if (composition_type_ != target_composition_type_) {
1179 composition_type_ = target_composition_type_;
1180 hwc2_hidl_->setLayerCompositionType(
1181 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1182 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1183 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001184
Corey Tabaka2251d822017-04-20 16:04:07 -07001185 HWC::Error error{HWC::Error::None};
1186 error = hwc2_hidl_->setLayerBuffer(HWC_DISPLAY_PRIMARY,
1187 hardware_composer_layer_, 0, handle,
1188 acquire_fence_.Get());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001189
Corey Tabaka2251d822017-04-20 16:04:07 -07001190 ALOGE_IF(error != HWC::Error::None,
1191 "Layer::Prepare: Error setting layer buffer: %s",
1192 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001193
Corey Tabaka2251d822017-04-20 16:04:07 -07001194 if (!surface_rect_functions_applied_) {
1195 const float float_right = right;
1196 const float float_bottom = bottom;
1197 error = hwc2_hidl_->setLayerSourceCrop(HWC_DISPLAY_PRIMARY,
1198 hardware_composer_layer_,
1199 {0, 0, float_right, float_bottom});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001200
Corey Tabaka2251d822017-04-20 16:04:07 -07001201 ALOGE_IF(error != HWC::Error::None,
1202 "Layer::Prepare: Error setting layer source crop: %s",
1203 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001204
Corey Tabaka2251d822017-04-20 16:04:07 -07001205 surface_rect_functions_applied_ = true;
1206 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001207 }
1208}
1209
1210void Layer::Finish(int release_fence_fd) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001211 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1212 &source_, [release_fence_fd](auto& source) {
1213 source.Finish(LocalHandle(release_fence_fd));
1214 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001215}
1216
Corey Tabaka2251d822017-04-20 16:04:07 -07001217void Layer::Drop() { acquire_fence_.Close(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001218
1219} // namespace dvr
1220} // namespace android