OSDN Git Service

drm_hwcomposer: Remove NVIDIA importer header
[android-x86/external-drm_hwcomposer.git] / drmdisplaycompositor.cpp
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 <pthread.h>
23 #include <sched.h>
24 #include <stdlib.h>
25 #include <time.h>
26 #include <sstream>
27 #include <vector>
28
29 #include <log/log.h>
30 #include <drm/drm_mode.h>
31 #include <sync/sync.h>
32 #include <utils/Trace.h>
33
34 #include "autolock.h"
35 #include "drmcrtc.h"
36 #include "drmplane.h"
37 #include "drmresources.h"
38 #include "glworker.h"
39
40 namespace android {
41
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<separate_rects::RectSet<uint64_t, int>> out_regions;
56   separate_rects::separate_rects_64(in_rects, &out_regions);
57
58   for (const separate_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
66 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     // Protected layers can't be squashed so we treat them as constantly
78     // changing.
79     if (layer->protected_usage() || last_handles_[i] != layer->sf_handle)
80       changed_layers.set(i);
81   }
82
83   for (size_t i = 0; i < regions_.size(); i++) {
84     changed_regions[i] = (regions_[i].layer_refs & changed_layers).any();
85   }
86 }
87
88 void SquashState::StableRegionsWithMarginalHistory(
89     const std::vector<bool> &changed_regions,
90     std::vector<bool> &stable_regions) const {
91   stable_regions.resize(regions_.size());
92   for (size_t i = 0; i < regions_.size(); i++) {
93     stable_regions[i] = !changed_regions[i] && is_stable(i);
94   }
95 }
96
97 void SquashState::RecordHistory(DrmHwcLayer *layers, size_t num_layers,
98                                 const std::vector<bool> &changed_regions) {
99   if (num_layers != last_handles_.size()) {
100     ALOGE("SquashState::RecordHistory expected %zu layers but got %zu layers",
101           last_handles_.size(), num_layers);
102     return;
103   }
104   if (changed_regions.size() != regions_.size()) {
105     ALOGE("SquashState::RecordHistory expected %zu regions but got %zu regions",
106           regions_.size(), changed_regions.size());
107     return;
108   }
109
110   for (size_t i = 0; i < last_handles_.size(); i++) {
111     DrmHwcLayer *layer = &layers[i];
112     last_handles_[i] = layer->sf_handle;
113   }
114
115   for (size_t i = 0; i < regions_.size(); i++) {
116     regions_[i].change_history <<= 1;
117     regions_[i].change_history.set(/* LSB */ 0, changed_regions[i]);
118   }
119
120   valid_history_++;
121 }
122
123 bool SquashState::RecordAndCompareSquashed(
124     const std::vector<bool> &squashed_regions) {
125   if (squashed_regions.size() != regions_.size()) {
126     ALOGE(
127         "SquashState::RecordAndCompareSquashed expected %zu regions but got "
128         "%zu regions",
129         regions_.size(), squashed_regions.size());
130     return false;
131   }
132   bool changed = false;
133   for (size_t i = 0; i < regions_.size(); i++) {
134     if (regions_[i].squashed != squashed_regions[i]) {
135       regions_[i].squashed = squashed_regions[i];
136       changed = true;
137     }
138   }
139   return changed;
140 }
141
142 void SquashState::Dump(std::ostringstream *out) const {
143   *out << "----SquashState generation=" << generation_number_
144        << " history=" << valid_history_ << "\n"
145        << "    Regions: count=" << regions_.size() << "\n";
146   for (size_t i = 0; i < regions_.size(); i++) {
147     const Region &region = regions_[i];
148     *out << "      [" << i << "]"
149          << " history=" << region.change_history << " rect";
150     region.rect.Dump(out);
151     *out << " layers=(";
152     bool first = true;
153     for (size_t layer_index = 0; layer_index < kMaxLayers; layer_index++) {
154       if ((region.layer_refs &
155            std::bitset<kMaxLayers>((size_t)1 << layer_index))
156               .any()) {
157         if (!first)
158           *out << " ";
159         first = false;
160         *out << layer_index;
161       }
162     }
163     *out << ")";
164     if (region.squashed)
165       *out << " squashed";
166     *out << "\n";
167   }
168 }
169
170 static bool UsesSquash(const std::vector<DrmCompositionPlane> &comp_planes) {
171   return std::any_of(comp_planes.begin(), comp_planes.end(),
172                      [](const DrmCompositionPlane &plane) {
173     return plane.type() == DrmCompositionPlane::Type::kSquash;
174   });
175 }
176
177 DrmDisplayCompositor::DrmDisplayCompositor()
178     : drm_(NULL),
179       display_(-1),
180       initialized_(false),
181       active_(false),
182       use_hw_overlays_(true),
183       framebuffer_index_(0),
184       squash_framebuffer_index_(0),
185       dump_frames_composited_(0),
186       dump_last_timestamp_ns_(0) {
187   struct timespec ts;
188   if (clock_gettime(CLOCK_MONOTONIC, &ts))
189     return;
190   dump_last_timestamp_ns_ = ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
191 }
192
193 DrmDisplayCompositor::~DrmDisplayCompositor() {
194   if (!initialized_)
195     return;
196
197   int ret = pthread_mutex_lock(&lock_);
198   if (ret)
199     ALOGE("Failed to acquire compositor lock %d", ret);
200
201   if (mode_.blob_id)
202     drm_->DestroyPropertyBlob(mode_.blob_id);
203   if (mode_.old_blob_id)
204     drm_->DestroyPropertyBlob(mode_.old_blob_id);
205
206   active_composition_.reset();
207
208   ret = pthread_mutex_unlock(&lock_);
209   if (ret)
210     ALOGE("Failed to acquire compositor lock %d", ret);
211
212   pthread_mutex_destroy(&lock_);
213 }
214
215 int DrmDisplayCompositor::Init(DrmResources *drm, int display) {
216   drm_ = drm;
217   display_ = display;
218
219   int ret = pthread_mutex_init(&lock_, NULL);
220   if (ret) {
221     ALOGE("Failed to initialize drm compositor lock %d\n", ret);
222     return ret;
223   }
224
225   pre_compositor_.reset(new GLWorkerCompositor());
226   ret = pre_compositor_->Init();
227   if (ret) {
228     ALOGE("Failed to initialize OpenGL compositor %d", ret);
229     pre_compositor_.reset();
230   }
231
232   initialized_ = true;
233   return 0;
234 }
235
236 std::unique_ptr<DrmDisplayComposition> DrmDisplayCompositor::CreateComposition()
237     const {
238   return std::unique_ptr<DrmDisplayComposition>(new DrmDisplayComposition());
239 }
240
241 std::tuple<uint32_t, uint32_t, int>
242 DrmDisplayCompositor::GetActiveModeResolution() {
243   DrmConnector *connector = drm_->GetConnectorForDisplay(display_);
244   if (connector == NULL) {
245     ALOGE("Failed to determine display mode: no connector for display %d",
246           display_);
247     return std::make_tuple(0, 0, -ENODEV);
248   }
249
250   const DrmMode &mode = connector->active_mode();
251   return std::make_tuple(mode.h_display(), mode.v_display(), 0);
252 }
253
254 int DrmDisplayCompositor::PrepareFramebuffer(
255     DrmFramebuffer &fb, DrmDisplayComposition *display_comp) {
256   int ret = fb.WaitReleased(-1);
257   if (ret) {
258     ALOGE("Failed to wait for framebuffer release %d", ret);
259     return ret;
260   }
261   uint32_t width, height;
262   std::tie(width, height, ret) = GetActiveModeResolution();
263   if (ret) {
264     ALOGE(
265         "Failed to allocate framebuffer because the display resolution could "
266         "not be determined %d",
267         ret);
268     return ret;
269   }
270
271   fb.set_release_fence_fd(-1);
272   if (!fb.Allocate(width, height)) {
273     ALOGE("Failed to allocate framebuffer with size %dx%d", width, height);
274     return -ENOMEM;
275   }
276
277   display_comp->layers().emplace_back();
278   DrmHwcLayer &pre_comp_layer = display_comp->layers().back();
279   pre_comp_layer.sf_handle = fb.buffer()->handle;
280   pre_comp_layer.blending = DrmHwcBlending::kPreMult;
281   pre_comp_layer.source_crop = DrmHwcRect<float>(0, 0, width, height);
282   pre_comp_layer.display_frame = DrmHwcRect<int>(0, 0, width, height);
283   ret = pre_comp_layer.buffer.ImportBuffer(fb.buffer()->handle,
284                                            display_comp->importer());
285   if (ret) {
286     ALOGE("Failed to import framebuffer for display %d", ret);
287     return ret;
288   }
289
290   return ret;
291 }
292
293 int DrmDisplayCompositor::ApplySquash(DrmDisplayComposition *display_comp) {
294   int ret = 0;
295
296   DrmFramebuffer &fb = squash_framebuffers_[squash_framebuffer_index_];
297   ret = PrepareFramebuffer(fb, display_comp);
298   if (ret) {
299     ALOGE("Failed to prepare framebuffer for squash %d", ret);
300     return ret;
301   }
302
303   std::vector<DrmCompositionRegion> &regions = display_comp->squash_regions();
304   if (pre_compositor_) {
305     ret = pre_compositor_->Composite(display_comp->layers().data(),
306                                    regions.data(), regions.size(), fb.buffer(),
307                                    display_comp->importer());
308     pre_compositor_->Finish();
309
310     if (ret) {
311       ALOGE("Failed to squash layers");
312       return ret;
313     }
314   }
315
316   ret = display_comp->CreateNextTimelineFence();
317   if (ret <= 0) {
318     ALOGE("Failed to create squash framebuffer release fence %d", ret);
319     return ret;
320   }
321
322   fb.set_release_fence_fd(ret);
323   display_comp->SignalSquashDone();
324
325   return 0;
326 }
327
328 int DrmDisplayCompositor::ApplyPreComposite(
329     DrmDisplayComposition *display_comp) {
330   int ret = 0;
331
332   DrmFramebuffer &fb = framebuffers_[framebuffer_index_];
333   ret = PrepareFramebuffer(fb, display_comp);
334   if (ret) {
335     ALOGE("Failed to prepare framebuffer for pre-composite %d", ret);
336     return ret;
337   }
338
339   std::vector<DrmCompositionRegion> &regions = display_comp->pre_comp_regions();
340   if (pre_compositor_) {
341     ret = pre_compositor_->Composite(display_comp->layers().data(),
342                                    regions.data(), regions.size(), fb.buffer(),
343                                    display_comp->importer());
344     pre_compositor_->Finish();
345
346     if (ret) {
347       ALOGE("Failed to pre-composite layers");
348       return ret;
349     }
350   }
351
352   ret = display_comp->CreateNextTimelineFence();
353   if (ret <= 0) {
354     ALOGE("Failed to create pre-composite framebuffer release fence %d", ret);
355     return ret;
356   }
357
358   fb.set_release_fence_fd(ret);
359   display_comp->SignalPreCompDone();
360
361   return 0;
362 }
363
364 int DrmDisplayCompositor::DisablePlanes(DrmDisplayComposition *display_comp) {
365   drmModeAtomicReqPtr pset = drmModeAtomicAlloc();
366   if (!pset) {
367     ALOGE("Failed to allocate property set");
368     return -ENOMEM;
369   }
370
371   int ret;
372   std::vector<DrmCompositionPlane> &comp_planes =
373       display_comp->composition_planes();
374   for (DrmCompositionPlane &comp_plane : comp_planes) {
375     DrmPlane *plane = comp_plane.plane();
376     ret = drmModeAtomicAddProperty(pset, plane->id(),
377                                    plane->crtc_property().id(), 0) < 0 ||
378           drmModeAtomicAddProperty(pset, plane->id(), plane->fb_property().id(),
379                                    0) < 0;
380     if (ret) {
381       ALOGE("Failed to add plane %d disable to pset", plane->id());
382       drmModeAtomicFree(pset);
383       return ret;
384     }
385   }
386
387   ret = drmModeAtomicCommit(drm_->fd(), pset, 0, drm_);
388   if (ret) {
389     ALOGE("Failed to commit pset ret=%d\n", ret);
390     drmModeAtomicFree(pset);
391     return ret;
392   }
393
394   drmModeAtomicFree(pset);
395   return 0;
396 }
397
398 int DrmDisplayCompositor::PrepareFrame(DrmDisplayComposition *display_comp) {
399   int ret = 0;
400
401   std::vector<DrmHwcLayer> &layers = display_comp->layers();
402   std::vector<DrmCompositionPlane> &comp_planes =
403       display_comp->composition_planes();
404   std::vector<DrmCompositionRegion> &squash_regions =
405       display_comp->squash_regions();
406   std::vector<DrmCompositionRegion> &pre_comp_regions =
407       display_comp->pre_comp_regions();
408
409   int squash_layer_index = -1;
410   if (squash_regions.size() > 0) {
411     squash_framebuffer_index_ = (squash_framebuffer_index_ + 1) % 2;
412     ret = ApplySquash(display_comp);
413     if (ret)
414       return ret;
415
416     squash_layer_index = layers.size() - 1;
417   } else {
418     if (UsesSquash(comp_planes)) {
419       DrmFramebuffer &fb = squash_framebuffers_[squash_framebuffer_index_];
420       layers.emplace_back();
421       squash_layer_index = layers.size() - 1;
422       DrmHwcLayer &squash_layer = layers.back();
423       ret = squash_layer.buffer.ImportBuffer(fb.buffer()->handle,
424                                              display_comp->importer());
425       if (ret) {
426         ALOGE("Failed to import old squashed framebuffer %d", ret);
427         return ret;
428       }
429       squash_layer.sf_handle = fb.buffer()->handle;
430       squash_layer.blending = DrmHwcBlending::kPreMult;
431       squash_layer.source_crop = DrmHwcRect<float>(
432           0, 0, squash_layer.buffer->width, squash_layer.buffer->height);
433       squash_layer.display_frame = DrmHwcRect<int>(
434           0, 0, squash_layer.buffer->width, squash_layer.buffer->height);
435       ret = display_comp->CreateNextTimelineFence();
436
437       if (ret <= 0) {
438         ALOGE("Failed to create squash framebuffer release fence %d", ret);
439         return ret;
440       }
441
442       fb.set_release_fence_fd(ret);
443       ret = 0;
444     }
445   }
446
447   bool do_pre_comp = pre_comp_regions.size() > 0;
448   int pre_comp_layer_index = -1;
449   if (do_pre_comp) {
450     ret = ApplyPreComposite(display_comp);
451     if (ret)
452       return ret;
453
454     pre_comp_layer_index = layers.size() - 1;
455     framebuffer_index_ = (framebuffer_index_ + 1) % DRM_DISPLAY_BUFFERS;
456   }
457
458   for (DrmCompositionPlane &comp_plane : comp_planes) {
459     std::vector<size_t> &source_layers = comp_plane.source_layers();
460     switch (comp_plane.type()) {
461       case DrmCompositionPlane::Type::kSquash:
462         if (source_layers.size())
463           ALOGE("Squash source_layers is expected to be empty (%zu/%d)",
464                 source_layers[0], squash_layer_index);
465         source_layers.push_back(squash_layer_index);
466         break;
467       case DrmCompositionPlane::Type::kPrecomp:
468         if (!do_pre_comp) {
469           ALOGE(
470               "Can not use pre composite framebuffer with no pre composite "
471               "regions");
472           return -EINVAL;
473         }
474         // Replace source_layers with the output of the precomposite
475         source_layers.clear();
476         source_layers.push_back(pre_comp_layer_index);
477         break;
478       default:
479         break;
480     }
481   }
482
483   return ret;
484 }
485
486 int DrmDisplayCompositor::CommitFrame(DrmDisplayComposition *display_comp,
487                                       bool test_only) {
488   ATRACE_CALL();
489
490   int ret = 0;
491
492   std::vector<DrmHwcLayer> &layers = display_comp->layers();
493   std::vector<DrmCompositionPlane> &comp_planes =
494       display_comp->composition_planes();
495   uint64_t out_fences[drm_->crtcs().size()];
496
497   DrmConnector *connector = drm_->GetConnectorForDisplay(display_);
498   if (!connector) {
499     ALOGE("Could not locate connector for display %d", display_);
500     return -ENODEV;
501   }
502   DrmCrtc *crtc = drm_->GetCrtcForDisplay(display_);
503   if (!crtc) {
504     ALOGE("Could not locate crtc for display %d", display_);
505     return -ENODEV;
506   }
507
508   drmModeAtomicReqPtr pset = drmModeAtomicAlloc();
509   if (!pset) {
510     ALOGE("Failed to allocate property set");
511     return -ENOMEM;
512   }
513
514   if (crtc->out_fence_ptr_property().id() != 0) {
515     ret = drmModeAtomicAddProperty(pset, crtc->id(), crtc->out_fence_ptr_property().id(),
516                                    (uint64_t) &out_fences[crtc->pipe()]);
517     if (ret < 0) {
518       ALOGE("Failed to add OUT_FENCE_PTR property to pset: %d", ret);
519       drmModeAtomicFree(pset);
520       return ret;
521     }
522   }
523
524   if (mode_.needs_modeset) {
525     ret = drmModeAtomicAddProperty(pset, crtc->id(), crtc->active_property().id(), 1);
526     if (ret < 0) {
527       ALOGE("Failed to add crtc active to pset\n");
528       drmModeAtomicFree(pset);
529       return ret;
530     }
531
532     ret = drmModeAtomicAddProperty(pset, crtc->id(), crtc->mode_property().id(),
533                                    mode_.blob_id) < 0 ||
534           drmModeAtomicAddProperty(pset, connector->id(),
535                                    connector->crtc_id_property().id(),
536                                    crtc->id()) < 0;
537     if (ret) {
538       ALOGE("Failed to add blob %d to pset", mode_.blob_id);
539       drmModeAtomicFree(pset);
540       return ret;
541     }
542   }
543
544   for (DrmCompositionPlane &comp_plane : comp_planes) {
545     DrmPlane *plane = comp_plane.plane();
546     DrmCrtc *crtc = comp_plane.crtc();
547     std::vector<size_t> &source_layers = comp_plane.source_layers();
548
549     int fb_id = -1;
550     int fence_fd = -1;
551     DrmHwcRect<int> display_frame;
552     DrmHwcRect<float> source_crop;
553     uint64_t rotation = 0;
554     uint64_t alpha = 0xFF;
555
556     if (comp_plane.type() != DrmCompositionPlane::Type::kDisable) {
557       if (source_layers.size() > 1) {
558         ALOGE("Can't handle more than one source layer sz=%zu type=%d",
559               source_layers.size(), comp_plane.type());
560         continue;
561       }
562
563       if (source_layers.empty() || source_layers.front() >= layers.size()) {
564         ALOGE("Source layer index %zu out of bounds %zu type=%d",
565               source_layers.front(), layers.size(), comp_plane.type());
566         break;
567       }
568       DrmHwcLayer &layer = layers[source_layers.front()];
569       if (!layer.buffer) {
570         ALOGE("Expected a valid framebuffer for pset");
571         break;
572       }
573       fb_id = layer.buffer->fb_id;
574       fence_fd = layer.acquire_fence.get();
575       display_frame = layer.display_frame;
576       source_crop = layer.source_crop;
577       if (layer.blending == DrmHwcBlending::kPreMult)
578         alpha = layer.alpha;
579
580       rotation = 0;
581       if (layer.transform & DrmHwcTransform::kFlipH)
582         rotation |= DRM_MODE_REFLECT_X;
583       if (layer.transform & DrmHwcTransform::kFlipV)
584         rotation |= DRM_MODE_REFLECT_Y;
585       if (layer.transform & DrmHwcTransform::kRotate90)
586         rotation |= DRM_MODE_ROTATE_90;
587       else if (layer.transform & DrmHwcTransform::kRotate180)
588         rotation |= DRM_MODE_ROTATE_180;
589       else if (layer.transform & DrmHwcTransform::kRotate270)
590         rotation |= DRM_MODE_ROTATE_270;
591       else
592         rotation |= DRM_MODE_ROTATE_0;
593
594       if (fence_fd >= 0) {
595         int prop_id = plane->in_fence_fd_property().id();
596         if (prop_id == 0) {
597                 ALOGE("Failed to get IN_FENCE_FD property id");
598                 break;
599         }
600         ret = drmModeAtomicAddProperty(pset, plane->id(), prop_id, fence_fd);
601         if (ret < 0) {
602           ALOGE("Failed to add IN_FENCE_FD property to pset: %d", ret);
603           break;
604         }
605       }
606     }
607
608     // Disable the plane if there's no framebuffer
609     if (fb_id < 0) {
610       ret = drmModeAtomicAddProperty(pset, plane->id(),
611                                      plane->crtc_property().id(), 0) < 0 ||
612             drmModeAtomicAddProperty(pset, plane->id(),
613                                      plane->fb_property().id(), 0) < 0;
614       if (ret) {
615         ALOGE("Failed to add plane %d disable to pset", plane->id());
616         break;
617       }
618       continue;
619     }
620
621     // TODO: Once we have atomic test, this should fall back to GL
622     if (rotation != DRM_MODE_ROTATE_0 && plane->rotation_property().id() == 0) {
623       ALOGE("Rotation is not supported on plane %d", plane->id());
624       ret = -EINVAL;
625       break;
626     }
627
628     // TODO: Once we have atomic test, this should fall back to GL
629     if (alpha != 0xFF && plane->alpha_property().id() == 0) {
630       ALOGE("Alpha is not supported on plane %d", plane->id());
631       ret = -EINVAL;
632       break;
633     }
634
635     ret = drmModeAtomicAddProperty(pset, plane->id(),
636                                    plane->crtc_property().id(), crtc->id()) < 0;
637     ret |= drmModeAtomicAddProperty(pset, plane->id(),
638                                     plane->fb_property().id(), fb_id) < 0;
639     ret |= drmModeAtomicAddProperty(pset, plane->id(),
640                                     plane->crtc_x_property().id(),
641                                     display_frame.left) < 0;
642     ret |= drmModeAtomicAddProperty(pset, plane->id(),
643                                     plane->crtc_y_property().id(),
644                                     display_frame.top) < 0;
645     ret |= drmModeAtomicAddProperty(
646                pset, plane->id(), plane->crtc_w_property().id(),
647                display_frame.right - display_frame.left) < 0;
648     ret |= drmModeAtomicAddProperty(
649                pset, plane->id(), plane->crtc_h_property().id(),
650                display_frame.bottom - display_frame.top) < 0;
651     ret |= drmModeAtomicAddProperty(pset, plane->id(),
652                                     plane->src_x_property().id(),
653                                     (int)(source_crop.left) << 16) < 0;
654     ret |= drmModeAtomicAddProperty(pset, plane->id(),
655                                     plane->src_y_property().id(),
656                                     (int)(source_crop.top) << 16) < 0;
657     ret |= drmModeAtomicAddProperty(
658                pset, plane->id(), plane->src_w_property().id(),
659                (int)(source_crop.right - source_crop.left) << 16) < 0;
660     ret |= drmModeAtomicAddProperty(
661                pset, plane->id(), plane->src_h_property().id(),
662                (int)(source_crop.bottom - source_crop.top) << 16) < 0;
663     if (ret) {
664       ALOGE("Failed to add plane %d to set", plane->id());
665       break;
666     }
667
668     if (plane->rotation_property().id()) {
669       ret = drmModeAtomicAddProperty(pset, plane->id(),
670                                      plane->rotation_property().id(),
671                                      rotation) < 0;
672       if (ret) {
673         ALOGE("Failed to add rotation property %d to plane %d",
674               plane->rotation_property().id(), plane->id());
675         break;
676       }
677     }
678
679     if (plane->alpha_property().id()) {
680       ret = drmModeAtomicAddProperty(pset, plane->id(),
681                                      plane->alpha_property().id(),
682                                      alpha) < 0;
683       if (ret) {
684         ALOGE("Failed to add alpha property %d to plane %d",
685               plane->alpha_property().id(), plane->id());
686         break;
687       }
688     }
689   }
690
691   if (!ret) {
692     uint32_t flags = DRM_MODE_ATOMIC_ALLOW_MODESET;
693     if (test_only)
694       flags |= DRM_MODE_ATOMIC_TEST_ONLY;
695
696     ret = drmModeAtomicCommit(drm_->fd(), pset, flags, drm_);
697     if (ret) {
698       if (test_only)
699         ALOGI("Commit test pset failed ret=%d\n", ret);
700       else
701         ALOGE("Failed to commit pset ret=%d\n", ret);
702       drmModeAtomicFree(pset);
703       return ret;
704     }
705   }
706   if (pset)
707     drmModeAtomicFree(pset);
708
709   if (!test_only && mode_.needs_modeset) {
710     ret = drm_->DestroyPropertyBlob(mode_.old_blob_id);
711     if (ret) {
712       ALOGE("Failed to destroy old mode property blob %" PRIu32 "/%d",
713             mode_.old_blob_id, ret);
714       return ret;
715     }
716
717     /* TODO: Add dpms to the pset when the kernel supports it */
718     ret = ApplyDpms(display_comp);
719     if (ret) {
720       ALOGE("Failed to apply DPMS after modeset %d\n", ret);
721       return ret;
722     }
723
724     connector->set_active_mode(mode_.mode);
725     mode_.old_blob_id = mode_.blob_id;
726     mode_.blob_id = 0;
727     mode_.needs_modeset = false;
728   }
729
730   if (crtc->out_fence_ptr_property().id()) {
731     display_comp->set_out_fence((int) out_fences[crtc->pipe()]);
732   }
733
734   return ret;
735 }
736
737 int DrmDisplayCompositor::ApplyDpms(DrmDisplayComposition *display_comp) {
738   DrmConnector *conn = drm_->GetConnectorForDisplay(display_);
739   if (!conn) {
740     ALOGE("Failed to get DrmConnector for display %d", display_);
741     return -ENODEV;
742   }
743
744   const DrmProperty &prop = conn->dpms_property();
745   int ret = drmModeConnectorSetProperty(drm_->fd(), conn->id(), prop.id(),
746                                         display_comp->dpms_mode());
747   if (ret) {
748     ALOGE("Failed to set DPMS property for connector %d", conn->id());
749     return ret;
750   }
751   return 0;
752 }
753
754 std::tuple<int, uint32_t> DrmDisplayCompositor::CreateModeBlob(
755     const DrmMode &mode) {
756   struct drm_mode_modeinfo drm_mode;
757   memset(&drm_mode, 0, sizeof(drm_mode));
758   mode.ToDrmModeModeInfo(&drm_mode);
759
760   uint32_t id = 0;
761   int ret = drm_->CreatePropertyBlob(&drm_mode,
762                                      sizeof(struct drm_mode_modeinfo), &id);
763   if (ret) {
764     ALOGE("Failed to create mode property blob %d", ret);
765     return std::make_tuple(ret, 0);
766   }
767   ALOGE("Create blob_id %" PRIu32 "\n", id);
768   return std::make_tuple(ret, id);
769 }
770
771 void DrmDisplayCompositor::ClearDisplay() {
772   AutoLock lock(&lock_, "compositor");
773   int ret = lock.Lock();
774   if (ret)
775     return;
776
777   if (!active_composition_)
778     return;
779
780   if (DisablePlanes(active_composition_.get()))
781     return;
782
783   active_composition_->SignalCompositionDone();
784
785   active_composition_.reset(NULL);
786 }
787
788 void DrmDisplayCompositor::ApplyFrame(
789     std::unique_ptr<DrmDisplayComposition> composition, int status) {
790   int ret = status;
791
792   if (!ret)
793     ret = CommitFrame(composition.get(), false);
794
795   if (ret) {
796     ALOGE("Composite failed for display %d", display_);
797     // Disable the hw used by the last active composition. This allows us to
798     // signal the release fences from that composition to avoid hanging.
799     ClearDisplay();
800     return;
801   }
802   ++dump_frames_composited_;
803
804   if (active_composition_)
805     active_composition_->SignalCompositionDone();
806
807   ret = pthread_mutex_lock(&lock_);
808   if (ret)
809     ALOGE("Failed to acquire lock for active_composition swap");
810
811   active_composition_.swap(composition);
812
813   if (!ret)
814     ret = pthread_mutex_unlock(&lock_);
815   if (ret)
816     ALOGE("Failed to release lock for active_composition swap");
817 }
818
819 int DrmDisplayCompositor::ApplyComposition(
820     std::unique_ptr<DrmDisplayComposition> composition) {
821   int ret = 0;
822   switch (composition->type()) {
823     case DRM_COMPOSITION_TYPE_FRAME:
824       ret = PrepareFrame(composition.get());
825       if (ret) {
826         ALOGE("Failed to prepare frame for display %d", display_);
827         return ret;
828       }
829       if (composition->geometry_changed()) {
830         // Send the composition to the kernel to ensure we can commit it. This
831         // is just a test, it won't actually commit the frame. If rejected,
832         // squash the frame into one layer and use the squashed composition
833         ret = CommitFrame(composition.get(), true);
834         if (ret)
835           ALOGI("Commit test failed, squashing frame for display %d", display_);
836         use_hw_overlays_ = !ret;
837       }
838
839       // If use_hw_overlays_ is false, we can't use hardware to composite the
840       // frame. So squash all layers into a single composition and apply that
841       // instead.
842       if (!use_hw_overlays_) {
843         std::unique_ptr<DrmDisplayComposition> squashed = CreateComposition();
844         ret = SquashFrame(composition.get(), squashed.get());
845         if (!ret) {
846           composition = std::move(squashed);
847         } else {
848           ALOGE("Failed to squash frame for display %d", display_);
849           // Disable the hw used by the last active composition. This allows us
850           // to signal the release fences from that composition to avoid
851           // hanging.
852           ClearDisplay();
853           return ret;
854         }
855       }
856       ApplyFrame(std::move(composition), ret);
857       break;
858     case DRM_COMPOSITION_TYPE_DPMS:
859       active_ = (composition->dpms_mode() == DRM_MODE_DPMS_ON);
860       ret = ApplyDpms(composition.get());
861       if (ret)
862         ALOGE("Failed to apply dpms for display %d", display_);
863       return ret;
864     case DRM_COMPOSITION_TYPE_MODESET:
865       mode_.mode = composition->display_mode();
866       if (mode_.blob_id)
867         drm_->DestroyPropertyBlob(mode_.blob_id);
868       std::tie(ret, mode_.blob_id) = CreateModeBlob(mode_.mode);
869       if (ret) {
870         ALOGE("Failed to create mode blob for display %d", display_);
871         return ret;
872       }
873       mode_.needs_modeset = true;
874       return 0;
875     default:
876       ALOGE("Unknown composition type %d", composition->type());
877       return -EINVAL;
878   }
879
880   return ret;
881 }
882
883 int DrmDisplayCompositor::SquashAll() {
884   AutoLock lock(&lock_, "compositor");
885   int ret = lock.Lock();
886   if (ret)
887     return ret;
888
889   if (!active_composition_)
890     return 0;
891
892   std::unique_ptr<DrmDisplayComposition> comp = CreateComposition();
893   ret = SquashFrame(active_composition_.get(), comp.get());
894
895   // ApplyFrame needs the lock
896   lock.Unlock();
897
898   if (!ret)
899     ApplyFrame(std::move(comp), 0);
900
901   return ret;
902 }
903
904 // Returns:
905 //   - 0 if src is successfully squashed into dst
906 //   - -EALREADY if the src is already squashed
907 //   - Appropriate error if the squash fails
908 int DrmDisplayCompositor::SquashFrame(DrmDisplayComposition *src,
909                                       DrmDisplayComposition *dst) {
910   if (src->type() != DRM_COMPOSITION_TYPE_FRAME)
911     return -ENOTSUP;
912
913   std::vector<DrmCompositionPlane> &src_planes = src->composition_planes();
914   std::vector<DrmHwcLayer> &src_layers = src->layers();
915
916   // Make sure there is more than one layer to squash.
917   size_t src_planes_with_layer = std::count_if(
918       src_planes.begin(), src_planes.end(), [](DrmCompositionPlane &p) {
919         return p.type() != DrmCompositionPlane::Type::kDisable;
920       });
921   if (src_planes_with_layer <= 1)
922     return -EALREADY;
923
924   int pre_comp_layer_index;
925
926   int ret = dst->Init(drm_, src->crtc(), src->importer(), src->planner(),
927                       src->frame_no());
928   if (ret) {
929     ALOGE("Failed to init squash all composition %d", ret);
930     return ret;
931   }
932
933   DrmCompositionPlane squashed_comp(DrmCompositionPlane::Type::kPrecomp, NULL,
934                                     src->crtc());
935   std::vector<DrmHwcLayer> dst_layers;
936   for (DrmCompositionPlane &comp_plane : src_planes) {
937     // Composition planes without DRM planes should never happen
938     if (comp_plane.plane() == NULL) {
939       ALOGE("Skipping squash all because of NULL plane");
940       ret = -EINVAL;
941       goto move_layers_back;
942     }
943
944     if (comp_plane.plane()->type() == DRM_PLANE_TYPE_PRIMARY)
945       squashed_comp.set_plane(comp_plane.plane());
946     else
947       dst->AddPlaneDisable(comp_plane.plane());
948
949     if (comp_plane.type() == DrmCompositionPlane::Type::kDisable)
950       continue;
951
952     for (auto i : comp_plane.source_layers()) {
953       DrmHwcLayer &layer = src_layers[i];
954
955       // Squashing protected layers is impossible.
956       if (layer.protected_usage()) {
957         ret = -ENOTSUP;
958         goto move_layers_back;
959       }
960
961       // The OutputFds point to freed memory after hwc_set returns. They are
962       // returned to the default to prevent DrmDisplayComposition::Plan from
963       // filling the OutputFds.
964       layer.release_fence = OutputFd();
965       dst_layers.emplace_back(std::move(layer));
966       squashed_comp.source_layers().push_back(
967           squashed_comp.source_layers().size());
968     }
969   }
970
971   if (squashed_comp.plane() == NULL) {
972     ALOGE("Primary plane not found for squash");
973     ret = -ENOTSUP;
974     goto move_layers_back;
975   }
976
977   ret = dst->SetLayers(dst_layers.data(), dst_layers.size(), false);
978   if (ret) {
979     ALOGE("Failed to set layers for squash all composition %d", ret);
980     goto move_layers_back;
981   }
982
983   ret = dst->AddPlaneComposition(std::move(squashed_comp));
984   if (ret) {
985     ALOGE("Failed to add squashed plane composition %d", ret);
986     goto move_layers_back;
987   }
988
989   ret = dst->FinalizeComposition();
990   if (ret) {
991     ALOGE("Failed to plan for squash all composition %d", ret);
992     goto move_layers_back;
993   }
994
995   ret = ApplyPreComposite(dst);
996   if (ret) {
997     ALOGE("Failed to pre-composite for squash all composition %d", ret);
998     goto move_layers_back;
999   }
1000
1001   pre_comp_layer_index = dst->layers().size() - 1;
1002   framebuffer_index_ = (framebuffer_index_ + 1) % DRM_DISPLAY_BUFFERS;
1003
1004   for (DrmCompositionPlane &plane : dst->composition_planes()) {
1005     if (plane.type() == DrmCompositionPlane::Type::kPrecomp) {
1006       // Replace source_layers with the output of the precomposite
1007       plane.source_layers().clear();
1008       plane.source_layers().push_back(pre_comp_layer_index);
1009       break;
1010     }
1011   }
1012
1013   return 0;
1014
1015 // TODO(zachr): think of a better way to transfer ownership back to the active
1016 // composition.
1017 move_layers_back:
1018   for (size_t plane_index = 0;
1019        plane_index < src_planes.size() && plane_index < dst_layers.size();) {
1020     if (src_planes[plane_index].source_layers().empty()) {
1021       plane_index++;
1022       continue;
1023     }
1024     for (auto i : src_planes[plane_index].source_layers())
1025       src_layers[i] = std::move(dst_layers[plane_index++]);
1026   }
1027
1028   return ret;
1029 }
1030
1031 void DrmDisplayCompositor::Dump(std::ostringstream *out) const {
1032   int ret = pthread_mutex_lock(&lock_);
1033   if (ret)
1034     return;
1035
1036   uint64_t num_frames = dump_frames_composited_;
1037   dump_frames_composited_ = 0;
1038
1039   struct timespec ts;
1040   ret = clock_gettime(CLOCK_MONOTONIC, &ts);
1041   if (ret) {
1042     pthread_mutex_unlock(&lock_);
1043     return;
1044   }
1045
1046   uint64_t cur_ts = ts.tv_sec * 1000 * 1000 * 1000 + ts.tv_nsec;
1047   uint64_t num_ms = (cur_ts - dump_last_timestamp_ns_) / (1000 * 1000);
1048   float fps = num_ms ? (num_frames * 1000.0f) / (num_ms) : 0.0f;
1049
1050   *out << "--DrmDisplayCompositor[" << display_
1051        << "]: num_frames=" << num_frames << " num_ms=" << num_ms
1052        << " fps=" << fps << "\n";
1053
1054   dump_last_timestamp_ns_ = cur_ts;
1055
1056   if (active_composition_)
1057     active_composition_->Dump(out);
1058
1059   squash_state_.Dump(out);
1060
1061   pthread_mutex_unlock(&lock_);
1062 }
1063 }