OSDN Git Service

drm_hwcomposer: Cleanup DRM atomic commit
[android-x86/external-drm_hwcomposer.git] / drm / DrmDevice.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 LOG_TAG "hwc-drm-device"
18
19 #include "DrmDevice.h"
20
21 #include <fcntl.h>
22 #include <xf86drm.h>
23 #include <xf86drmMode.h>
24
25 #include <algorithm>
26 #include <array>
27 #include <cerrno>
28 #include <cinttypes>
29 #include <cstdint>
30 #include <sstream>
31 #include <string>
32
33 #include "utils/log.h"
34 #include "utils/properties.h"
35
36 static void trim_left(std::string *str) {
37   str->erase(std::begin(*str),
38              std::find_if(std::begin(*str), std::end(*str),
39                           [](int ch) { return std::isspace(ch) == 0; }));
40 }
41
42 static void trim_right(std::string *str) {
43   str->erase(std::find_if(std::rbegin(*str), std::rend(*str),
44                           [](int ch) { return std::isspace(ch) == 0; })
45                  .base(),
46              std::end(*str));
47 }
48
49 static void trim(std::string *str) {
50   trim_left(str);
51   trim_right(str);
52 }
53
54 namespace android {
55
56 static std::vector<std::string> read_primary_display_order_prop() {
57   std::array<char, PROPERTY_VALUE_MAX> display_order_buf{};
58   property_get("vendor.hwc.drm.primary_display_order", display_order_buf.data(),
59                "...");
60
61   std::vector<std::string> display_order;
62   std::istringstream str(display_order_buf.data());
63   for (std::string conn_name; std::getline(str, conn_name, ',');) {
64     trim(&conn_name);
65     display_order.push_back(std::move(conn_name));
66   }
67   return display_order;
68 }
69
70 static std::vector<DrmConnector *> make_primary_display_candidates(
71     const std::vector<std::unique_ptr<DrmConnector>> &connectors) {
72   std::vector<DrmConnector *> primary_candidates;
73   std::transform(std::begin(connectors), std::end(connectors),
74                  std::back_inserter(primary_candidates),
75                  [](const std::unique_ptr<DrmConnector> &conn) {
76                    return conn.get();
77                  });
78   primary_candidates.erase(std::remove_if(std::begin(primary_candidates),
79                                           std::end(primary_candidates),
80                                           [](const DrmConnector *conn) {
81                                             return conn->state() !=
82                                                    DRM_MODE_CONNECTED;
83                                           }),
84                            std::end(primary_candidates));
85
86   std::vector<std::string> display_order = read_primary_display_order_prop();
87   bool use_other = display_order.back() == "...";
88
89   // putting connectors from primary_display_order first
90   auto curr_connector = std::begin(primary_candidates);
91   for (const std::string &display_name : display_order) {
92     auto it = std::find_if(std::begin(primary_candidates),
93                            std::end(primary_candidates),
94                            [&display_name](const DrmConnector *conn) {
95                              return conn->name() == display_name;
96                            });
97     if (it != std::end(primary_candidates)) {
98       std::iter_swap(it, curr_connector);
99       ++curr_connector;
100     }
101   }
102
103   if (use_other) {
104     // then putting internal connectors second, everything else afterwards
105     std::partition(curr_connector, std::end(primary_candidates),
106                    [](const DrmConnector *conn) { return conn->internal(); });
107   } else {
108     primary_candidates.erase(curr_connector, std::end(primary_candidates));
109   }
110
111   return primary_candidates;
112 }
113
114 DrmDevice::DrmDevice() : event_listener_(this) {
115   self.reset(this);
116   mDrmFbImporter = std::make_unique<DrmFbImporter>(self);
117 }
118
119 DrmDevice::~DrmDevice() {
120   event_listener_.Exit();
121 }
122
123 std::tuple<int, int> DrmDevice::Init(const char *path, int num_displays) {
124   /* TODO: Use drmOpenControl here instead */
125   fd_ = UniqueFd(open(path, O_RDWR | O_CLOEXEC));
126   if (fd() < 0) {
127     ALOGE("Failed to open dri %s: %s", path, strerror(errno));
128     return std::make_tuple(-ENODEV, 0);
129   }
130
131   int ret = drmSetClientCap(fd(), DRM_CLIENT_CAP_UNIVERSAL_PLANES, 1);
132   if (ret) {
133     ALOGE("Failed to set universal plane cap %d", ret);
134     return std::make_tuple(ret, 0);
135   }
136
137   ret = drmSetClientCap(fd(), DRM_CLIENT_CAP_ATOMIC, 1);
138   if (ret) {
139     ALOGE("Failed to set atomic cap %d", ret);
140     return std::make_tuple(ret, 0);
141   }
142
143 #ifdef DRM_CLIENT_CAP_WRITEBACK_CONNECTORS
144   ret = drmSetClientCap(fd(), DRM_CLIENT_CAP_WRITEBACK_CONNECTORS, 1);
145   if (ret) {
146     ALOGI("Failed to set writeback cap %d", ret);
147     ret = 0;
148   }
149 #endif
150
151   uint64_t cap_value = 0;
152   if (drmGetCap(fd(), DRM_CAP_ADDFB2_MODIFIERS, &cap_value)) {
153     ALOGW("drmGetCap failed. Fallback to no modifier support.");
154     cap_value = 0;
155   }
156   HasAddFb2ModifiersSupport_ = cap_value != 0;
157
158   drmSetMaster(fd());
159   if (!drmIsMaster(fd())) {
160     ALOGE("DRM/KMS master access required");
161     return std::make_tuple(-EACCES, 0);
162   }
163
164   auto res = MakeDrmModeResUnique(fd());
165   if (!res) {
166     ALOGE("Failed to get DrmDevice resources");
167     return std::make_tuple(-ENODEV, 0);
168   }
169
170   min_resolution_ = std::pair<uint32_t, uint32_t>(res->min_width,
171                                                   res->min_height);
172   max_resolution_ = std::pair<uint32_t, uint32_t>(res->max_width,
173                                                   res->max_height);
174
175   // Assumes that the primary display will always be in the first
176   // drm_device opened.
177   bool found_primary = num_displays != 0;
178
179   for (int i = 0; !ret && i < res->count_crtcs; ++i) {
180     auto c = MakeDrmModeCrtcUnique(fd(), res->crtcs[i]);
181     if (!c) {
182       ALOGE("Failed to get crtc %d", res->crtcs[i]);
183       ret = -ENODEV;
184       break;
185     }
186
187     std::unique_ptr<DrmCrtc> crtc(new DrmCrtc(this, c.get(), i));
188
189     ret = crtc->Init();
190     if (ret) {
191       ALOGE("Failed to initialize crtc %d", res->crtcs[i]);
192       break;
193     }
194     crtcs_.emplace_back(std::move(crtc));
195   }
196
197   std::vector<uint32_t> possible_clones;
198   for (int i = 0; !ret && i < res->count_encoders; ++i) {
199     auto e = MakeDrmModeEncoderUnique(fd(), res->encoders[i]);
200     if (!e) {
201       ALOGE("Failed to get encoder %d", res->encoders[i]);
202       ret = -ENODEV;
203       break;
204     }
205
206     std::vector<DrmCrtc *> possible_crtcs;
207     DrmCrtc *current_crtc = nullptr;
208     for (auto &crtc : crtcs_) {
209       if ((1 << crtc->pipe()) & e->possible_crtcs)
210         possible_crtcs.push_back(crtc.get());
211
212       if (crtc->id() == e->crtc_id)
213         current_crtc = crtc.get();
214     }
215
216     std::unique_ptr<DrmEncoder> enc(
217         new DrmEncoder(e.get(), current_crtc, possible_crtcs));
218     possible_clones.push_back(e->possible_clones);
219
220     encoders_.emplace_back(std::move(enc));
221   }
222
223   for (unsigned int i = 0; i < encoders_.size(); i++) {
224     for (unsigned int j = 0; j < encoders_.size(); j++)
225       if (possible_clones[i] & (1 << j))
226         encoders_[i]->AddPossibleClone(encoders_[j].get());
227   }
228
229   for (int i = 0; !ret && i < res->count_connectors; ++i) {
230     auto c = MakeDrmModeConnectorUnique(fd(), res->connectors[i]);
231     if (!c) {
232       ALOGE("Failed to get connector %d", res->connectors[i]);
233       ret = -ENODEV;
234       break;
235     }
236
237     std::vector<DrmEncoder *> possible_encoders;
238     DrmEncoder *current_encoder = nullptr;
239     for (int j = 0; j < c->count_encoders; ++j) {
240       for (auto &encoder : encoders_) {
241         if (encoder->id() == c->encoders[j])
242           possible_encoders.push_back(encoder.get());
243         if (encoder->id() == c->encoder_id)
244           current_encoder = encoder.get();
245       }
246     }
247
248     std::unique_ptr<DrmConnector> conn(
249         new DrmConnector(this, c.get(), current_encoder, possible_encoders));
250
251     ret = conn->Init();
252     if (ret) {
253       ALOGE("Init connector %d failed", res->connectors[i]);
254       break;
255     }
256
257     if (conn->writeback())
258       writeback_connectors_.emplace_back(std::move(conn));
259     else
260       connectors_.emplace_back(std::move(conn));
261   }
262
263   // Primary display priority:
264   // 1) vendor.hwc.drm.primary_display_order property
265   // 2) internal connectors
266   // 3) anything else
267   std::vector<DrmConnector *>
268       primary_candidates = make_primary_display_candidates(connectors_);
269   if (!primary_candidates.empty() && !found_primary) {
270     DrmConnector &conn = **std::begin(primary_candidates);
271     conn.set_display(num_displays);
272     displays_[num_displays] = num_displays;
273     ++num_displays;
274     found_primary = true;
275   } else {
276     ALOGE(
277         "Failed to find primary display from "
278         "\"vendor.hwc.drm.primary_display_order\" property");
279   }
280
281   // If no priority display were found then pick first available as primary and
282   // for the others assign consecutive display_numbers.
283   for (auto &conn : connectors_) {
284     if (conn->external() || conn->internal()) {
285       if (!found_primary) {
286         conn->set_display(num_displays);
287         displays_[num_displays] = num_displays;
288         found_primary = true;
289         ++num_displays;
290       } else if (conn->display() < 0) {
291         conn->set_display(num_displays);
292         displays_[num_displays] = num_displays;
293         ++num_displays;
294       }
295     }
296   }
297
298   // Catch-all for the above loops
299   if (ret)
300     return std::make_tuple(ret, 0);
301
302   auto plane_res = MakeDrmModePlaneResUnique(fd());
303   if (!plane_res) {
304     ALOGE("Failed to get plane resources");
305     return std::make_tuple(-ENOENT, 0);
306   }
307
308   for (uint32_t i = 0; i < plane_res->count_planes; ++i) {
309     auto p = MakeDrmModePlaneUnique(fd(), plane_res->planes[i]);
310     if (!p) {
311       ALOGE("Failed to get plane %d", plane_res->planes[i]);
312       ret = -ENODEV;
313       break;
314     }
315
316     std::unique_ptr<DrmPlane> plane(new DrmPlane(this, p.get()));
317
318     ret = plane->Init();
319     if (ret) {
320       ALOGE("Init plane %d failed", plane_res->planes[i]);
321       break;
322     }
323
324     planes_.emplace_back(std::move(plane));
325   }
326   if (ret)
327     return std::make_tuple(ret, 0);
328
329   ret = event_listener_.Init();
330   if (ret) {
331     ALOGE("Can't initialize event listener %d", ret);
332     return std::make_tuple(ret, 0);
333   }
334
335   for (auto &conn : connectors_) {
336     ret = CreateDisplayPipe(conn.get());
337     if (ret) {
338       ALOGE("Failed CreateDisplayPipe %d with %d", conn->id(), ret);
339       return std::make_tuple(ret, 0);
340     }
341     if (!AttachWriteback(conn.get())) {
342       ALOGI("Display %d has writeback attach to it", conn->display());
343     }
344   }
345   return std::make_tuple(ret, displays_.size());
346 }
347
348 bool DrmDevice::HandlesDisplay(int display) const {
349   return displays_.find(display) != displays_.end();
350 }
351
352 DrmConnector *DrmDevice::GetConnectorForDisplay(int display) const {
353   for (const auto &conn : connectors_) {
354     if (conn->display() == display)
355       return conn.get();
356   }
357   return nullptr;
358 }
359
360 DrmConnector *DrmDevice::GetWritebackConnectorForDisplay(int display) const {
361   for (const auto &conn : writeback_connectors_) {
362     if (conn->display() == display)
363       return conn.get();
364   }
365   return nullptr;
366 }
367
368 // TODO(nobody): what happens when hotplugging
369 DrmConnector *DrmDevice::AvailableWritebackConnector(int display) const {
370   DrmConnector *writeback_conn = GetWritebackConnectorForDisplay(display);
371   DrmConnector *display_conn = GetConnectorForDisplay(display);
372   // If we have a writeback already attached to the same CRTC just use that,
373   // if possible.
374   if (display_conn && writeback_conn &&
375       writeback_conn->encoder()->CanClone(display_conn->encoder()))
376     return writeback_conn;
377
378   // Use another CRTC if available and doesn't have any connector
379   for (const auto &crtc : crtcs_) {
380     if (crtc->display() == display)
381       continue;
382     display_conn = GetConnectorForDisplay(crtc->display());
383     // If we have a display connected don't use it for writeback
384     if (display_conn && display_conn->state() == DRM_MODE_CONNECTED)
385       continue;
386     writeback_conn = GetWritebackConnectorForDisplay(crtc->display());
387     if (writeback_conn)
388       return writeback_conn;
389   }
390   return nullptr;
391 }
392
393 DrmCrtc *DrmDevice::GetCrtcForDisplay(int display) const {
394   for (const auto &crtc : crtcs_) {
395     if (crtc->display() == display)
396       return crtc.get();
397   }
398   return nullptr;
399 }
400
401 DrmPlane *DrmDevice::GetPlane(uint32_t id) const {
402   for (const auto &plane : planes_) {
403     if (plane->id() == id)
404       return plane.get();
405   }
406   return nullptr;
407 }
408
409 const std::vector<std::unique_ptr<DrmCrtc>> &DrmDevice::crtcs() const {
410   return crtcs_;
411 }
412
413 uint32_t DrmDevice::next_mode_id() {
414   return ++mode_id_;
415 }
416
417 int DrmDevice::TryEncoderForDisplay(int display, DrmEncoder *enc) {
418   /* First try to use the currently-bound crtc */
419   DrmCrtc *crtc = enc->crtc();
420   if (crtc && crtc->can_bind(display)) {
421     crtc->set_display(display);
422     enc->set_crtc(crtc);
423     return 0;
424   }
425
426   /* Try to find a possible crtc which will work */
427   for (DrmCrtc *crtc : enc->possible_crtcs()) {
428     /* We've already tried this earlier */
429     if (crtc == enc->crtc())
430       continue;
431
432     if (crtc->can_bind(display)) {
433       crtc->set_display(display);
434       enc->set_crtc(crtc);
435       return 0;
436     }
437   }
438
439   /* We can't use the encoder, but nothing went wrong, try another one */
440   return -EAGAIN;
441 }
442
443 int DrmDevice::CreateDisplayPipe(DrmConnector *connector) {
444   int display = connector->display();
445   /* Try to use current setup first */
446   if (connector->encoder()) {
447     int ret = TryEncoderForDisplay(display, connector->encoder());
448     if (!ret) {
449       return 0;
450     }
451
452     if (ret != -EAGAIN) {
453       ALOGE("Could not set mode %d/%d", display, ret);
454       return ret;
455     }
456   }
457
458   for (DrmEncoder *enc : connector->possible_encoders()) {
459     int ret = TryEncoderForDisplay(display, enc);
460     if (!ret) {
461       connector->set_encoder(enc);
462       return 0;
463     }
464
465     if (ret != -EAGAIN) {
466       ALOGE("Could not set mode %d/%d", display, ret);
467       return ret;
468     }
469   }
470   ALOGE("Could not find a suitable encoder/crtc for display %d",
471         connector->display());
472   return -ENODEV;
473 }
474
475 // Attach writeback connector to the CRTC linked to the display_conn
476 int DrmDevice::AttachWriteback(DrmConnector *display_conn) {
477   DrmCrtc *display_crtc = display_conn->encoder()->crtc();
478   if (GetWritebackConnectorForDisplay(display_crtc->display()) != nullptr) {
479     ALOGE("Display already has writeback attach to it");
480     return -EINVAL;
481   }
482   for (auto &writeback_conn : writeback_connectors_) {
483     if (writeback_conn->display() >= 0)
484       continue;
485     for (DrmEncoder *writeback_enc : writeback_conn->possible_encoders()) {
486       for (DrmCrtc *possible_crtc : writeback_enc->possible_crtcs()) {
487         if (possible_crtc != display_crtc)
488           continue;
489         // Use just encoders which had not been bound already
490         if (writeback_enc->can_bind(display_crtc->display())) {
491           writeback_enc->set_crtc(display_crtc);
492           writeback_conn->set_encoder(writeback_enc);
493           writeback_conn->set_display(display_crtc->display());
494           writeback_conn->UpdateModes();
495           return 0;
496         }
497       }
498     }
499   }
500   return -EINVAL;
501 }
502
503 int DrmDevice::CreatePropertyBlob(void *data, size_t length,
504                                   uint32_t *blob_id) const {
505   struct drm_mode_create_blob create_blob {};
506   create_blob.length = length;
507   create_blob.data = (__u64)data;
508
509   int ret = drmIoctl(fd(), DRM_IOCTL_MODE_CREATEPROPBLOB, &create_blob);
510   if (ret) {
511     ALOGE("Failed to create mode property blob %d", ret);
512     return ret;
513   }
514   *blob_id = create_blob.blob_id;
515   return 0;
516 }
517
518 int DrmDevice::DestroyPropertyBlob(uint32_t blob_id) const {
519   if (!blob_id)
520     return 0;
521
522   struct drm_mode_destroy_blob destroy_blob {};
523   destroy_blob.blob_id = (__u32)blob_id;
524   int ret = drmIoctl(fd(), DRM_IOCTL_MODE_DESTROYPROPBLOB, &destroy_blob);
525   if (ret) {
526     ALOGE("Failed to destroy mode property blob %" PRIu32 "/%d", blob_id, ret);
527     return ret;
528   }
529   return 0;
530 }
531
532 DrmEventListener *DrmDevice::event_listener() {
533   return &event_listener_;
534 }
535
536 int DrmDevice::GetProperty(uint32_t obj_id, uint32_t obj_type,
537                            const char *prop_name, DrmProperty *property) const {
538   drmModeObjectPropertiesPtr props = nullptr;
539
540   props = drmModeObjectGetProperties(fd(), obj_id, obj_type);
541   if (!props) {
542     ALOGE("Failed to get properties for %d/%x", obj_id, obj_type);
543     return -ENODEV;
544   }
545
546   bool found = false;
547   for (int i = 0; !found && (size_t)i < props->count_props; ++i) {
548     drmModePropertyPtr p = drmModeGetProperty(fd(), props->props[i]);
549     if (!strcmp(p->name, prop_name)) {
550       property->Init(obj_id, p, props->prop_values[i]);
551       found = true;
552     }
553     drmModeFreeProperty(p);
554   }
555
556   drmModeFreeObjectProperties(props);
557   return found ? 0 : -ENOENT;
558 }
559
560 int DrmDevice::GetPlaneProperty(const DrmPlane &plane, const char *prop_name,
561                                 DrmProperty *property) {
562   return GetProperty(plane.id(), DRM_MODE_OBJECT_PLANE, prop_name, property);
563 }
564
565 int DrmDevice::GetCrtcProperty(const DrmCrtc &crtc, const char *prop_name,
566                                DrmProperty *property) {
567   return GetProperty(crtc.id(), DRM_MODE_OBJECT_CRTC, prop_name, property);
568 }
569
570 int DrmDevice::GetConnectorProperty(const DrmConnector &connector,
571                                     const char *prop_name,
572                                     DrmProperty *property) {
573   return GetProperty(connector.id(), DRM_MODE_OBJECT_CONNECTOR, prop_name,
574                      property);
575 }
576
577 std::string DrmDevice::GetName() const {
578   auto *ver = drmGetVersion(fd());
579   if (!ver) {
580     ALOGW("Failed to get drm version for fd=%d", fd());
581     return "generic";
582   }
583
584   std::string name(ver->name);
585   drmFreeVersion(ver);
586   return name;
587 }
588 }  // namespace android