blob: d937c889df8058edc252d0d801c11eb44f9b71c5 [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
Corey Tabaka89bbefc2017-06-06 16:14:21 -0700432#if TRACE > 1
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
Steven Thomas2ddf5672017-06-15 11:38:40 -0700476 if (request_display_callback_)
477 request_display_callback_(!display_idle);
478
Corey Tabaka2251d822017-04-20 16:04:07 -0700479 // Set idle state based on whether there are any surfaces to handle.
480 UpdatePostThreadState(PostThreadState::Idle, display_idle);
Steven Thomas050b2c82017-03-06 11:45:16 -0800481}
Jin Qian7480c062017-03-21 00:04:15 +0000482
John Bates954796e2017-05-11 11:00:31 -0700483int HardwareComposer::OnNewGlobalBuffer(DvrGlobalBufferKey key,
484 IonBuffer& ion_buffer) {
Okan Arikan822b7102017-05-08 13:31:34 -0700485 if (key == DvrGlobalBuffers::kVsyncBuffer) {
486 vsync_ring_ = std::make_unique<CPUMappedBroadcastRing<DvrVsyncRing>>(
487 &ion_buffer, CPUUsageMode::WRITE_OFTEN);
488
489 if (vsync_ring_->IsMapped() == false) {
490 return -EPERM;
491 }
492 }
493
494 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700495 return MapConfigBuffer(ion_buffer);
496 }
497
498 return 0;
499}
500
501void HardwareComposer::OnDeletedGlobalBuffer(DvrGlobalBufferKey key) {
Okan Arikan822b7102017-05-08 13:31:34 -0700502 if (key == DvrGlobalBuffers::kVrFlingerConfigBufferKey) {
John Bates954796e2017-05-11 11:00:31 -0700503 ConfigBufferDeleted();
504 }
505}
506
507int HardwareComposer::MapConfigBuffer(IonBuffer& ion_buffer) {
508 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700509 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700510
Okan Arikan6f468c62017-05-31 14:48:30 -0700511 if (ion_buffer.width() < DvrConfigRing::MemorySize()) {
John Bates954796e2017-05-11 11:00:31 -0700512 ALOGE("HardwareComposer::MapConfigBuffer: invalid buffer size.");
513 return -EINVAL;
514 }
515
516 void* buffer_base = 0;
517 int result = ion_buffer.Lock(ion_buffer.usage(), 0, 0, ion_buffer.width(),
518 ion_buffer.height(), &buffer_base);
519 if (result != 0) {
Corey Tabaka0b485c92017-05-19 12:02:58 -0700520 ALOGE(
521 "HardwareComposer::MapConfigBuffer: Failed to map vrflinger config "
522 "buffer.");
John Bates954796e2017-05-11 11:00:31 -0700523 return -EPERM;
524 }
525
Okan Arikan6f468c62017-05-31 14:48:30 -0700526 shared_config_ring_ = DvrConfigRing::Create(buffer_base, ion_buffer.width());
John Bates954796e2017-05-11 11:00:31 -0700527 ion_buffer.Unlock();
528
529 return 0;
530}
531
532void HardwareComposer::ConfigBufferDeleted() {
533 std::lock_guard<std::mutex> lock(shared_config_mutex_);
Okan Arikan6f468c62017-05-31 14:48:30 -0700534 shared_config_ring_ = DvrConfigRing();
John Bates954796e2017-05-11 11:00:31 -0700535}
536
537void HardwareComposer::UpdateConfigBuffer() {
538 std::lock_guard<std::mutex> lock(shared_config_mutex_);
539 if (!shared_config_ring_.is_valid())
540 return;
541 // Copy from latest record in shared_config_ring_ to local copy.
Okan Arikan6f468c62017-05-31 14:48:30 -0700542 DvrConfig record;
John Bates954796e2017-05-11 11:00:31 -0700543 if (shared_config_ring_.GetNewest(&shared_config_ring_sequence_, &record)) {
544 post_thread_config_ = record;
545 }
546}
547
Corey Tabaka2251d822017-04-20 16:04:07 -0700548int HardwareComposer::PostThreadPollInterruptible(
549 const pdx::LocalHandle& event_fd, int requested_events) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800550 pollfd pfd[2] = {
551 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700552 .fd = event_fd.Get(),
Steven Thomas66747c12017-03-22 18:45:31 -0700553 .events = static_cast<short>(requested_events),
554 .revents = 0,
Steven Thomas050b2c82017-03-06 11:45:16 -0800555 },
556 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700557 .fd = post_thread_event_fd_.Get(),
Steven Thomas050b2c82017-03-06 11:45:16 -0800558 .events = POLLPRI | POLLIN,
559 .revents = 0,
560 },
561 };
562 int ret, error;
563 do {
564 ret = poll(pfd, 2, -1);
565 error = errno;
566 ALOGW_IF(ret < 0,
567 "HardwareComposer::PostThreadPollInterruptible: Error during "
568 "poll(): %s (%d)",
569 strerror(error), error);
570 } while (ret < 0 && error == EINTR);
571
572 if (ret < 0) {
573 return -error;
574 } else if (pfd[0].revents != 0) {
575 return 0;
576 } else if (pfd[1].revents != 0) {
577 ALOGI("VrHwcPost thread interrupted");
578 return kPostThreadInterrupted;
579 } else {
580 return 0;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800581 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800582}
583
584// Reads the value of the display driver wait_pingpong state. Returns 0 or 1
585// (the value of the state) on success or a negative error otherwise.
586// TODO(eieio): This is pretty driver specific, this should be moved to a
587// separate class eventually.
588int HardwareComposer::ReadWaitPPState() {
589 // Gracefully handle when the kernel does not support this feature.
590 if (!primary_display_wait_pp_fd_)
591 return 0;
592
593 const int wait_pp_fd = primary_display_wait_pp_fd_.Get();
594 int ret, error;
595
596 ret = lseek(wait_pp_fd, 0, SEEK_SET);
597 if (ret < 0) {
598 error = errno;
599 ALOGE("HardwareComposer::ReadWaitPPState: Failed to seek wait_pp fd: %s",
600 strerror(error));
601 return -error;
602 }
603
604 char data = -1;
605 ret = read(wait_pp_fd, &data, sizeof(data));
606 if (ret < 0) {
607 error = errno;
608 ALOGE("HardwareComposer::ReadWaitPPState: Failed to read wait_pp state: %s",
609 strerror(error));
610 return -error;
611 }
612
613 switch (data) {
614 case '0':
615 return 0;
616 case '1':
617 return 1;
618 default:
619 ALOGE(
620 "HardwareComposer::ReadWaitPPState: Unexpected value for wait_pp: %d",
621 data);
622 return -EINVAL;
623 }
624}
625
626// Reads the timestamp of the last vsync from the display driver.
627// TODO(eieio): This is pretty driver specific, this should be moved to a
628// separate class eventually.
629int HardwareComposer::ReadVSyncTimestamp(int64_t* timestamp) {
630 const int event_fd = primary_display_vsync_event_fd_.Get();
631 int ret, error;
632
633 // The driver returns data in the form "VSYNC=<timestamp ns>".
634 std::array<char, 32> data;
635 data.fill('\0');
636
637 // Seek back to the beginning of the event file.
638 ret = lseek(event_fd, 0, SEEK_SET);
639 if (ret < 0) {
640 error = errno;
641 ALOGE(
642 "HardwareComposer::ReadVSyncTimestamp: Failed to seek vsync event fd: "
643 "%s",
644 strerror(error));
645 return -error;
646 }
647
648 // Read the vsync event timestamp.
649 ret = read(event_fd, data.data(), data.size());
650 if (ret < 0) {
651 error = errno;
652 ALOGE_IF(
653 error != EAGAIN,
654 "HardwareComposer::ReadVSyncTimestamp: Error while reading timestamp: "
655 "%s",
656 strerror(error));
657 return -error;
658 }
659
660 ret = sscanf(data.data(), "VSYNC=%" PRIu64,
661 reinterpret_cast<uint64_t*>(timestamp));
662 if (ret < 0) {
663 error = errno;
664 ALOGE(
665 "HardwareComposer::ReadVSyncTimestamp: Error while parsing timestamp: "
666 "%s",
667 strerror(error));
668 return -error;
669 }
670
671 return 0;
672}
673
674// Blocks until the next vsync event is signaled by the display driver.
675// TODO(eieio): This is pretty driver specific, this should be moved to a
676// separate class eventually.
Steven Thomas050b2c82017-03-06 11:45:16 -0800677int HardwareComposer::BlockUntilVSync() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700678 // Vsync is signaled by POLLPRI on the fb vsync node.
679 return PostThreadPollInterruptible(primary_display_vsync_event_fd_, POLLPRI);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800680}
681
682// Waits for the next vsync and returns the timestamp of the vsync event. If
683// vsync already passed since the last call, returns the latest vsync timestamp
684// instead of blocking. This method updates the last_vsync_timeout_ in the
685// process.
686//
687// TODO(eieio): This is pretty driver specific, this should be moved to a
688// separate class eventually.
689int HardwareComposer::WaitForVSync(int64_t* timestamp) {
690 int error;
691
692 // Get the current timestamp and decide what to do.
693 while (true) {
694 int64_t current_vsync_timestamp;
695 error = ReadVSyncTimestamp(&current_vsync_timestamp);
696 if (error < 0 && error != -EAGAIN)
697 return error;
698
699 if (error == -EAGAIN) {
700 // Vsync was turned off, wait for the next vsync event.
Steven Thomas050b2c82017-03-06 11:45:16 -0800701 error = BlockUntilVSync();
702 if (error < 0 || error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800703 return error;
704
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800705 // Try again to get the timestamp for this new vsync interval.
706 continue;
707 }
708
709 // Check that we advanced to a later vsync interval.
710 if (TimestampGT(current_vsync_timestamp, last_vsync_timestamp_)) {
711 *timestamp = last_vsync_timestamp_ = current_vsync_timestamp;
712 return 0;
713 }
714
715 // See how close we are to the next expected vsync. If we're within 1ms,
716 // sleep for 1ms and try again.
717 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
Corey Tabaka2251d822017-04-20 16:04:07 -0700718 const int64_t threshold_ns = 1000000; // 1ms
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800719
720 const int64_t next_vsync_est = last_vsync_timestamp_ + ns_per_frame;
721 const int64_t distance_to_vsync_est = next_vsync_est - GetSystemClockNs();
722
723 if (distance_to_vsync_est > threshold_ns) {
724 // Wait for vsync event notification.
Steven Thomas050b2c82017-03-06 11:45:16 -0800725 error = BlockUntilVSync();
726 if (error < 0 || error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800727 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800728 } else {
Steven Thomas050b2c82017-03-06 11:45:16 -0800729 // Sleep for a short time (1 millisecond) before retrying.
Corey Tabaka2251d822017-04-20 16:04:07 -0700730 error = SleepUntil(GetSystemClockNs() + threshold_ns);
Steven Thomas050b2c82017-03-06 11:45:16 -0800731 if (error < 0 || error == kPostThreadInterrupted)
732 return error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800733 }
734 }
735}
736
737int HardwareComposer::SleepUntil(int64_t wakeup_timestamp) {
738 const int timer_fd = vsync_sleep_timer_fd_.Get();
739 const itimerspec wakeup_itimerspec = {
740 .it_interval = {.tv_sec = 0, .tv_nsec = 0},
741 .it_value = NsToTimespec(wakeup_timestamp),
742 };
743 int ret =
744 timerfd_settime(timer_fd, TFD_TIMER_ABSTIME, &wakeup_itimerspec, nullptr);
745 int error = errno;
746 if (ret < 0) {
747 ALOGE("HardwareComposer::SleepUntil: Failed to set timerfd: %s",
748 strerror(error));
749 return -error;
750 }
751
Corey Tabaka2251d822017-04-20 16:04:07 -0700752 return PostThreadPollInterruptible(vsync_sleep_timer_fd_, POLLIN);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800753}
754
755void HardwareComposer::PostThread() {
756 // NOLINTNEXTLINE(runtime/int)
Steven Thomas050b2c82017-03-06 11:45:16 -0800757 prctl(PR_SET_NAME, reinterpret_cast<unsigned long>("VrHwcPost"), 0, 0, 0);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800758
Corey Tabaka2251d822017-04-20 16:04:07 -0700759 // Set the scheduler to SCHED_FIFO with high priority. If this fails here
760 // there may have been a startup timing issue between this thread and
761 // performanced. Try again later when this thread becomes active.
762 bool thread_policy_setup =
763 SetThreadPolicy("graphics:high", "/system/performance");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800764
Steven Thomas050b2c82017-03-06 11:45:16 -0800765#if ENABLE_BACKLIGHT_BRIGHTNESS
766 // TODO(hendrikw): This isn't required at the moment. It's possible that there
767 // is another method to access this when needed.
768 // Open the backlight brightness control sysfs node.
769 backlight_brightness_fd_ = LocalHandle(kBacklightBrightnessSysFile, O_RDWR);
770 ALOGW_IF(!backlight_brightness_fd_,
771 "HardwareComposer: Failed to open backlight brightness control: %s",
772 strerror(errno));
Corey Tabaka2251d822017-04-20 16:04:07 -0700773#endif // ENABLE_BACKLIGHT_BRIGHTNESS
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800774
Steven Thomas050b2c82017-03-06 11:45:16 -0800775 // Open the vsync event node for the primary display.
776 // TODO(eieio): Move this into a platform-specific class.
777 primary_display_vsync_event_fd_ =
778 LocalHandle(kPrimaryDisplayVSyncEventFile, O_RDONLY);
779 ALOGE_IF(!primary_display_vsync_event_fd_,
780 "HardwareComposer: Failed to open vsync event node for primary "
781 "display: %s",
782 strerror(errno));
783
784 // Open the wait pingpong status node for the primary display.
785 // TODO(eieio): Move this into a platform-specific class.
786 primary_display_wait_pp_fd_ =
787 LocalHandle(kPrimaryDisplayWaitPPEventFile, O_RDONLY);
788 ALOGW_IF(
789 !primary_display_wait_pp_fd_,
790 "HardwareComposer: Failed to open wait_pp node for primary display: %s",
791 strerror(errno));
792
793 // Create a timerfd based on CLOCK_MONOTINIC.
794 vsync_sleep_timer_fd_.Reset(timerfd_create(CLOCK_MONOTONIC, 0));
795 LOG_ALWAYS_FATAL_IF(
796 !vsync_sleep_timer_fd_,
797 "HardwareComposer: Failed to create vsync sleep timerfd: %s",
798 strerror(errno));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800799
800 const int64_t ns_per_frame = display_metrics_.vsync_period_ns;
801 const int64_t photon_offset_ns = GetPosePredictionTimeOffset(ns_per_frame);
802
803 // TODO(jbates) Query vblank time from device, when such an API is available.
804 // This value (6.3%) was measured on A00 in low persistence mode.
805 int64_t vblank_ns = ns_per_frame * 63 / 1000;
806 int64_t right_eye_photon_offset_ns = (ns_per_frame - vblank_ns) / 2;
807
808 // Check property for overriding right eye offset value.
809 right_eye_photon_offset_ns =
810 property_get_int64(kRightEyeOffsetProperty, right_eye_photon_offset_ns);
811
Steven Thomas050b2c82017-03-06 11:45:16 -0800812 bool was_running = false;
813
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800814 while (1) {
815 ATRACE_NAME("HardwareComposer::PostThread");
816
John Bates954796e2017-05-11 11:00:31 -0700817 // Check for updated config once per vsync.
818 UpdateConfigBuffer();
819
Corey Tabaka2251d822017-04-20 16:04:07 -0700820 while (post_thread_quiescent_) {
Steven Thomas050b2c82017-03-06 11:45:16 -0800821 std::unique_lock<std::mutex> lock(post_thread_mutex_);
Corey Tabaka2251d822017-04-20 16:04:07 -0700822 ALOGI("HardwareComposer::PostThread: Entering quiescent state.");
823
824 // Tear down resources.
825 OnPostThreadPaused();
826
827 was_running = false;
828 post_thread_resumed_ = false;
829 post_thread_ready_.notify_all();
830
831 if (post_thread_state_ & PostThreadState::Quit) {
832 ALOGI("HardwareComposer::PostThread: Quitting.");
833 return;
Steven Thomas282a5ed2017-02-07 18:07:01 -0800834 }
Corey Tabaka2251d822017-04-20 16:04:07 -0700835
836 post_thread_wait_.wait(lock, [this] { return !post_thread_quiescent_; });
837
838 post_thread_resumed_ = true;
839 post_thread_ready_.notify_all();
840
841 ALOGI("HardwareComposer::PostThread: Exiting quiescent state.");
Steven Thomas050b2c82017-03-06 11:45:16 -0800842 }
843
844 if (!was_running) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700845 // Setup resources.
Steven Thomas050b2c82017-03-06 11:45:16 -0800846 OnPostThreadResumed();
847 was_running = true;
Corey Tabaka2251d822017-04-20 16:04:07 -0700848
849 // Try to setup the scheduler policy if it failed during startup. Only
850 // attempt to do this on transitions from inactive to active to avoid
851 // spamming the system with RPCs and log messages.
852 if (!thread_policy_setup) {
853 thread_policy_setup =
854 SetThreadPolicy("graphics:high", "/system/performance");
855 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800856 }
857
858 int64_t vsync_timestamp = 0;
859 {
860 std::array<char, 128> buf;
861 snprintf(buf.data(), buf.size(), "wait_vsync|vsync=%d|",
862 vsync_count_ + 1);
863 ATRACE_NAME(buf.data());
864
Corey Tabaka2251d822017-04-20 16:04:07 -0700865 const int error = WaitForVSync(&vsync_timestamp);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800866 ALOGE_IF(
867 error < 0,
868 "HardwareComposer::PostThread: Failed to wait for vsync event: %s",
869 strerror(-error));
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800870 // Don't bother processing this frame if a pause was requested
Steven Thomas050b2c82017-03-06 11:45:16 -0800871 if (error == kPostThreadInterrupted)
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800872 continue;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800873 }
874
875 ++vsync_count_;
876
Corey Tabaka2251d822017-04-20 16:04:07 -0700877 const bool layer_config_changed = UpdateLayerConfig();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800878
Okan Arikan822b7102017-05-08 13:31:34 -0700879 // Publish the vsync event.
880 if (vsync_ring_) {
881 DvrVsync vsync;
882 vsync.vsync_count = vsync_count_;
883 vsync.vsync_timestamp_ns = vsync_timestamp;
884 vsync.vsync_left_eye_offset_ns = photon_offset_ns;
885 vsync.vsync_right_eye_offset_ns = right_eye_photon_offset_ns;
886 vsync.vsync_period_ns = ns_per_frame;
887
888 vsync_ring_->Publish(vsync);
889 }
890
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800891 // Signal all of the vsync clients. Because absolute time is used for the
892 // wakeup time below, this can take a little time if necessary.
893 if (vsync_callback_)
Corey Tabaka2251d822017-04-20 16:04:07 -0700894 vsync_callback_(HWC_DISPLAY_PRIMARY, vsync_timestamp,
895 /*frame_time_estimate*/ 0, vsync_count_);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800896
897 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700898 // Sleep until shortly before vsync.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800899 ATRACE_NAME("sleep");
900
Corey Tabaka2251d822017-04-20 16:04:07 -0700901 const int64_t display_time_est_ns = vsync_timestamp + ns_per_frame;
902 const int64_t now_ns = GetSystemClockNs();
John Bates954796e2017-05-11 11:00:31 -0700903 const int64_t sleep_time_ns = display_time_est_ns - now_ns -
904 post_thread_config_.frame_post_offset_ns;
905 const int64_t wakeup_time_ns =
906 display_time_est_ns - post_thread_config_.frame_post_offset_ns;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800907
908 ATRACE_INT64("sleep_time_ns", sleep_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800909 if (sleep_time_ns > 0) {
Corey Tabaka2251d822017-04-20 16:04:07 -0700910 int error = SleepUntil(wakeup_time_ns);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800911 ALOGE_IF(error < 0, "HardwareComposer::PostThread: Failed to sleep: %s",
912 strerror(-error));
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700913 if (error == kPostThreadInterrupted) {
914 if (layer_config_changed) {
915 // If the layer config changed we need to validateDisplay() even if
916 // we're going to drop the frame, to flush the Composer object's
917 // internal command buffer and apply our layer changes.
918 Validate(HWC_DISPLAY_PRIMARY);
919 }
Steven Thomas050b2c82017-03-06 11:45:16 -0800920 continue;
Steven Thomas0af4b9f2017-04-26 14:34:01 -0700921 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800922 }
923 }
924
Corey Tabaka2251d822017-04-20 16:04:07 -0700925 PostLayers();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800926 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800927}
928
Corey Tabaka2251d822017-04-20 16:04:07 -0700929// Checks for changes in the surface stack and updates the layer config to
930// accomodate the new stack.
Steven Thomas050b2c82017-03-06 11:45:16 -0800931bool HardwareComposer::UpdateLayerConfig() {
Corey Tabaka2251d822017-04-20 16:04:07 -0700932 std::vector<std::shared_ptr<DirectDisplaySurface>> surfaces;
Steven Thomas050b2c82017-03-06 11:45:16 -0800933 {
Corey Tabaka2251d822017-04-20 16:04:07 -0700934 std::unique_lock<std::mutex> lock(post_thread_mutex_);
935 if (pending_surfaces_.empty())
Steven Thomas050b2c82017-03-06 11:45:16 -0800936 return false;
Corey Tabaka2251d822017-04-20 16:04:07 -0700937
938 surfaces = std::move(pending_surfaces_);
Steven Thomas050b2c82017-03-06 11:45:16 -0800939 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800940
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800941 ATRACE_NAME("UpdateLayerConfig_HwLayers");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800942
Corey Tabaka2251d822017-04-20 16:04:07 -0700943 display_surfaces_.clear();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800944
Corey Tabaka2251d822017-04-20 16:04:07 -0700945 Layer* target_layer;
946 size_t layer_index;
947 for (layer_index = 0;
948 layer_index < std::min(surfaces.size(), kMaxHardwareLayers);
949 layer_index++) {
950 // The bottom layer is opaque, other layers blend.
951 HWC::BlendMode blending =
952 layer_index == 0 ? HWC::BlendMode::None : HWC::BlendMode::Coverage;
953 layers_[layer_index].Setup(surfaces[layer_index], blending,
954 display_transform_, HWC::Composition::Device,
955 layer_index);
956 display_surfaces_.push_back(surfaces[layer_index]);
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800957 }
958
Corey Tabaka2251d822017-04-20 16:04:07 -0700959 // Clear unused layers.
960 for (size_t i = layer_index; i < kMaxHardwareLayers; i++)
961 layers_[i].Reset();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800962
Corey Tabaka2251d822017-04-20 16:04:07 -0700963 active_layer_count_ = layer_index;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800964 ALOGD_IF(TRACE, "HardwareComposer::UpdateLayerConfig: %zd active layers",
965 active_layer_count_);
966
Corey Tabaka2251d822017-04-20 16:04:07 -0700967 // Any surfaces left over could not be assigned a hardware layer and will
968 // not be displayed.
969 ALOGW_IF(surfaces.size() != display_surfaces_.size(),
970 "HardwareComposer::UpdateLayerConfig: More surfaces than layers: "
971 "pending_surfaces=%zu display_surfaces=%zu",
972 surfaces.size(), display_surfaces_.size());
973
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800974 return true;
975}
976
Alex Vakulenkoa8a92782017-01-27 14:41:57 -0800977void HardwareComposer::SetVSyncCallback(VSyncCallback callback) {
978 vsync_callback_ = callback;
979}
980
981void HardwareComposer::HwcRefresh(hwc2_callback_data_t /*data*/,
982 hwc2_display_t /*display*/) {
983 // TODO(eieio): implement invalidate callbacks.
984}
985
986void HardwareComposer::HwcVSync(hwc2_callback_data_t /*data*/,
987 hwc2_display_t /*display*/,
988 int64_t /*timestamp*/) {
989 ATRACE_NAME(__PRETTY_FUNCTION__);
990 // Intentionally empty. HWC may require a callback to be set to enable vsync
991 // signals. We bypass this callback thread by monitoring the vsync event
992 // directly, but signals still need to be enabled.
993}
994
995void HardwareComposer::HwcHotplug(hwc2_callback_data_t /*callbackData*/,
996 hwc2_display_t /*display*/,
997 hwc2_connection_t /*connected*/) {
998 // TODO(eieio): implement display hotplug callbacks.
999}
1000
Steven Thomas3cfac282017-02-06 12:29:30 -08001001void HardwareComposer::OnHardwareComposerRefresh() {
1002 // TODO(steventhomas): Handle refresh.
1003}
1004
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001005void HardwareComposer::SetBacklightBrightness(int brightness) {
1006 if (backlight_brightness_fd_) {
1007 std::array<char, 32> text;
1008 const int length = snprintf(text.data(), text.size(), "%d", brightness);
1009 write(backlight_brightness_fd_.Get(), text.data(), length);
1010 }
1011}
1012
Corey Tabaka2251d822017-04-20 16:04:07 -07001013void Layer::InitializeGlobals(Hwc2::Composer* hwc2_hidl,
1014 const HWCDisplayMetrics* metrics) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001015 hwc2_hidl_ = hwc2_hidl;
1016 display_metrics_ = metrics;
1017}
1018
1019void Layer::Reset() {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001020 if (hwc2_hidl_ != nullptr && hardware_composer_layer_) {
1021 hwc2_hidl_->destroyLayer(HWC_DISPLAY_PRIMARY, hardware_composer_layer_);
1022 hardware_composer_layer_ = 0;
1023 }
1024
Corey Tabaka2251d822017-04-20 16:04:07 -07001025 z_order_ = 0;
1026 blending_ = HWC::BlendMode::None;
1027 transform_ = HWC::Transform::None;
1028 composition_type_ = HWC::Composition::Invalid;
1029 target_composition_type_ = composition_type_;
1030 source_ = EmptyVariant{};
1031 acquire_fence_.Close();
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001032 surface_rect_functions_applied_ = false;
1033}
1034
Corey Tabaka2251d822017-04-20 16:04:07 -07001035void Layer::Setup(const std::shared_ptr<DirectDisplaySurface>& surface,
1036 HWC::BlendMode blending, HWC::Transform transform,
1037 HWC::Composition composition_type, size_t z_order) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001038 Reset();
Corey Tabaka2251d822017-04-20 16:04:07 -07001039 z_order_ = z_order;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001040 blending_ = blending;
1041 transform_ = transform;
Corey Tabaka2251d822017-04-20 16:04:07 -07001042 composition_type_ = HWC::Composition::Invalid;
1043 target_composition_type_ = composition_type;
1044 source_ = SourceSurface{surface};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001045 CommonLayerSetup();
1046}
1047
1048void Layer::Setup(const std::shared_ptr<IonBuffer>& buffer,
Corey Tabaka2251d822017-04-20 16:04:07 -07001049 HWC::BlendMode blending, HWC::Transform transform,
1050 HWC::Composition composition_type, size_t z_order) {
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001051 Reset();
Corey Tabaka2251d822017-04-20 16:04:07 -07001052 z_order_ = z_order;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001053 blending_ = blending;
1054 transform_ = transform;
Corey Tabaka2251d822017-04-20 16:04:07 -07001055 composition_type_ = HWC::Composition::Invalid;
1056 target_composition_type_ = composition_type;
1057 source_ = SourceBuffer{buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001058 CommonLayerSetup();
1059}
1060
Corey Tabaka2251d822017-04-20 16:04:07 -07001061void Layer::UpdateBuffer(const std::shared_ptr<IonBuffer>& buffer) {
1062 if (source_.is<SourceBuffer>())
1063 std::get<SourceBuffer>(source_) = {buffer};
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001064}
1065
Corey Tabaka2251d822017-04-20 16:04:07 -07001066void Layer::SetBlending(HWC::BlendMode blending) { blending_ = blending; }
1067void Layer::SetZOrder(size_t z_order) { z_order_ = z_order; }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001068
1069IonBuffer* Layer::GetBuffer() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001070 struct Visitor {
1071 IonBuffer* operator()(SourceSurface& source) { return source.GetBuffer(); }
1072 IonBuffer* operator()(SourceBuffer& source) { return source.GetBuffer(); }
1073 IonBuffer* operator()(EmptyVariant) { return nullptr; }
1074 };
1075 return source_.Visit(Visitor{});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001076}
1077
1078void Layer::UpdateLayerSettings() {
1079 if (!IsLayerSetup()) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001080 ALOGE(
1081 "HardwareComposer::Layer::UpdateLayerSettings: Attempt to update "
1082 "unused Layer!");
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001083 return;
1084 }
1085
Corey Tabaka2251d822017-04-20 16:04:07 -07001086 HWC::Error error;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001087 hwc2_display_t display = HWC_DISPLAY_PRIMARY;
1088
Corey Tabaka2251d822017-04-20 16:04:07 -07001089 error = hwc2_hidl_->setLayerCompositionType(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001090 display, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001091 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1092 ALOGE_IF(
1093 error != HWC::Error::None,
1094 "Layer::UpdateLayerSettings: Error setting layer composition type: %s",
1095 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001096
Corey Tabaka2251d822017-04-20 16:04:07 -07001097 error = hwc2_hidl_->setLayerBlendMode(
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001098 display, hardware_composer_layer_,
Corey Tabaka2251d822017-04-20 16:04:07 -07001099 blending_.cast<Hwc2::IComposerClient::BlendMode>());
1100 ALOGE_IF(error != HWC::Error::None,
1101 "Layer::UpdateLayerSettings: Error setting layer blend mode: %s",
1102 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001103
Corey Tabaka2251d822017-04-20 16:04:07 -07001104 // TODO(eieio): Use surface attributes or some other mechanism to control
1105 // the layer display frame.
1106 error = hwc2_hidl_->setLayerDisplayFrame(
1107 display, hardware_composer_layer_,
1108 {0, 0, display_metrics_->width, display_metrics_->height});
1109 ALOGE_IF(error != HWC::Error::None,
1110 "Layer::UpdateLayerSettings: Error setting layer display frame: %s",
1111 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001112
Corey Tabaka2251d822017-04-20 16:04:07 -07001113 error = hwc2_hidl_->setLayerVisibleRegion(
1114 display, hardware_composer_layer_,
1115 {{0, 0, display_metrics_->width, display_metrics_->height}});
1116 ALOGE_IF(error != HWC::Error::None,
1117 "Layer::UpdateLayerSettings: Error setting layer visible region: %s",
1118 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001119
Corey Tabaka2251d822017-04-20 16:04:07 -07001120 error =
1121 hwc2_hidl_->setLayerPlaneAlpha(display, hardware_composer_layer_, 1.0f);
1122 ALOGE_IF(error != HWC::Error::None,
1123 "Layer::UpdateLayerSettings: Error setting layer plane alpha: %s",
1124 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001125
Corey Tabaka2251d822017-04-20 16:04:07 -07001126 error =
1127 hwc2_hidl_->setLayerZOrder(display, hardware_composer_layer_, z_order_);
1128 ALOGE_IF(error != HWC::Error::None,
1129 "Layer::UpdateLayerSettings: Error setting z_ order: %s",
1130 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001131}
1132
1133void Layer::CommonLayerSetup() {
Corey Tabaka2251d822017-04-20 16:04:07 -07001134 HWC::Error error =
1135 hwc2_hidl_->createLayer(HWC_DISPLAY_PRIMARY, &hardware_composer_layer_);
1136 ALOGE_IF(
1137 error != HWC::Error::None,
1138 "Layer::CommonLayerSetup: Failed to create layer on primary display: %s",
1139 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001140 UpdateLayerSettings();
1141}
1142
1143void Layer::Prepare() {
1144 int right, bottom;
Daniel Nicoara1f42e3a2017-04-10 13:27:32 -04001145 sp<GraphicBuffer> handle;
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001146
Corey Tabaka2251d822017-04-20 16:04:07 -07001147 // Acquire the next buffer according to the type of source.
1148 IfAnyOf<SourceSurface, SourceBuffer>::Call(&source_, [&](auto& source) {
1149 std::tie(right, bottom, handle, acquire_fence_) = source.Acquire();
1150 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001151
Corey Tabaka2251d822017-04-20 16:04:07 -07001152 // When a layer is first setup there may be some time before the first buffer
1153 // arrives. Setup the HWC layer as a solid color to stall for time until the
1154 // first buffer arrives. Once the first buffer arrives there will always be a
1155 // buffer for the frame even if it is old.
1156 if (!handle.get()) {
1157 if (composition_type_ == HWC::Composition::Invalid) {
1158 composition_type_ = HWC::Composition::SolidColor;
1159 hwc2_hidl_->setLayerCompositionType(
1160 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1161 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1162 Hwc2::IComposerClient::Color layer_color = {0, 0, 0, 0};
1163 hwc2_hidl_->setLayerColor(HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1164 layer_color);
1165 } else {
1166 // The composition type is already set. Nothing else to do until a
1167 // buffer arrives.
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001168 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001169 } else {
Corey Tabaka2251d822017-04-20 16:04:07 -07001170 if (composition_type_ != target_composition_type_) {
1171 composition_type_ = target_composition_type_;
1172 hwc2_hidl_->setLayerCompositionType(
1173 HWC_DISPLAY_PRIMARY, hardware_composer_layer_,
1174 composition_type_.cast<Hwc2::IComposerClient::Composition>());
1175 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001176
Corey Tabaka2251d822017-04-20 16:04:07 -07001177 HWC::Error error{HWC::Error::None};
1178 error = hwc2_hidl_->setLayerBuffer(HWC_DISPLAY_PRIMARY,
1179 hardware_composer_layer_, 0, handle,
1180 acquire_fence_.Get());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001181
Corey Tabaka2251d822017-04-20 16:04:07 -07001182 ALOGE_IF(error != HWC::Error::None,
1183 "Layer::Prepare: Error setting layer buffer: %s",
1184 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001185
Corey Tabaka2251d822017-04-20 16:04:07 -07001186 if (!surface_rect_functions_applied_) {
1187 const float float_right = right;
1188 const float float_bottom = bottom;
1189 error = hwc2_hidl_->setLayerSourceCrop(HWC_DISPLAY_PRIMARY,
1190 hardware_composer_layer_,
1191 {0, 0, float_right, float_bottom});
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001192
Corey Tabaka2251d822017-04-20 16:04:07 -07001193 ALOGE_IF(error != HWC::Error::None,
1194 "Layer::Prepare: Error setting layer source crop: %s",
1195 error.to_string().c_str());
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001196
Corey Tabaka2251d822017-04-20 16:04:07 -07001197 surface_rect_functions_applied_ = true;
1198 }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001199 }
1200}
1201
1202void Layer::Finish(int release_fence_fd) {
Corey Tabaka2251d822017-04-20 16:04:07 -07001203 IfAnyOf<SourceSurface, SourceBuffer>::Call(
1204 &source_, [release_fence_fd](auto& source) {
1205 source.Finish(LocalHandle(release_fence_fd));
1206 });
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001207}
1208
Corey Tabaka2251d822017-04-20 16:04:07 -07001209void Layer::Drop() { acquire_fence_.Close(); }
Alex Vakulenkoa8a92782017-01-27 14:41:57 -08001210
1211} // namespace dvr
1212} // namespace android