• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 #include "drmcrtc.h"
22 #include "drmplane.h"
23 #include "drmresources.h"
24 #include "glworker.h"
25 
26 #include <pthread.h>
27 #include <sched.h>
28 #include <sstream>
29 #include <stdlib.h>
30 #include <time.h>
31 #include <vector>
32 
33 #include <drm/drm_mode.h>
34 #include <cutils/log.h>
35 #include <sync/sync.h>
36 #include <utils/Trace.h>
37 
38 #define DRM_DISPLAY_COMPOSITOR_MAX_QUEUE_DEPTH 2
39 
40 namespace android {
41 
Init(DrmHwcLayer * layers,size_t num_layers)42 void SquashState::Init(DrmHwcLayer *layers, size_t num_layers) {
43   generation_number_++;
44   valid_history_ = 0;
45   regions_.clear();
46   last_handles_.clear();
47 
48   std::vector<DrmHwcRect<int>> in_rects;
49   for (size_t i = 0; i < num_layers; i++) {
50     DrmHwcLayer *layer = &layers[i];
51     in_rects.emplace_back(layer->display_frame);
52     last_handles_.push_back(layer->sf_handle);
53   }
54 
55   std::vector<seperate_rects::RectSet<uint64_t, int>> out_regions;
56   seperate_rects::seperate_rects_64(in_rects, &out_regions);
57 
58   for (const seperate_rects::RectSet<uint64_t, int> &out_region : out_regions) {
59     regions_.emplace_back();
60     Region &region = regions_.back();
61     region.rect = out_region.rect;
62     region.layer_refs = out_region.id_set.getBits();
63   }
64 }
65 
GenerateHistory(DrmHwcLayer * layers,size_t num_layers,std::vector<bool> & changed_regions) const66 void SquashState::GenerateHistory(DrmHwcLayer *layers, size_t num_layers,
67                                   std::vector<bool> &changed_regions) const {
68   changed_regions.resize(regions_.size());
69   if (num_layers != last_handles_.size()) {
70     ALOGE("SquashState::GenerateHistory expected %zu layers but got %zu layers",
71           last_handles_.size(), num_layers);
72     return;
73   }
74   std::bitset<kMaxLayers> changed_layers;
75   for (size_t i = 0; i < last_handles_.size(); i++) {
76     DrmHwcLayer *layer = &layers[i];
77     if (last_handles_[i] != layer->sf_handle) {
78       changed_layers.set(i);
79     }
80   }
81 
82   for (size_t i = 0; i < regions_.size(); i++) {
83     changed_regions[i] = (regions_[i].layer_refs & changed_layers).any();
84   }
85 }
86 
StableRegionsWithMarginalHistory(const std::vector<bool> & changed_regions,std::vector<bool> & stable_regions) const87 void SquashState::StableRegionsWithMarginalHistory(
88     const std::vector<bool> &changed_regions,
89     std::vector<bool> &stable_regions) const {
90   stable_regions.resize(regions_.size());
91   for (size_t i = 0; i < regions_.size(); i++) {
92     stable_regions[i] = !changed_regions[i] && is_stable(i);
93   }
94 }
95 
RecordHistory(DrmHwcLayer * layers,size_t num_layers,const std::vector<bool> & changed_regions)96 void SquashState::RecordHistory(DrmHwcLayer *layers, size_t num_layers,
97                                 const std::vector<bool> &changed_regions) {
98   if (num_layers != last_handles_.size()) {
99     ALOGE("SquashState::RecordHistory expected %zu layers but got %zu layers",
100           last_handles_.size(), num_layers);
101     return;
102   }
103   if (changed_regions.size() != regions_.size()) {
104     ALOGE("SquashState::RecordHistory expected %zu regions but got %zu regions",
105           regions_.size(), changed_regions.size());
106     return;
107   }
108 
109   for (size_t i = 0; i < last_handles_.size(); i++) {
110     DrmHwcLayer *layer = &layers[i];
111     last_handles_[i] = layer->sf_handle;
112   }
113 
114   for (size_t i = 0; i < regions_.size(); i++) {
115     regions_[i].change_history <<= 1;
116     regions_[i].change_history.set(/* LSB */ 0, changed_regions[i]);
117   }
118 
119   valid_history_++;
120 }
121 
RecordAndCompareSquashed(const std::vector<bool> & squashed_regions)122 bool SquashState::RecordAndCompareSquashed(
123     const std::vector<bool> &squashed_regions) {
124   if (squashed_regions.size() != regions_.size()) {
125     ALOGE(
126         "SquashState::RecordAndCompareSquashed expected %zu regions but got "
127         "%zu regions",
128         regions_.size(), squashed_regions.size());
129     return false;
130   }
131   bool changed = false;
132   for (size_t i = 0; i < regions_.size(); i++) {
133     if (regions_[i].squashed != squashed_regions[i]) {
134       regions_[i].squashed = squashed_regions[i];
135       changed = true;
136     }
137   }
138   return changed;
139 }
140 
Dump(std::ostringstream * out) const141 void SquashState::Dump(std::ostringstream *out) const {
142   *out << "----SquashState generation=" << generation_number_
143        << " history=" << valid_history_ << "\n"
144        << "    Regions: count=" << regions_.size() << "\n";
145   for (size_t i = 0; i < regions_.size(); i++) {
146     const Region &region = regions_[i];
147     *out << "      [" << i << "]"
148          << " history=" << region.change_history << " rect";
149     region.rect.Dump(out);
150     *out << " layers=(";
151     bool first = true;
152     for (size_t layer_index = 0; layer_index < kMaxLayers; layer_index++) {
153       if ((region.layer_refs &
154            std::bitset<kMaxLayers>((size_t)1 << layer_index))
155               .any()) {
156         if (!first)
157           *out << " ";
158         first = false;
159         *out << layer_index;
160       }
161     }
162     *out << ")";
163     if (region.squashed)
164       *out << " squashed";
165     *out << "\n";
166   }
167 }
168 
UsesSquash(const std::vector<DrmCompositionPlane> & comp_planes)169 static bool UsesSquash(const std::vector<DrmCompositionPlane> &comp_planes) {
170   return std::any_of(comp_planes.begin(), comp_planes.end(),
171                      [](const DrmCompositionPlane &plane) {
172                        return plane.source_layer ==
173                               DrmCompositionPlane::kSourceSquash;
174                      });
175 }
176 
FrameWorker(DrmDisplayCompositor * compositor)177 DrmDisplayCompositor::FrameWorker::FrameWorker(DrmDisplayCompositor *compositor)
178     : Worker("frame-worker", HAL_PRIORITY_URGENT_DISPLAY),
179       compositor_(compositor) {
180 }
181 
~FrameWorker()182 DrmDisplayCompositor::FrameWorker::~FrameWorker() {
183 }
184 
Init()185 int DrmDisplayCompositor::FrameWorker::Init() {
186   return InitWorker();
187 }
188 
QueueFrame(std::unique_ptr<DrmDisplayComposition> composition,int status)189 void DrmDisplayCompositor::FrameWorker::QueueFrame(
190     std::unique_ptr<DrmDisplayComposition> composition, int status) {
191   Lock();
192   FrameState frame;
193   frame.composition = std::move(composition);
194   frame.status = status;
195   frame_queue_.push(std::move(frame));
196   SignalLocked();
197   Unlock();
198 }
199 
Routine()200 void DrmDisplayCompositor::FrameWorker::Routine() {
201   int ret = Lock();
202   if (ret) {
203     ALOGE("Failed to lock worker, %d", ret);
204     return;
205   }
206 
207   int wait_ret = 0;
208   if (frame_queue_.empty()) {
209     wait_ret = WaitForSignalOrExitLocked();
210   }
211 
212   FrameState frame;
213   if (!frame_queue_.empty()) {
214     frame = std::move(frame_queue_.front());
215     frame_queue_.pop();
216   }
217 
218   ret = Unlock();
219   if (ret) {
220     ALOGE("Failed to unlock worker, %d", ret);
221     return;
222   }
223 
224   if (wait_ret == -EINTR) {
225     return;
226   } else if (wait_ret) {
227     ALOGE("Failed to wait for signal, %d", wait_ret);
228     return;
229   }
230 
231   compositor_->ApplyFrame(std::move(frame.composition), frame.status);
232 }
233 
DrmDisplayCompositor()234 DrmDisplayCompositor::DrmDisplayCompositor()
235     : drm_(NULL),
236       display_(-1),
237       worker_(this),
238       frame_worker_(this),
239       initialized_(false),
240       active_(false),
241       needs_modeset_(false),
242       framebuffer_index_(0),
243       squash_framebuffer_index_(0),
244       dump_frames_composited_(0),
245       dump_last_timestamp_ns_(0) {
246   struct timespec ts;
247   if (clock_gettime(CLOCK_MONOTONIC, &ts))
248     return;
249   dump_last_timestamp_ns_ = ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
250 }
251 
~DrmDisplayCompositor()252 DrmDisplayCompositor::~DrmDisplayCompositor() {
253   if (!initialized_)
254     return;
255 
256   worker_.Exit();
257   frame_worker_.Exit();
258 
259   int ret = pthread_mutex_lock(&lock_);
260   if (ret)
261     ALOGE("Failed to acquire compositor lock %d", ret);
262 
263   while (!composite_queue_.empty()) {
264     composite_queue_.front().reset();
265     composite_queue_.pop();
266   }
267   active_composition_.reset();
268 
269   ret = pthread_mutex_unlock(&lock_);
270   if (ret)
271     ALOGE("Failed to acquire compositor lock %d", ret);
272 
273   pthread_mutex_destroy(&lock_);
274 }
275 
Init(DrmResources * drm,int display)276 int DrmDisplayCompositor::Init(DrmResources *drm, int display) {
277   drm_ = drm;
278   display_ = display;
279 
280   int ret = pthread_mutex_init(&lock_, NULL);
281   if (ret) {
282     ALOGE("Failed to initialize drm compositor lock %d\n", ret);
283     return ret;
284   }
285   ret = worker_.Init();
286   if (ret) {
287     pthread_mutex_destroy(&lock_);
288     ALOGE("Failed to initialize compositor worker %d\n", ret);
289     return ret;
290   }
291   ret = frame_worker_.Init();
292   if (ret) {
293     pthread_mutex_destroy(&lock_);
294     ALOGE("Failed to initialize frame worker %d\n", ret);
295     return ret;
296   }
297 
298   initialized_ = true;
299   return 0;
300 }
301 
CreateComposition() const302 std::unique_ptr<DrmDisplayComposition> DrmDisplayCompositor::CreateComposition()
303     const {
304   return std::unique_ptr<DrmDisplayComposition>(new DrmDisplayComposition());
305 }
306 
QueueComposition(std::unique_ptr<DrmDisplayComposition> composition)307 int DrmDisplayCompositor::QueueComposition(
308     std::unique_ptr<DrmDisplayComposition> composition) {
309   switch (composition->type()) {
310     case DRM_COMPOSITION_TYPE_FRAME:
311       if (!active_)
312         return -ENODEV;
313       break;
314     case DRM_COMPOSITION_TYPE_DPMS:
315       /*
316        * Update the state as soon as we get it so we can start/stop queuing
317        * frames asap.
318        */
319       active_ = (composition->dpms_mode() == DRM_MODE_DPMS_ON);
320       break;
321     case DRM_COMPOSITION_TYPE_MODESET:
322       break;
323     case DRM_COMPOSITION_TYPE_EMPTY:
324       return 0;
325     default:
326       ALOGE("Unknown composition type %d/%d", composition->type(), display_);
327       return -ENOENT;
328   }
329 
330   int ret = pthread_mutex_lock(&lock_);
331   if (ret) {
332     ALOGE("Failed to acquire compositor lock %d", ret);
333     return ret;
334   }
335 
336   // Block the queue if it gets too large. Otherwise, SurfaceFlinger will start
337   // to eat our buffer handles when we get about 1 second behind.
338   while (composite_queue_.size() >= DRM_DISPLAY_COMPOSITOR_MAX_QUEUE_DEPTH) {
339     pthread_mutex_unlock(&lock_);
340     sched_yield();
341     pthread_mutex_lock(&lock_);
342   }
343 
344   composite_queue_.push(std::move(composition));
345 
346   ret = pthread_mutex_unlock(&lock_);
347   if (ret) {
348     ALOGE("Failed to release compositor lock %d", ret);
349     return ret;
350   }
351 
352   worker_.Signal();
353   return 0;
354 }
355 
356 std::tuple<uint32_t, uint32_t, int>
GetActiveModeResolution()357 DrmDisplayCompositor::GetActiveModeResolution() {
358   DrmConnector *connector = drm_->GetConnectorForDisplay(display_);
359   if (connector == NULL) {
360     ALOGE("Failed to determine display mode: no connector for display %d",
361           display_);
362     return std::make_tuple(0, 0, -ENODEV);
363   }
364 
365   const DrmMode &mode = connector->active_mode();
366   return std::make_tuple(mode.h_display(), mode.v_display(), 0);
367 }
368 
PrepareFramebuffer(DrmFramebuffer & fb,DrmDisplayComposition * display_comp)369 int DrmDisplayCompositor::PrepareFramebuffer(
370     DrmFramebuffer &fb, DrmDisplayComposition *display_comp) {
371   int ret = fb.WaitReleased(-1);
372   if (ret) {
373     ALOGE("Failed to wait for framebuffer release %d", ret);
374     return ret;
375   }
376   uint32_t width, height;
377   std::tie(width, height, ret) = GetActiveModeResolution();
378   if (ret) {
379     ALOGE(
380         "Failed to allocate framebuffer because the display resolution could "
381         "not be determined %d",
382         ret);
383     return ret;
384   }
385 
386   fb.set_release_fence_fd(-1);
387   if (!fb.Allocate(width, height)) {
388     ALOGE("Failed to allocate framebuffer with size %dx%d", width, height);
389     return -ENOMEM;
390   }
391 
392   display_comp->layers().emplace_back();
393   DrmHwcLayer &pre_comp_layer = display_comp->layers().back();
394   pre_comp_layer.sf_handle = fb.buffer()->handle;
395   pre_comp_layer.source_crop = DrmHwcRect<float>(0, 0, width, height);
396   pre_comp_layer.display_frame = DrmHwcRect<int>(0, 0, width, height);
397   ret = pre_comp_layer.buffer.ImportBuffer(fb.buffer()->handle,
398                                            display_comp->importer());
399   if (ret) {
400     ALOGE("Failed to import framebuffer for display %d", ret);
401     return ret;
402   }
403 
404   return ret;
405 }
406 
ApplySquash(DrmDisplayComposition * display_comp)407 int DrmDisplayCompositor::ApplySquash(DrmDisplayComposition *display_comp) {
408   int ret = 0;
409 
410   DrmFramebuffer &fb = squash_framebuffers_[squash_framebuffer_index_];
411   ret = PrepareFramebuffer(fb, display_comp);
412   if (ret) {
413     ALOGE("Failed to prepare framebuffer for squash %d", ret);
414     return ret;
415   }
416 
417   std::vector<DrmCompositionRegion> &regions = display_comp->squash_regions();
418   ret = pre_compositor_->Composite(display_comp->layers().data(),
419                                    regions.data(), regions.size(), fb.buffer());
420   pre_compositor_->Finish();
421 
422   if (ret) {
423     ALOGE("Failed to squash layers");
424     return ret;
425   }
426 
427   ret = display_comp->CreateNextTimelineFence();
428   if (ret <= 0) {
429     ALOGE("Failed to create squash framebuffer release fence %d", ret);
430     return ret;
431   }
432 
433   fb.set_release_fence_fd(ret);
434   display_comp->SignalSquashDone();
435 
436   return 0;
437 }
438 
ApplyPreComposite(DrmDisplayComposition * display_comp)439 int DrmDisplayCompositor::ApplyPreComposite(
440     DrmDisplayComposition *display_comp) {
441   int ret = 0;
442 
443   DrmFramebuffer &fb = framebuffers_[framebuffer_index_];
444   ret = PrepareFramebuffer(fb, display_comp);
445   if (ret) {
446     ALOGE("Failed to prepare framebuffer for pre-composite %d", ret);
447     return ret;
448   }
449 
450   std::vector<DrmCompositionRegion> &regions = display_comp->pre_comp_regions();
451   ret = pre_compositor_->Composite(display_comp->layers().data(),
452                                    regions.data(), regions.size(), fb.buffer());
453   pre_compositor_->Finish();
454 
455   if (ret) {
456     ALOGE("Failed to pre-composite layers");
457     return ret;
458   }
459 
460   ret = display_comp->CreateNextTimelineFence();
461   if (ret <= 0) {
462     ALOGE("Failed to create pre-composite framebuffer release fence %d", ret);
463     return ret;
464   }
465 
466   fb.set_release_fence_fd(ret);
467   display_comp->SignalPreCompDone();
468 
469   return 0;
470 }
471 
DisablePlanes(DrmDisplayComposition * display_comp)472 int DrmDisplayCompositor::DisablePlanes(DrmDisplayComposition *display_comp) {
473   drmModePropertySetPtr pset = drmModePropertySetAlloc();
474   if (!pset) {
475     ALOGE("Failed to allocate property set");
476     return -ENOMEM;
477   }
478 
479   int ret;
480   std::vector<DrmCompositionPlane> &comp_planes =
481       display_comp->composition_planes();
482   for (DrmCompositionPlane &comp_plane : comp_planes) {
483     DrmPlane *plane = comp_plane.plane;
484     ret =
485         drmModePropertySetAdd(pset, plane->id(), plane->crtc_property().id(),
486                               0) ||
487         drmModePropertySetAdd(pset, plane->id(), plane->fb_property().id(), 0);
488     if (ret) {
489       ALOGE("Failed to add plane %d disable to pset", plane->id());
490       drmModePropertySetFree(pset);
491       return ret;
492     }
493   }
494 
495   ret = drmModePropertySetCommit(drm_->fd(), 0, drm_, pset);
496   if (ret) {
497     ALOGE("Failed to commit pset ret=%d\n", ret);
498     drmModePropertySetFree(pset);
499     return ret;
500   }
501 
502   drmModePropertySetFree(pset);
503   return 0;
504 }
505 
PrepareFrame(DrmDisplayComposition * display_comp)506 int DrmDisplayCompositor::PrepareFrame(DrmDisplayComposition *display_comp) {
507   int ret = 0;
508 
509   std::vector<DrmHwcLayer> &layers = display_comp->layers();
510   std::vector<DrmCompositionPlane> &comp_planes =
511       display_comp->composition_planes();
512   std::vector<DrmCompositionRegion> &squash_regions =
513       display_comp->squash_regions();
514   std::vector<DrmCompositionRegion> &pre_comp_regions =
515       display_comp->pre_comp_regions();
516 
517   int squash_layer_index = -1;
518   if (squash_regions.size() > 0) {
519     squash_framebuffer_index_ = (squash_framebuffer_index_ + 1) % 2;
520     ret = ApplySquash(display_comp);
521     if (ret)
522       return ret;
523 
524     squash_layer_index = layers.size() - 1;
525   } else {
526     if (UsesSquash(comp_planes)) {
527       DrmFramebuffer &fb = squash_framebuffers_[squash_framebuffer_index_];
528       layers.emplace_back();
529       squash_layer_index = layers.size() - 1;
530       DrmHwcLayer &squash_layer = layers.back();
531       ret = squash_layer.buffer.ImportBuffer(fb.buffer()->handle,
532                                              display_comp->importer());
533       if (ret) {
534         ALOGE("Failed to import old squashed framebuffer %d", ret);
535         return ret;
536       }
537       squash_layer.sf_handle = fb.buffer()->handle;
538       squash_layer.source_crop = DrmHwcRect<float>(
539           0, 0, squash_layer.buffer->width, squash_layer.buffer->height);
540       squash_layer.display_frame = DrmHwcRect<int>(
541           0, 0, squash_layer.buffer->width, squash_layer.buffer->height);
542       ret = display_comp->CreateNextTimelineFence();
543 
544       if (ret <= 0) {
545         ALOGE("Failed to create squash framebuffer release fence %d", ret);
546         return ret;
547       }
548 
549       fb.set_release_fence_fd(ret);
550       ret = 0;
551     }
552   }
553 
554   bool do_pre_comp = pre_comp_regions.size() > 0;
555   int pre_comp_layer_index = -1;
556   if (do_pre_comp) {
557     ret = ApplyPreComposite(display_comp);
558     if (ret)
559       return ret;
560 
561     pre_comp_layer_index = layers.size() - 1;
562     framebuffer_index_ = (framebuffer_index_ + 1) % DRM_DISPLAY_BUFFERS;
563   }
564 
565   for (DrmCompositionPlane &comp_plane : comp_planes) {
566     switch (comp_plane.source_layer) {
567       case DrmCompositionPlane::kSourceSquash:
568         comp_plane.source_layer = squash_layer_index;
569         break;
570       case DrmCompositionPlane::kSourcePreComp:
571         if (!do_pre_comp) {
572           ALOGE(
573               "Can not use pre composite framebuffer with no pre composite "
574               "regions");
575           return -EINVAL;
576         }
577         comp_plane.source_layer = pre_comp_layer_index;
578         break;
579       default:
580         break;
581     }
582   }
583 
584   return ret;
585 }
586 
CommitFrame(DrmDisplayComposition * display_comp)587 int DrmDisplayCompositor::CommitFrame(DrmDisplayComposition *display_comp) {
588   int ret = 0;
589 
590   std::vector<DrmHwcLayer> &layers = display_comp->layers();
591   std::vector<DrmCompositionPlane> &comp_planes =
592       display_comp->composition_planes();
593   std::vector<DrmCompositionRegion> &pre_comp_regions =
594       display_comp->pre_comp_regions();
595 
596   DrmFramebuffer *pre_comp_fb;
597 
598   DrmConnector *connector = drm_->GetConnectorForDisplay(display_);
599   if (!connector) {
600     ALOGE("Could not locate connector for display %d", display_);
601     return -ENODEV;
602   }
603   DrmCrtc *crtc = drm_->GetCrtcForDisplay(display_);
604   if (!crtc) {
605     ALOGE("Could not locate crtc for display %d", display_);
606     return -ENODEV;
607   }
608 
609   drmModePropertySetPtr pset = drmModePropertySetAlloc();
610   if (!pset) {
611     ALOGE("Failed to allocate property set");
612     return -ENOMEM;
613   }
614 
615   uint32_t blob_id = 0;
616   uint64_t old_blob_id;
617   if (needs_modeset_) {
618     DrmProperty old_mode;
619     ret = drm_->GetCrtcProperty(*crtc, crtc->mode_property().name().c_str(),
620                                 &old_mode);
621     if (ret) {
622       ALOGE("Failed to get old mode property from crtc %d", crtc->id());
623       drmModePropertySetFree(pset);
624       return ret;
625     }
626     ret = old_mode.value(&old_blob_id);
627     if (ret) {
628       ALOGE("Could not get old blob id value %d", ret);
629       drmModePropertySetFree(pset);
630       return ret;
631     }
632 
633     struct drm_mode_modeinfo drm_mode;
634     memset(&drm_mode, 0, sizeof(drm_mode));
635     next_mode_.ToDrmModeModeInfo(&drm_mode);
636 
637     ret = drm_->CreatePropertyBlob(&drm_mode, sizeof(struct drm_mode_modeinfo),
638                                    &blob_id);
639     if (ret) {
640       ALOGE("Failed to create mode property blob %d", ret);
641       drmModePropertySetFree(pset);
642       return ret;
643     }
644 
645     ret = drmModePropertySetAdd(pset, crtc->id(), crtc->mode_property().id(),
646                                 blob_id) ||
647           drmModePropertySetAdd(pset, connector->id(),
648                                 connector->crtc_id_property().id(), crtc->id());
649     if (ret) {
650       ALOGE("Failed to add blob %d to pset", blob_id);
651       drmModePropertySetFree(pset);
652       drm_->DestroyPropertyBlob(blob_id);
653       return ret;
654     }
655   }
656 
657   for (DrmCompositionPlane &comp_plane : comp_planes) {
658     DrmPlane *plane = comp_plane.plane;
659     DrmCrtc *crtc = comp_plane.crtc;
660 
661     int fb_id = -1;
662     DrmHwcRect<int> display_frame;
663     DrmHwcRect<float> source_crop;
664     uint64_t rotation = 0;
665     uint64_t alpha = 0xFF;
666     switch (comp_plane.source_layer) {
667       case DrmCompositionPlane::kSourceNone:
668         break;
669       case DrmCompositionPlane::kSourceSquash:
670         ALOGE("Actual source layer index expected for squash layer");
671         break;
672       case DrmCompositionPlane::kSourcePreComp:
673         ALOGE("Actual source layer index expected for pre-comp layer");
674         break;
675       default: {
676         if (comp_plane.source_layer >= layers.size()) {
677           ALOGE("Source layer index %zu out of bounds %zu",
678                 comp_plane.source_layer, layers.size());
679           break;
680         }
681         DrmHwcLayer &layer = layers[comp_plane.source_layer];
682         if (layer.acquire_fence.get() >= 0) {
683           int acquire_fence = layer.acquire_fence.get();
684           for (int i = 0; i < kAcquireWaitTries; ++i) {
685             ret = sync_wait(acquire_fence, kAcquireWaitTimeoutMs);
686             if (ret)
687               ALOGW("Acquire fence %d wait %d failed (%d). Total time %d",
688                     acquire_fence, i, ret, (i + 1) * kAcquireWaitTimeoutMs);
689           }
690           if (ret) {
691             ALOGE("Failed to wait for acquire %d/%d", acquire_fence, ret);
692             break;
693           }
694           layer.acquire_fence.Close();
695         }
696         if (!layer.buffer) {
697           ALOGE("Expected a valid framebuffer for pset");
698           break;
699         }
700         fb_id = layer.buffer->fb_id;
701         display_frame = layer.display_frame;
702         source_crop = layer.source_crop;
703         if (layer.blending == DrmHwcBlending::kPreMult)
704           alpha = layer.alpha;
705         switch (layer.transform) {
706           case DrmHwcTransform::kFlipH:
707             rotation = 1 << DRM_REFLECT_X;
708             break;
709           case DrmHwcTransform::kFlipV:
710             rotation = 1 << DRM_REFLECT_Y;
711             break;
712           case DrmHwcTransform::kRotate90:
713             rotation = 1 << DRM_ROTATE_90;
714             break;
715           case DrmHwcTransform::kRotate180:
716             rotation = 1 << DRM_ROTATE_180;
717             break;
718           case DrmHwcTransform::kRotate270:
719             rotation = 1 << DRM_ROTATE_270;
720             break;
721           case DrmHwcTransform::kIdentity:
722             rotation = 0;
723             break;
724           default:
725             ALOGE("Invalid transform value 0x%x given", layer.transform);
726             break;
727         }
728         break;
729       }
730     }
731 
732     // Disable the plane if there's no framebuffer
733     if (fb_id < 0) {
734       ret = drmModePropertySetAdd(pset, plane->id(),
735                                   plane->crtc_property().id(), 0) ||
736             drmModePropertySetAdd(pset, plane->id(), plane->fb_property().id(),
737                                   0);
738       if (ret) {
739         ALOGE("Failed to add plane %d disable to pset", plane->id());
740         break;
741       }
742       continue;
743     }
744 
745     // TODO: Once we have atomic test, this should fall back to GL
746     if (rotation && plane->rotation_property().id() == 0) {
747       ALOGE("Rotation is not supported on plane %d", plane->id());
748       ret = -EINVAL;
749       break;
750     }
751 
752     // TODO: Once we have atomic test, this should fall back to GL
753     if (alpha != 0xFF && plane->alpha_property().id() == 0) {
754       ALOGE("Alpha is not supported on plane %d", plane->id());
755       ret = -EINVAL;
756       break;
757     }
758 
759     ret =
760         drmModePropertySetAdd(pset, plane->id(), plane->crtc_property().id(),
761                               crtc->id()) ||
762         drmModePropertySetAdd(pset, plane->id(), plane->fb_property().id(),
763                               fb_id) ||
764         drmModePropertySetAdd(pset, plane->id(), plane->crtc_x_property().id(),
765                               display_frame.left) ||
766         drmModePropertySetAdd(pset, plane->id(), plane->crtc_y_property().id(),
767                               display_frame.top) ||
768         drmModePropertySetAdd(pset, plane->id(), plane->crtc_w_property().id(),
769                               display_frame.right - display_frame.left) ||
770         drmModePropertySetAdd(pset, plane->id(), plane->crtc_h_property().id(),
771                               display_frame.bottom - display_frame.top) ||
772         drmModePropertySetAdd(pset, plane->id(), plane->src_x_property().id(),
773                               (int)(source_crop.left) << 16) ||
774         drmModePropertySetAdd(pset, plane->id(), plane->src_y_property().id(),
775                               (int)(source_crop.top) << 16) ||
776         drmModePropertySetAdd(pset, plane->id(), plane->src_w_property().id(),
777                               (int)(source_crop.right - source_crop.left)
778                                   << 16) ||
779         drmModePropertySetAdd(pset, plane->id(), plane->src_h_property().id(),
780                               (int)(source_crop.bottom - source_crop.top)
781                                   << 16);
782     if (ret) {
783       ALOGE("Failed to add plane %d to set", plane->id());
784       break;
785     }
786 
787     if (plane->rotation_property().id()) {
788       ret = drmModePropertySetAdd(pset, plane->id(),
789                                   plane->rotation_property().id(), rotation);
790       if (ret) {
791         ALOGE("Failed to add rotation property %d to plane %d",
792               plane->rotation_property().id(), plane->id());
793         break;
794       }
795     }
796 
797     if (plane->alpha_property().id()) {
798       ret = drmModePropertySetAdd(pset, plane->id(),
799                                   plane->alpha_property().id(), alpha);
800       if (ret) {
801         ALOGE("Failed to add alpha property %d to plane %d",
802               plane->alpha_property().id(), plane->id());
803         break;
804       }
805     }
806   }
807 
808 out:
809   if (!ret) {
810     ret = drmModePropertySetCommit(drm_->fd(), DRM_MODE_ATOMIC_ALLOW_MODESET,
811                                    drm_, pset);
812     if (ret) {
813       ALOGE("Failed to commit pset ret=%d\n", ret);
814       drmModePropertySetFree(pset);
815       if (needs_modeset_)
816         drm_->DestroyPropertyBlob(blob_id);
817       return ret;
818     }
819   }
820   if (pset)
821     drmModePropertySetFree(pset);
822 
823   if (needs_modeset_) {
824     ret = drm_->DestroyPropertyBlob(old_blob_id);
825     if (ret) {
826       ALOGE("Failed to destroy old mode property blob %lld/%d", old_blob_id,
827             ret);
828       return ret;
829     }
830 
831     /* TODO: Add dpms to the pset when the kernel supports it */
832     ret = ApplyDpms(display_comp);
833     if (ret) {
834       ALOGE("Failed to apply DPMS after modeset %d\n", ret);
835       return ret;
836     }
837 
838     connector->set_active_mode(next_mode_);
839     needs_modeset_ = false;
840   }
841 
842   return ret;
843 }
844 
ApplyDpms(DrmDisplayComposition * display_comp)845 int DrmDisplayCompositor::ApplyDpms(DrmDisplayComposition *display_comp) {
846   DrmConnector *conn = drm_->GetConnectorForDisplay(display_);
847   if (!conn) {
848     ALOGE("Failed to get DrmConnector for display %d", display_);
849     return -ENODEV;
850   }
851 
852   const DrmProperty &prop = conn->dpms_property();
853   int ret = drmModeConnectorSetProperty(drm_->fd(), conn->id(), prop.id(),
854                                         display_comp->dpms_mode());
855   if (ret) {
856     ALOGE("Failed to set DPMS property for connector %d", conn->id());
857     return ret;
858   }
859   return 0;
860 }
861 
ApplyFrame(std::unique_ptr<DrmDisplayComposition> composition,int status)862 void DrmDisplayCompositor::ApplyFrame(
863     std::unique_ptr<DrmDisplayComposition> composition, int status) {
864   int ret = status;
865 
866   if (!ret)
867     ret = CommitFrame(composition.get());
868 
869   if (ret) {
870     ALOGE("Composite failed for display %d", display_);
871 
872     // Disable the hw used by the last active composition. This allows us to
873     // signal the release fences from that composition to avoid hanging.
874     if (DisablePlanes(active_composition_.get()))
875       return;
876   }
877   ++dump_frames_composited_;
878 
879   if (active_composition_)
880     active_composition_->SignalCompositionDone();
881 
882   ret = pthread_mutex_lock(&lock_);
883   if (ret)
884     ALOGE("Failed to acquire lock for active_composition swap");
885 
886   active_composition_.swap(composition);
887 
888   if (!ret)
889     ret = pthread_mutex_unlock(&lock_);
890   if (ret)
891     ALOGE("Failed to release lock for active_composition swap");
892 }
893 
Composite()894 int DrmDisplayCompositor::Composite() {
895   ATRACE_CALL();
896 
897   if (!pre_compositor_) {
898     pre_compositor_.reset(new GLWorkerCompositor());
899     int ret = pre_compositor_->Init();
900     if (ret) {
901       ALOGE("Failed to initialize OpenGL compositor %d", ret);
902       return ret;
903     }
904   }
905 
906   int ret = pthread_mutex_lock(&lock_);
907   if (ret) {
908     ALOGE("Failed to acquire compositor lock %d", ret);
909     return ret;
910   }
911   if (composite_queue_.empty()) {
912     ret = pthread_mutex_unlock(&lock_);
913     if (ret)
914       ALOGE("Failed to release compositor lock %d", ret);
915     return ret;
916   }
917 
918   std::unique_ptr<DrmDisplayComposition> composition(
919       std::move(composite_queue_.front()));
920 
921   composite_queue_.pop();
922 
923   ret = pthread_mutex_unlock(&lock_);
924   if (ret) {
925     ALOGE("Failed to release compositor lock %d", ret);
926     return ret;
927   }
928 
929   switch (composition->type()) {
930     case DRM_COMPOSITION_TYPE_FRAME:
931       ret = PrepareFrame(composition.get());
932       frame_worker_.QueueFrame(std::move(composition), ret);
933       break;
934     case DRM_COMPOSITION_TYPE_DPMS:
935       ret = ApplyDpms(composition.get());
936       if (ret)
937         ALOGE("Failed to apply dpms for display %d", display_);
938       return ret;
939     case DRM_COMPOSITION_TYPE_MODESET:
940       next_mode_ = composition->display_mode();
941       needs_modeset_ = true;
942       return 0;
943     default:
944       ALOGE("Unknown composition type %d", composition->type());
945       return -EINVAL;
946   }
947 
948   return ret;
949 }
950 
HaveQueuedComposites() const951 bool DrmDisplayCompositor::HaveQueuedComposites() const {
952   int ret = pthread_mutex_lock(&lock_);
953   if (ret) {
954     ALOGE("Failed to acquire compositor lock %d", ret);
955     return false;
956   }
957 
958   bool empty_ret = !composite_queue_.empty();
959 
960   ret = pthread_mutex_unlock(&lock_);
961   if (ret) {
962     ALOGE("Failed to release compositor lock %d", ret);
963     return false;
964   }
965 
966   return empty_ret;
967 }
968 
Dump(std::ostringstream * out) const969 void DrmDisplayCompositor::Dump(std::ostringstream *out) const {
970   int ret = pthread_mutex_lock(&lock_);
971   if (ret)
972     return;
973 
974   uint64_t num_frames = dump_frames_composited_;
975   dump_frames_composited_ = 0;
976 
977   struct timespec ts;
978   ret = clock_gettime(CLOCK_MONOTONIC, &ts);
979   if (ret) {
980     pthread_mutex_unlock(&lock_);
981     return;
982   }
983 
984   uint64_t cur_ts = ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
985   uint64_t num_ms = (cur_ts - dump_last_timestamp_ns_) / (1000 * 1000);
986   float fps = num_ms ? (num_frames * 1000.0f) / (num_ms) : 0.0f;
987 
988   *out << "--DrmDisplayCompositor[" << display_
989        << "]: num_frames=" << num_frames << " num_ms=" << num_ms
990        << " fps=" << fps << "\n";
991 
992   dump_last_timestamp_ns_ = cur_ts;
993 
994   if (active_composition_)
995     active_composition_->Dump(out);
996 
997   squash_state_.Dump(out);
998 
999   pthread_mutex_unlock(&lock_);
1000 }
1001 }
1002