1 /*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
18 #define LOG_TAG "hwc-drm-display-compositor"
19
20 #include "DrmDisplayCompositor.h"
21
22 #include <drm/drm_mode.h>
23 #include <log/log.h>
24 #include <pthread.h>
25 #include <sched.h>
26 #include <stdlib.h>
27 #include <sync/sync.h>
28 #include <time.h>
29 #include <utils/Trace.h>
30
31 #include <array>
32 #include <sstream>
33 #include <vector>
34
35 #include "drm/DrmCrtc.h"
36 #include "drm/DrmDevice.h"
37 #include "drm/DrmPlane.h"
38 #include "utils/autolock.h"
39
40 static const uint32_t kWaitWritebackFence = 100; // ms
41
42 namespace android {
43
operator <<(std::ostream & str,FlatteningState state)44 std::ostream &operator<<(std::ostream &str, FlatteningState state) {
45 std::array<const char *, 6> flattenting_state_str = {
46 "None", "Not needed", "SF Requested", "Squashed by GPU",
47 "Serial", "Concurrent",
48 };
49
50 return str << flattenting_state_str[static_cast<int>(state)];
51 }
52
53 class CompositorVsyncCallback : public VsyncCallback {
54 public:
CompositorVsyncCallback(DrmDisplayCompositor * compositor)55 CompositorVsyncCallback(DrmDisplayCompositor *compositor)
56 : compositor_(compositor) {
57 }
58
Callback(int display,int64_t timestamp)59 void Callback(int display, int64_t timestamp) {
60 compositor_->Vsync(display, timestamp);
61 }
62
63 private:
64 DrmDisplayCompositor *compositor_;
65 };
66
DrmDisplayCompositor()67 DrmDisplayCompositor::DrmDisplayCompositor()
68 : resource_manager_(NULL),
69 display_(-1),
70 initialized_(false),
71 active_(false),
72 use_hw_overlays_(true),
73 dump_frames_composited_(0),
74 dump_last_timestamp_ns_(0),
75 flatten_countdown_(FLATTEN_COUNTDOWN_INIT),
76 writeback_fence_(-1),
77 flattening_state_(FlatteningState::kNone),
78 frames_flattened_(0) {
79 struct timespec ts;
80 if (clock_gettime(CLOCK_MONOTONIC, &ts))
81 return;
82 dump_last_timestamp_ns_ = ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
83 }
84
~DrmDisplayCompositor()85 DrmDisplayCompositor::~DrmDisplayCompositor() {
86 if (!initialized_)
87 return;
88
89 vsync_worker_.Exit();
90 int ret = pthread_mutex_lock(&lock_);
91 if (ret)
92 ALOGE("Failed to acquire compositor lock %d", ret);
93 DrmDevice *drm = resource_manager_->GetDrmDevice(display_);
94 if (mode_.blob_id)
95 drm->DestroyPropertyBlob(mode_.blob_id);
96 if (mode_.old_blob_id)
97 drm->DestroyPropertyBlob(mode_.old_blob_id);
98
99 active_composition_.reset();
100
101 ret = pthread_mutex_unlock(&lock_);
102 if (ret)
103 ALOGE("Failed to acquire compositor lock %d", ret);
104
105 pthread_mutex_destroy(&lock_);
106 }
107
Init(ResourceManager * resource_manager,int display)108 int DrmDisplayCompositor::Init(ResourceManager *resource_manager, int display) {
109 resource_manager_ = resource_manager;
110 display_ = display;
111 DrmDevice *drm = resource_manager_->GetDrmDevice(display);
112 if (!drm) {
113 ALOGE("Could not find drmdevice for display");
114 return -EINVAL;
115 }
116 int ret = pthread_mutex_init(&lock_, NULL);
117 if (ret) {
118 ALOGE("Failed to initialize drm compositor lock %d\n", ret);
119 return ret;
120 }
121 planner_ = Planner::CreateInstance(drm);
122
123 vsync_worker_.Init(drm, display_);
124 auto callback = std::make_shared<CompositorVsyncCallback>(this);
125 vsync_worker_.RegisterCallback(callback);
126
127 initialized_ = true;
128 return 0;
129 }
130
CreateComposition() const131 std::unique_ptr<DrmDisplayComposition> DrmDisplayCompositor::CreateComposition()
132 const {
133 return std::unique_ptr<DrmDisplayComposition>(new DrmDisplayComposition());
134 }
135
136 std::unique_ptr<DrmDisplayComposition>
CreateInitializedComposition() const137 DrmDisplayCompositor::CreateInitializedComposition() const {
138 DrmDevice *drm = resource_manager_->GetDrmDevice(display_);
139 DrmCrtc *crtc = drm->GetCrtcForDisplay(display_);
140 if (!crtc) {
141 ALOGE("Failed to find crtc for display = %d", display_);
142 return std::unique_ptr<DrmDisplayComposition>();
143 }
144 std::unique_ptr<DrmDisplayComposition> comp = CreateComposition();
145 std::shared_ptr<Importer> importer = resource_manager_->GetImporter(display_);
146 if (!importer) {
147 ALOGE("Failed to find resources for display = %d", display_);
148 return std::unique_ptr<DrmDisplayComposition>();
149 }
150 int ret = comp->Init(drm, crtc, importer.get(), planner_.get(), 0);
151 if (ret) {
152 ALOGE("Failed to init composition for display = %d", display_);
153 return std::unique_ptr<DrmDisplayComposition>();
154 }
155 return comp;
156 }
157
GetFlatteningState() const158 FlatteningState DrmDisplayCompositor::GetFlatteningState() const {
159 return flattening_state_;
160 }
161
GetFlattenedFramesCount() const162 uint32_t DrmDisplayCompositor::GetFlattenedFramesCount() const {
163 return frames_flattened_;
164 }
165
ShouldFlattenOnClient() const166 bool DrmDisplayCompositor::ShouldFlattenOnClient() const {
167 return flattening_state_ == FlatteningState::kClientRequested ||
168 flattening_state_ == FlatteningState::kClientDone;
169 }
170
171 std::tuple<uint32_t, uint32_t, int>
GetActiveModeResolution()172 DrmDisplayCompositor::GetActiveModeResolution() {
173 DrmDevice *drm = resource_manager_->GetDrmDevice(display_);
174 DrmConnector *connector = drm->GetConnectorForDisplay(display_);
175 if (connector == NULL) {
176 ALOGE("Failed to determine display mode: no connector for display %d",
177 display_);
178 return std::make_tuple(0, 0, -ENODEV);
179 }
180
181 const DrmMode &mode = connector->active_mode();
182 return std::make_tuple(mode.h_display(), mode.v_display(), 0);
183 }
184
DisablePlanes(DrmDisplayComposition * display_comp)185 int DrmDisplayCompositor::DisablePlanes(DrmDisplayComposition *display_comp) {
186 drmModeAtomicReqPtr pset = drmModeAtomicAlloc();
187 if (!pset) {
188 ALOGE("Failed to allocate property set");
189 return -ENOMEM;
190 }
191
192 int ret;
193 std::vector<DrmCompositionPlane> &comp_planes = display_comp
194 ->composition_planes();
195 for (DrmCompositionPlane &comp_plane : comp_planes) {
196 DrmPlane *plane = comp_plane.plane();
197 ret = drmModeAtomicAddProperty(pset, plane->id(),
198 plane->crtc_property().id(), 0) < 0 ||
199 drmModeAtomicAddProperty(pset, plane->id(), plane->fb_property().id(),
200 0) < 0;
201 if (ret) {
202 ALOGE("Failed to add plane %d disable to pset", plane->id());
203 drmModeAtomicFree(pset);
204 return ret;
205 }
206 }
207 DrmDevice *drm = resource_manager_->GetDrmDevice(display_);
208 ret = drmModeAtomicCommit(drm->fd(), pset, 0, drm);
209 if (ret) {
210 ALOGE("Failed to commit pset ret=%d\n", ret);
211 drmModeAtomicFree(pset);
212 return ret;
213 }
214
215 drmModeAtomicFree(pset);
216 return 0;
217 }
218
SetupWritebackCommit(drmModeAtomicReqPtr pset,uint32_t crtc_id,DrmConnector * writeback_conn,DrmHwcBuffer * writeback_buffer)219 int DrmDisplayCompositor::SetupWritebackCommit(drmModeAtomicReqPtr pset,
220 uint32_t crtc_id,
221 DrmConnector *writeback_conn,
222 DrmHwcBuffer *writeback_buffer) {
223 int ret = 0;
224 if (writeback_conn->writeback_fb_id().id() == 0 ||
225 writeback_conn->writeback_out_fence().id() == 0) {
226 ALOGE("Writeback properties don't exit");
227 return -EINVAL;
228 }
229 if ((*writeback_buffer)->fb_id == 0) {
230 ALOGE("Invalid writeback buffer");
231 return -EINVAL;
232 }
233 ret = drmModeAtomicAddProperty(pset, writeback_conn->id(),
234 writeback_conn->writeback_fb_id().id(),
235 (*writeback_buffer)->fb_id);
236 if (ret < 0) {
237 ALOGE("Failed to add writeback_fb_id");
238 return ret;
239 }
240 ret = drmModeAtomicAddProperty(pset, writeback_conn->id(),
241 writeback_conn->writeback_out_fence().id(),
242 (uint64_t)&writeback_fence_);
243 if (ret < 0) {
244 ALOGE("Failed to add writeback_out_fence");
245 return ret;
246 }
247
248 ret = drmModeAtomicAddProperty(pset, writeback_conn->id(),
249 writeback_conn->crtc_id_property().id(),
250 crtc_id);
251 if (ret < 0) {
252 ALOGE("Failed to attach writeback");
253 return ret;
254 }
255 return 0;
256 }
257
CommitFrame(DrmDisplayComposition * display_comp,bool test_only,DrmConnector * writeback_conn,DrmHwcBuffer * writeback_buffer)258 int DrmDisplayCompositor::CommitFrame(DrmDisplayComposition *display_comp,
259 bool test_only,
260 DrmConnector *writeback_conn,
261 DrmHwcBuffer *writeback_buffer) {
262 ATRACE_CALL();
263
264 int ret = 0;
265
266 std::vector<DrmHwcLayer> &layers = display_comp->layers();
267 std::vector<DrmCompositionPlane> &comp_planes = display_comp
268 ->composition_planes();
269 DrmDevice *drm = resource_manager_->GetDrmDevice(display_);
270 uint64_t out_fences[drm->crtcs().size()];
271
272 DrmConnector *connector = drm->GetConnectorForDisplay(display_);
273 if (!connector) {
274 ALOGE("Could not locate connector for display %d", display_);
275 return -ENODEV;
276 }
277 DrmCrtc *crtc = drm->GetCrtcForDisplay(display_);
278 if (!crtc) {
279 ALOGE("Could not locate crtc for display %d", display_);
280 return -ENODEV;
281 }
282
283 drmModeAtomicReqPtr pset = drmModeAtomicAlloc();
284 if (!pset) {
285 ALOGE("Failed to allocate property set");
286 return -ENOMEM;
287 }
288
289 if (writeback_buffer != NULL) {
290 if (writeback_conn == NULL) {
291 ALOGE("Invalid arguments requested writeback without writeback conn");
292 return -EINVAL;
293 }
294 ret = SetupWritebackCommit(pset, crtc->id(), writeback_conn,
295 writeback_buffer);
296 if (ret < 0) {
297 ALOGE("Failed to Setup Writeback Commit ret = %d", ret);
298 return ret;
299 }
300 }
301 if (crtc->out_fence_ptr_property().id() != 0) {
302 ret = drmModeAtomicAddProperty(pset, crtc->id(),
303 crtc->out_fence_ptr_property().id(),
304 (uint64_t)&out_fences[crtc->pipe()]);
305 if (ret < 0) {
306 ALOGE("Failed to add OUT_FENCE_PTR property to pset: %d", ret);
307 drmModeAtomicFree(pset);
308 return ret;
309 }
310 }
311
312 if (mode_.needs_modeset) {
313 ret = drmModeAtomicAddProperty(pset, crtc->id(),
314 crtc->active_property().id(), 1);
315 if (ret < 0) {
316 ALOGE("Failed to add crtc active to pset\n");
317 drmModeAtomicFree(pset);
318 return ret;
319 }
320
321 ret = drmModeAtomicAddProperty(pset, crtc->id(), crtc->mode_property().id(),
322 mode_.blob_id) < 0 ||
323 drmModeAtomicAddProperty(pset, connector->id(),
324 connector->crtc_id_property().id(),
325 crtc->id()) < 0;
326 if (ret) {
327 ALOGE("Failed to add blob %d to pset", mode_.blob_id);
328 drmModeAtomicFree(pset);
329 return ret;
330 }
331 }
332
333 for (DrmCompositionPlane &comp_plane : comp_planes) {
334 DrmPlane *plane = comp_plane.plane();
335 DrmCrtc *crtc = comp_plane.crtc();
336 std::vector<size_t> &source_layers = comp_plane.source_layers();
337
338 int fb_id = -1;
339 int fence_fd = -1;
340 hwc_rect_t display_frame;
341 hwc_frect_t source_crop;
342 uint64_t rotation = 0;
343 uint64_t alpha = 0xFFFF;
344 uint64_t blend;
345
346 if (comp_plane.type() != DrmCompositionPlane::Type::kDisable) {
347 if (source_layers.size() > 1) {
348 ALOGE("Can't handle more than one source layer sz=%zu type=%d",
349 source_layers.size(), comp_plane.type());
350 continue;
351 }
352
353 if (source_layers.empty() || source_layers.front() >= layers.size()) {
354 ALOGE("Source layer index %zu out of bounds %zu type=%d",
355 source_layers.front(), layers.size(), comp_plane.type());
356 break;
357 }
358 DrmHwcLayer &layer = layers[source_layers.front()];
359 if (!layer.buffer) {
360 ALOGE("Expected a valid framebuffer for pset");
361 break;
362 }
363 fb_id = layer.buffer->fb_id;
364 fence_fd = layer.acquire_fence.get();
365 display_frame = layer.display_frame;
366 source_crop = layer.source_crop;
367 alpha = layer.alpha;
368
369 if (plane->blend_property().id()) {
370 switch (layer.blending) {
371 case DrmHwcBlending::kPreMult:
372 std::tie(blend, ret) = plane->blend_property().GetEnumValueWithName(
373 "Pre-multiplied");
374 break;
375 case DrmHwcBlending::kCoverage:
376 std::tie(blend, ret) = plane->blend_property().GetEnumValueWithName(
377 "Coverage");
378 break;
379 case DrmHwcBlending::kNone:
380 default:
381 std::tie(blend, ret) = plane->blend_property().GetEnumValueWithName(
382 "None");
383 break;
384 }
385 }
386
387 if (plane->zpos_property().id() &&
388 !plane->zpos_property().is_immutable()) {
389 uint64_t min_zpos = 0;
390
391 // Ignore ret and use min_zpos as 0 by default
392 std::tie(std::ignore, min_zpos) = plane->zpos_property().range_min();
393
394 ret = drmModeAtomicAddProperty(pset, plane->id(),
395 plane->zpos_property().id(),
396 source_layers.front() + min_zpos) < 0;
397 if (ret) {
398 ALOGE("Failed to add zpos property %d to plane %d",
399 plane->zpos_property().id(), plane->id());
400 break;
401 }
402 }
403
404 rotation = 0;
405 if (layer.transform & DrmHwcTransform::kFlipH)
406 rotation |= DRM_MODE_REFLECT_X;
407 if (layer.transform & DrmHwcTransform::kFlipV)
408 rotation |= DRM_MODE_REFLECT_Y;
409 if (layer.transform & DrmHwcTransform::kRotate90)
410 rotation |= DRM_MODE_ROTATE_90;
411 else if (layer.transform & DrmHwcTransform::kRotate180)
412 rotation |= DRM_MODE_ROTATE_180;
413 else if (layer.transform & DrmHwcTransform::kRotate270)
414 rotation |= DRM_MODE_ROTATE_270;
415 else
416 rotation |= DRM_MODE_ROTATE_0;
417
418 if (fence_fd >= 0) {
419 int prop_id = plane->in_fence_fd_property().id();
420 if (prop_id == 0) {
421 ALOGE("Failed to get IN_FENCE_FD property id");
422 break;
423 }
424 ret = drmModeAtomicAddProperty(pset, plane->id(), prop_id, fence_fd);
425 if (ret < 0) {
426 ALOGE("Failed to add IN_FENCE_FD property to pset: %d", ret);
427 break;
428 }
429 }
430 }
431
432 // Disable the plane if there's no framebuffer
433 if (fb_id < 0) {
434 ret = drmModeAtomicAddProperty(pset, plane->id(),
435 plane->crtc_property().id(), 0) < 0 ||
436 drmModeAtomicAddProperty(pset, plane->id(),
437 plane->fb_property().id(), 0) < 0;
438 if (ret) {
439 ALOGE("Failed to add plane %d disable to pset", plane->id());
440 break;
441 }
442 continue;
443 }
444
445 ret = drmModeAtomicAddProperty(pset, plane->id(),
446 plane->crtc_property().id(), crtc->id()) < 0;
447 ret |= drmModeAtomicAddProperty(pset, plane->id(),
448 plane->fb_property().id(), fb_id) < 0;
449 ret |= drmModeAtomicAddProperty(pset, plane->id(),
450 plane->crtc_x_property().id(),
451 display_frame.left) < 0;
452 ret |= drmModeAtomicAddProperty(pset, plane->id(),
453 plane->crtc_y_property().id(),
454 display_frame.top) < 0;
455 ret |= drmModeAtomicAddProperty(pset, plane->id(),
456 plane->crtc_w_property().id(),
457 display_frame.right - display_frame.left) <
458 0;
459 ret |= drmModeAtomicAddProperty(pset, plane->id(),
460 plane->crtc_h_property().id(),
461 display_frame.bottom - display_frame.top) <
462 0;
463 ret |= drmModeAtomicAddProperty(pset, plane->id(),
464 plane->src_x_property().id(),
465 (int)(source_crop.left) << 16) < 0;
466 ret |= drmModeAtomicAddProperty(pset, plane->id(),
467 plane->src_y_property().id(),
468 (int)(source_crop.top) << 16) < 0;
469 ret |= drmModeAtomicAddProperty(pset, plane->id(),
470 plane->src_w_property().id(),
471 (int)(source_crop.right - source_crop.left)
472 << 16) < 0;
473 ret |= drmModeAtomicAddProperty(pset, plane->id(),
474 plane->src_h_property().id(),
475 (int)(source_crop.bottom - source_crop.top)
476 << 16) < 0;
477 if (ret) {
478 ALOGE("Failed to add plane %d to set", plane->id());
479 break;
480 }
481
482 if (plane->rotation_property().id()) {
483 ret = drmModeAtomicAddProperty(pset, plane->id(),
484 plane->rotation_property().id(),
485 rotation) < 0;
486 if (ret) {
487 ALOGE("Failed to add rotation property %d to plane %d",
488 plane->rotation_property().id(), plane->id());
489 break;
490 }
491 }
492
493 if (plane->alpha_property().id()) {
494 ret = drmModeAtomicAddProperty(pset, plane->id(),
495 plane->alpha_property().id(), alpha) < 0;
496 if (ret) {
497 ALOGE("Failed to add alpha property %d to plane %d",
498 plane->alpha_property().id(), plane->id());
499 break;
500 }
501 }
502
503 if (plane->blend_property().id()) {
504 ret = drmModeAtomicAddProperty(pset, plane->id(),
505 plane->blend_property().id(), blend) < 0;
506 if (ret) {
507 ALOGE("Failed to add pixel blend mode property %d to plane %d",
508 plane->blend_property().id(), plane->id());
509 break;
510 }
511 }
512 }
513
514 if (!ret) {
515 uint32_t flags = DRM_MODE_ATOMIC_ALLOW_MODESET;
516 if (test_only)
517 flags |= DRM_MODE_ATOMIC_TEST_ONLY;
518
519 ret = drmModeAtomicCommit(drm->fd(), pset, flags, drm);
520 if (ret) {
521 if (!test_only)
522 ALOGE("Failed to commit pset ret=%d\n", ret);
523 drmModeAtomicFree(pset);
524 return ret;
525 }
526 }
527 if (pset)
528 drmModeAtomicFree(pset);
529
530 if (!test_only && mode_.needs_modeset) {
531 ret = drm->DestroyPropertyBlob(mode_.old_blob_id);
532 if (ret) {
533 ALOGE("Failed to destroy old mode property blob %" PRIu32 "/%d",
534 mode_.old_blob_id, ret);
535 return ret;
536 }
537
538 /* TODO: Add dpms to the pset when the kernel supports it */
539 ret = ApplyDpms(display_comp);
540 if (ret) {
541 ALOGE("Failed to apply DPMS after modeset %d\n", ret);
542 return ret;
543 }
544
545 connector->set_active_mode(mode_.mode);
546 mode_.old_blob_id = mode_.blob_id;
547 mode_.blob_id = 0;
548 mode_.needs_modeset = false;
549 }
550
551 if (crtc->out_fence_ptr_property().id()) {
552 display_comp->set_out_fence((int)out_fences[crtc->pipe()]);
553 }
554
555 return ret;
556 }
557
ApplyDpms(DrmDisplayComposition * display_comp)558 int DrmDisplayCompositor::ApplyDpms(DrmDisplayComposition *display_comp) {
559 DrmDevice *drm = resource_manager_->GetDrmDevice(display_);
560 DrmConnector *conn = drm->GetConnectorForDisplay(display_);
561 if (!conn) {
562 ALOGE("Failed to get DrmConnector for display %d", display_);
563 return -ENODEV;
564 }
565
566 const DrmProperty &prop = conn->dpms_property();
567 int ret = drmModeConnectorSetProperty(drm->fd(), conn->id(), prop.id(),
568 display_comp->dpms_mode());
569 if (ret) {
570 ALOGE("Failed to set DPMS property for connector %d", conn->id());
571 return ret;
572 }
573 return 0;
574 }
575
CreateModeBlob(const DrmMode & mode)576 std::tuple<int, uint32_t> DrmDisplayCompositor::CreateModeBlob(
577 const DrmMode &mode) {
578 struct drm_mode_modeinfo drm_mode;
579 memset(&drm_mode, 0, sizeof(drm_mode));
580 mode.ToDrmModeModeInfo(&drm_mode);
581
582 uint32_t id = 0;
583 DrmDevice *drm = resource_manager_->GetDrmDevice(display_);
584 int ret = drm->CreatePropertyBlob(&drm_mode, sizeof(struct drm_mode_modeinfo),
585 &id);
586 if (ret) {
587 ALOGE("Failed to create mode property blob %d", ret);
588 return std::make_tuple(ret, 0);
589 }
590 ALOGE("Create blob_id %" PRIu32 "\n", id);
591 return std::make_tuple(ret, id);
592 }
593
ClearDisplay()594 void DrmDisplayCompositor::ClearDisplay() {
595 if (!active_composition_)
596 return;
597
598 if (DisablePlanes(active_composition_.get()))
599 return;
600
601 active_composition_.reset(NULL);
602 vsync_worker_.VSyncControl(false);
603 }
604
ApplyFrame(std::unique_ptr<DrmDisplayComposition> composition,int status,bool writeback)605 void DrmDisplayCompositor::ApplyFrame(
606 std::unique_ptr<DrmDisplayComposition> composition, int status,
607 bool writeback) {
608 AutoLock lock(&lock_, __func__);
609 if (lock.Lock())
610 return;
611 int ret = status;
612
613 if (!ret) {
614 if (writeback && !CountdownExpired()) {
615 ALOGE("Abort playing back scene");
616 return;
617 }
618 ret = CommitFrame(composition.get(), false);
619 }
620
621 if (ret) {
622 ALOGE("Composite failed for display %d", display_);
623 // Disable the hw used by the last active composition. This allows us to
624 // signal the release fences from that composition to avoid hanging.
625 ClearDisplay();
626 return;
627 }
628 ++dump_frames_composited_;
629
630 active_composition_.swap(composition);
631
632 flatten_countdown_ = FLATTEN_COUNTDOWN_INIT;
633 if (flattening_state_ != FlatteningState::kClientRequested) {
634 SetFlattening(FlatteningState::kNone);
635 } else {
636 SetFlattening(FlatteningState::kClientDone);
637 }
638 vsync_worker_.VSyncControl(!writeback);
639 }
640
ApplyComposition(std::unique_ptr<DrmDisplayComposition> composition)641 int DrmDisplayCompositor::ApplyComposition(
642 std::unique_ptr<DrmDisplayComposition> composition) {
643 int ret = 0;
644 switch (composition->type()) {
645 case DRM_COMPOSITION_TYPE_FRAME:
646 if (composition->geometry_changed()) {
647 // Send the composition to the kernel to ensure we can commit it. This
648 // is just a test, it won't actually commit the frame.
649 ret = CommitFrame(composition.get(), true);
650 if (ret) {
651 ALOGE("Commit test failed for display %d, FIXME", display_);
652 return ret;
653 }
654 }
655
656 ApplyFrame(std::move(composition), ret);
657 break;
658 case DRM_COMPOSITION_TYPE_DPMS:
659 active_ = (composition->dpms_mode() == DRM_MODE_DPMS_ON);
660 ret = ApplyDpms(composition.get());
661 if (ret)
662 ALOGE("Failed to apply dpms for display %d", display_);
663 return ret;
664 case DRM_COMPOSITION_TYPE_MODESET:
665 mode_.mode = composition->display_mode();
666 if (mode_.blob_id)
667 resource_manager_->GetDrmDevice(display_)->DestroyPropertyBlob(
668 mode_.blob_id);
669 std::tie(ret, mode_.blob_id) = CreateModeBlob(mode_.mode);
670 if (ret) {
671 ALOGE("Failed to create mode blob for display %d", display_);
672 return ret;
673 }
674 mode_.needs_modeset = true;
675 return 0;
676 default:
677 ALOGE("Unknown composition type %d", composition->type());
678 return -EINVAL;
679 }
680
681 return ret;
682 }
683
TestComposition(DrmDisplayComposition * composition)684 int DrmDisplayCompositor::TestComposition(DrmDisplayComposition *composition) {
685 return CommitFrame(composition, true);
686 }
687
688 // Flatten a scene on the display by using a writeback connector
689 // and returns the composition result as a DrmHwcLayer.
FlattenOnDisplay(std::unique_ptr<DrmDisplayComposition> & src,DrmConnector * writeback_conn,DrmMode & src_mode,DrmHwcLayer * writeback_layer)690 int DrmDisplayCompositor::FlattenOnDisplay(
691 std::unique_ptr<DrmDisplayComposition> &src, DrmConnector *writeback_conn,
692 DrmMode &src_mode, DrmHwcLayer *writeback_layer) {
693 int ret = 0;
694 DrmDevice *drm = resource_manager_->GetDrmDevice(display_);
695 ret = writeback_conn->UpdateModes();
696 if (ret) {
697 ALOGE("Failed to update modes %d", ret);
698 return ret;
699 }
700 for (const DrmMode &mode : writeback_conn->modes()) {
701 if (mode.h_display() == src_mode.h_display() &&
702 mode.v_display() == src_mode.v_display()) {
703 mode_.mode = mode;
704 if (mode_.blob_id)
705 drm->DestroyPropertyBlob(mode_.blob_id);
706 std::tie(ret, mode_.blob_id) = CreateModeBlob(mode_.mode);
707 if (ret) {
708 ALOGE("Failed to create mode blob for display %d", display_);
709 return ret;
710 }
711 mode_.needs_modeset = true;
712 break;
713 }
714 }
715 if (mode_.blob_id <= 0) {
716 ALOGE("Failed to find similar mode");
717 return -EINVAL;
718 }
719
720 DrmCrtc *crtc = drm->GetCrtcForDisplay(display_);
721 if (!crtc) {
722 ALOGE("Failed to find crtc for display %d", display_);
723 return -EINVAL;
724 }
725 // TODO what happens if planes could go to both CRTCs, I don't think it's
726 // handled anywhere
727 std::vector<DrmPlane *> primary_planes;
728 std::vector<DrmPlane *> overlay_planes;
729 for (auto &plane : drm->planes()) {
730 if (!plane->GetCrtcSupported(*crtc))
731 continue;
732 if (plane->type() == DRM_PLANE_TYPE_PRIMARY)
733 primary_planes.push_back(plane.get());
734 else if (plane->type() == DRM_PLANE_TYPE_OVERLAY)
735 overlay_planes.push_back(plane.get());
736 }
737
738 ret = src->Plan(&primary_planes, &overlay_planes);
739 if (ret) {
740 ALOGE("Failed to plan the composition ret = %d", ret);
741 return ret;
742 }
743
744 // Disable the planes we're not using
745 for (auto i = primary_planes.begin(); i != primary_planes.end();) {
746 src->AddPlaneDisable(*i);
747 i = primary_planes.erase(i);
748 }
749 for (auto i = overlay_planes.begin(); i != overlay_planes.end();) {
750 src->AddPlaneDisable(*i);
751 i = overlay_planes.erase(i);
752 }
753
754 AutoLock lock(&lock_, __func__);
755 ret = lock.Lock();
756 if (ret)
757 return ret;
758 DrmFramebuffer *writeback_fb = &framebuffers_[framebuffer_index_];
759 framebuffer_index_ = (framebuffer_index_ + 1) % DRM_DISPLAY_BUFFERS;
760 if (!writeback_fb->Allocate(mode_.mode.h_display(), mode_.mode.v_display())) {
761 ALOGE("Failed to allocate writeback buffer");
762 return -ENOMEM;
763 }
764 DrmHwcBuffer *writeback_buffer = &writeback_layer->buffer;
765 writeback_layer->sf_handle = writeback_fb->buffer()->handle;
766 ret = writeback_layer->ImportBuffer(
767 resource_manager_->GetImporter(display_).get());
768 if (ret) {
769 ALOGE("Failed to import writeback buffer");
770 return ret;
771 }
772
773 ret = CommitFrame(src.get(), true, writeback_conn, writeback_buffer);
774 if (ret) {
775 ALOGE("Atomic check failed");
776 return ret;
777 }
778 ret = CommitFrame(src.get(), false, writeback_conn, writeback_buffer);
779 if (ret) {
780 ALOGE("Atomic commit failed");
781 return ret;
782 }
783
784 ret = sync_wait(writeback_fence_, kWaitWritebackFence);
785 writeback_layer->acquire_fence.Set(writeback_fence_);
786 writeback_fence_ = -1;
787 if (ret) {
788 ALOGE("Failed to wait on writeback fence");
789 return ret;
790 }
791 return 0;
792 }
793
SetFlattening(FlatteningState new_state)794 void DrmDisplayCompositor::SetFlattening(FlatteningState new_state) {
795 if (flattening_state_ != new_state) {
796 switch (flattening_state_) {
797 case FlatteningState::kClientDone:
798 case FlatteningState::kConcurrent:
799 case FlatteningState::kSerial:
800 ++frames_flattened_;
801 break;
802 case FlatteningState::kClientRequested:
803 case FlatteningState::kNone:
804 case FlatteningState::kNotNeeded:
805 break;
806 }
807 }
808 flattening_state_ = new_state;
809 }
810
IsFlatteningNeeded() const811 bool DrmDisplayCompositor::IsFlatteningNeeded() const {
812 return CountdownExpired() && active_composition_->layers().size() >= 2;
813 }
814
FlattenOnClient()815 int DrmDisplayCompositor::FlattenOnClient() {
816 const std::lock_guard<std::mutex> lock(refresh_callback_lock);
817
818 if (refresh_callback_hook_ && refresh_callback_data_) {
819 {
820 AutoLock lock(&lock_, __func__);
821 if (!IsFlatteningNeeded()) {
822 if (flattening_state_ != FlatteningState::kClientDone) {
823 ALOGV("Flattening is not needed");
824 SetFlattening(FlatteningState::kNotNeeded);
825 }
826 return -EALREADY;
827 }
828 }
829
830 ALOGV(
831 "No writeback connector available, "
832 "falling back to client composition");
833 SetFlattening(FlatteningState::kClientRequested);
834 refresh_callback_hook_(refresh_callback_data_, display_);
835 return 0;
836 } else {
837 ALOGV("No writeback connector available");
838 return -EINVAL;
839 }
840 }
841
842 // Flatten a scene by enabling the writeback connector attached
843 // to the same CRTC as the one driving the display.
FlattenSerial(DrmConnector * writeback_conn)844 int DrmDisplayCompositor::FlattenSerial(DrmConnector *writeback_conn) {
845 ALOGV("FlattenSerial by enabling writeback connector to the same crtc");
846 // Flattened composition with only one layer that is obtained
847 // using the writeback connector
848 std::unique_ptr<DrmDisplayComposition>
849 writeback_comp = CreateInitializedComposition();
850 if (!writeback_comp)
851 return -EINVAL;
852
853 AutoLock lock(&lock_, __func__);
854 int ret = lock.Lock();
855 if (ret)
856 return ret;
857 if (!IsFlatteningNeeded()) {
858 ALOGV("Flattening is not needed");
859 SetFlattening(FlatteningState::kNotNeeded);
860 return -EALREADY;
861 }
862
863 DrmFramebuffer *writeback_fb = &framebuffers_[framebuffer_index_];
864 framebuffer_index_ = (framebuffer_index_ + 1) % DRM_DISPLAY_BUFFERS;
865 lock.Unlock();
866
867 if (!writeback_fb->Allocate(mode_.mode.h_display(), mode_.mode.v_display())) {
868 ALOGE("Failed to allocate writeback buffer");
869 return -ENOMEM;
870 }
871 writeback_comp->layers().emplace_back();
872
873 DrmHwcLayer &writeback_layer = writeback_comp->layers().back();
874 writeback_layer.sf_handle = writeback_fb->buffer()->handle;
875 writeback_layer.source_crop = {0, 0, (float)mode_.mode.h_display(),
876 (float)mode_.mode.v_display()};
877 writeback_layer.display_frame = {0, 0, (int)mode_.mode.h_display(),
878 (int)mode_.mode.v_display()};
879 ret = writeback_layer.ImportBuffer(
880 resource_manager_->GetImporter(display_).get());
881 if (ret || writeback_comp->layers().size() != 1) {
882 ALOGE("Failed to import writeback buffer");
883 return ret;
884 }
885
886 drmModeAtomicReqPtr pset = drmModeAtomicAlloc();
887 if (!pset) {
888 ALOGE("Failed to allocate property set");
889 return -ENOMEM;
890 }
891 DrmDevice *drm = resource_manager_->GetDrmDevice(display_);
892 DrmCrtc *crtc = drm->GetCrtcForDisplay(display_);
893 if (!crtc) {
894 ALOGE("Failed to find crtc for display %d", display_);
895 return -EINVAL;
896 }
897 ret = SetupWritebackCommit(pset, crtc->id(), writeback_conn,
898 &writeback_layer.buffer);
899 if (ret < 0) {
900 ALOGE("Failed to Setup Writeback Commit");
901 return ret;
902 }
903 ret = drmModeAtomicCommit(drm->fd(), pset, 0, drm);
904 if (ret) {
905 ALOGE("Failed to enable writeback %d", ret);
906 return ret;
907 }
908 ret = sync_wait(writeback_fence_, kWaitWritebackFence);
909 writeback_layer.acquire_fence.Set(writeback_fence_);
910 writeback_fence_ = -1;
911 if (ret) {
912 ALOGE("Failed to wait on writeback fence");
913 return ret;
914 }
915
916 DrmCompositionPlane squashed_comp(DrmCompositionPlane::Type::kLayer, NULL,
917 crtc);
918 for (auto &drmplane : drm->planes()) {
919 if (!drmplane->GetCrtcSupported(*crtc))
920 continue;
921 if (!squashed_comp.plane() && drmplane->type() == DRM_PLANE_TYPE_PRIMARY)
922 squashed_comp.set_plane(drmplane.get());
923 else
924 writeback_comp->AddPlaneDisable(drmplane.get());
925 }
926 squashed_comp.source_layers().push_back(0);
927 ret = writeback_comp->AddPlaneComposition(std::move(squashed_comp));
928 if (ret) {
929 ALOGE("Failed to add flatten scene");
930 return ret;
931 }
932
933 ApplyFrame(std::move(writeback_comp), 0, true);
934 return 0;
935 }
936
937 // Flatten a scene by using a crtc which works concurrent with
938 // the one driving the display.
FlattenConcurrent(DrmConnector * writeback_conn)939 int DrmDisplayCompositor::FlattenConcurrent(DrmConnector *writeback_conn) {
940 ALOGV("FlattenConcurrent by using an unused crtc/display");
941 int ret = 0;
942 DrmDisplayCompositor drmdisplaycompositor;
943 ret = drmdisplaycompositor.Init(resource_manager_, writeback_conn->display());
944 if (ret) {
945 ALOGE("Failed to init drmdisplaycompositor = %d", ret);
946 return ret;
947 }
948 // Copy of the active_composition, needed because of two things:
949 // 1) Not to hold the lock for the whole time we are accessing
950 // active_composition
951 // 2) It will be committed on a crtc that might not be on the same
952 // dri node, so buffers need to be imported on the right node.
953 std::unique_ptr<DrmDisplayComposition>
954 copy_comp = drmdisplaycompositor.CreateInitializedComposition();
955
956 // Writeback composition that will be committed to the display.
957 std::unique_ptr<DrmDisplayComposition>
958 writeback_comp = CreateInitializedComposition();
959
960 if (!copy_comp || !writeback_comp)
961 return -EINVAL;
962 AutoLock lock(&lock_, __func__);
963 ret = lock.Lock();
964 if (ret)
965 return ret;
966 if (!IsFlatteningNeeded()) {
967 ALOGV("Flattening is not needed");
968 SetFlattening(FlatteningState::kNotNeeded);
969 return -EALREADY;
970 }
971 DrmCrtc *crtc = active_composition_->crtc();
972
973 std::vector<DrmHwcLayer> copy_layers;
974 for (DrmHwcLayer &src_layer : active_composition_->layers()) {
975 DrmHwcLayer copy;
976 ret = copy.InitFromDrmHwcLayer(&src_layer,
977 resource_manager_
978 ->GetImporter(writeback_conn->display())
979 .get());
980 if (ret) {
981 ALOGE("Failed to import buffer ret = %d", ret);
982 return -EINVAL;
983 }
984 copy_layers.emplace_back(std::move(copy));
985 }
986 ret = copy_comp->SetLayers(copy_layers.data(), copy_layers.size(), true);
987 if (ret) {
988 ALOGE("Failed to set copy_comp layers");
989 return ret;
990 }
991
992 lock.Unlock();
993 DrmHwcLayer writeback_layer;
994 ret = drmdisplaycompositor.FlattenOnDisplay(copy_comp, writeback_conn,
995 mode_.mode, &writeback_layer);
996 if (ret) {
997 ALOGE("Failed to flatten on display ret = %d", ret);
998 return ret;
999 }
1000
1001 DrmCompositionPlane squashed_comp(DrmCompositionPlane::Type::kLayer, NULL,
1002 crtc);
1003 for (auto &drmplane : resource_manager_->GetDrmDevice(display_)->planes()) {
1004 if (!drmplane->GetCrtcSupported(*crtc))
1005 continue;
1006 if (drmplane->type() == DRM_PLANE_TYPE_PRIMARY)
1007 squashed_comp.set_plane(drmplane.get());
1008 else
1009 writeback_comp->AddPlaneDisable(drmplane.get());
1010 }
1011 writeback_comp->layers().emplace_back();
1012 DrmHwcLayer &next_layer = writeback_comp->layers().back();
1013 next_layer.sf_handle = writeback_layer.get_usable_handle();
1014 next_layer.blending = DrmHwcBlending::kPreMult;
1015 next_layer.source_crop = {0, 0, (float)mode_.mode.h_display(),
1016 (float)mode_.mode.v_display()};
1017 next_layer.display_frame = {0, 0, (int)mode_.mode.h_display(),
1018 (int)mode_.mode.v_display()};
1019 ret = next_layer.ImportBuffer(resource_manager_->GetImporter(display_).get());
1020 if (ret) {
1021 ALOGE("Failed to import framebuffer for display %d", ret);
1022 return ret;
1023 }
1024 squashed_comp.source_layers().push_back(0);
1025 ret = writeback_comp->AddPlaneComposition(std::move(squashed_comp));
1026 if (ret) {
1027 ALOGE("Failed to add plane composition %d", ret);
1028 return ret;
1029 }
1030 ApplyFrame(std::move(writeback_comp), 0, true);
1031 return ret;
1032 }
1033
FlattenActiveComposition()1034 int DrmDisplayCompositor::FlattenActiveComposition() {
1035 DrmConnector *writeback_conn = resource_manager_->AvailableWritebackConnector(
1036 display_);
1037 if (!active_composition_ || !writeback_conn) {
1038 // Try to fallback to GPU composition on client, since it is more
1039 // power-efficient than composition on device side
1040 return FlattenOnClient();
1041 }
1042
1043 if (writeback_conn->display() != display_) {
1044 SetFlattening(FlatteningState::kConcurrent);
1045 return FlattenConcurrent(writeback_conn);
1046 } else {
1047 SetFlattening(FlatteningState::kSerial);
1048 return FlattenSerial(writeback_conn);
1049 }
1050
1051 return 0;
1052 }
1053
CountdownExpired() const1054 bool DrmDisplayCompositor::CountdownExpired() const {
1055 return flatten_countdown_ <= 0;
1056 }
1057
Vsync(int display,int64_t timestamp)1058 void DrmDisplayCompositor::Vsync(int display, int64_t timestamp) {
1059 AutoLock lock(&lock_, __func__);
1060 if (lock.Lock())
1061 return;
1062 flatten_countdown_--;
1063 if (!CountdownExpired())
1064 return;
1065 lock.Unlock();
1066 int ret = FlattenActiveComposition();
1067 ALOGV("scene flattening triggered for display %d at timestamp %" PRIu64
1068 " result = %d \n",
1069 display, timestamp, ret);
1070 }
1071
Dump(std::ostringstream * out) const1072 void DrmDisplayCompositor::Dump(std::ostringstream *out) const {
1073 int ret = pthread_mutex_lock(&lock_);
1074 if (ret)
1075 return;
1076
1077 uint64_t num_frames = dump_frames_composited_;
1078 dump_frames_composited_ = 0;
1079
1080 struct timespec ts;
1081 ret = clock_gettime(CLOCK_MONOTONIC, &ts);
1082 if (ret) {
1083 pthread_mutex_unlock(&lock_);
1084 return;
1085 }
1086
1087 uint64_t cur_ts = ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
1088 uint64_t num_ms = (cur_ts - dump_last_timestamp_ns_) / (1000 * 1000);
1089 float fps = num_ms ? (num_frames * 1000.0f) / (num_ms) : 0.0f;
1090
1091 *out << "--DrmDisplayCompositor[" << display_
1092 << "]: num_frames=" << num_frames << " num_ms=" << num_ms
1093 << " fps=" << fps << "\n";
1094
1095 dump_last_timestamp_ns_ = cur_ts;
1096
1097 pthread_mutex_unlock(&lock_);
1098 }
1099 } // namespace android
1100