• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2016 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-two"
19 
20 #include "DrmHwcTwo.h"
21 
22 #include <cutils/properties.h>
23 #include <hardware/hardware.h>
24 #include <hardware/hwcomposer2.h>
25 #include <inttypes.h>
26 #include <log/log.h>
27 
28 #include <string>
29 
30 #include "backend/BackendManager.h"
31 #include "bufferinfo/BufferInfoGetter.h"
32 #include "compositor/DrmDisplayComposition.h"
33 
34 namespace android {
35 
DrmHwcTwo()36 DrmHwcTwo::DrmHwcTwo() {
37   common.tag = HARDWARE_DEVICE_TAG;
38   common.version = HWC_DEVICE_API_VERSION_2_0;
39   common.close = HookDevClose;
40   getCapabilities = HookDevGetCapabilities;
41   getFunction = HookDevGetFunction;
42 }
43 
CreateDisplay(hwc2_display_t displ,HWC2::DisplayType type)44 HWC2::Error DrmHwcTwo::CreateDisplay(hwc2_display_t displ,
45                                      HWC2::DisplayType type) {
46   DrmDevice *drm = resource_manager_.GetDrmDevice(displ);
47   std::shared_ptr<Importer> importer = resource_manager_.GetImporter(displ);
48   if (!drm || !importer) {
49     ALOGE("Failed to get a valid drmresource and importer");
50     return HWC2::Error::NoResources;
51   }
52   displays_.emplace(std::piecewise_construct, std::forward_as_tuple(displ),
53                     std::forward_as_tuple(&resource_manager_, drm, importer,
54                                           displ, type));
55 
56   DrmCrtc *crtc = drm->GetCrtcForDisplay(static_cast<int>(displ));
57   if (!crtc) {
58     ALOGE("Failed to get crtc for display %d", static_cast<int>(displ));
59     return HWC2::Error::BadDisplay;
60   }
61   std::vector<DrmPlane *> display_planes;
62   for (auto &plane : drm->planes()) {
63     if (plane->GetCrtcSupported(*crtc))
64       display_planes.push_back(plane.get());
65   }
66   displays_.at(displ).Init(&display_planes);
67   return HWC2::Error::None;
68 }
69 
Init()70 HWC2::Error DrmHwcTwo::Init() {
71   int rv = resource_manager_.Init();
72   if (rv) {
73     ALOGE("Can't initialize the resource manager %d", rv);
74     return HWC2::Error::NoResources;
75   }
76 
77   HWC2::Error ret = HWC2::Error::None;
78   for (int i = 0; i < resource_manager_.getDisplayCount(); i++) {
79     ret = CreateDisplay(i, HWC2::DisplayType::Physical);
80     if (ret != HWC2::Error::None) {
81       ALOGE("Failed to create display %d with error %d", i, ret);
82       return ret;
83     }
84   }
85 
86   auto &drmDevices = resource_manager_.getDrmDevices();
87   for (auto &device : drmDevices) {
88     device->RegisterHotplugHandler(new DrmHotplugHandler(this, device.get()));
89   }
90   return ret;
91 }
92 
93 template <typename... Args>
unsupported(char const * func,Args...)94 static inline HWC2::Error unsupported(char const *func, Args... /*args*/) {
95   ALOGV("Unsupported function: %s", func);
96   return HWC2::Error::Unsupported;
97 }
98 
supported(char const * func)99 static inline void supported(char const *func) {
100   ALOGV("Supported function: %s", func);
101 }
102 
CreateVirtualDisplay(uint32_t width,uint32_t height,int32_t * format,hwc2_display_t * display)103 HWC2::Error DrmHwcTwo::CreateVirtualDisplay(uint32_t width, uint32_t height,
104                                             int32_t *format,
105                                             hwc2_display_t *display) {
106   // TODO: Implement virtual display
107   return unsupported(__func__, width, height, format, display);
108 }
109 
DestroyVirtualDisplay(hwc2_display_t display)110 HWC2::Error DrmHwcTwo::DestroyVirtualDisplay(hwc2_display_t display) {
111   // TODO: Implement virtual display
112   return unsupported(__func__, display);
113 }
114 
DumpDelta(DrmHwcTwo::HwcDisplay::Stats delta)115 std::string DrmHwcTwo::HwcDisplay::DumpDelta(
116     DrmHwcTwo::HwcDisplay::Stats delta) {
117   if (delta.total_pixops_ == 0)
118     return "No stats yet";
119   double Ratio = 1.0 - double(delta.gpu_pixops_) / double(delta.total_pixops_);
120 
121   return (std::stringstream()
122           << " Total frames count: " << delta.total_frames_ << "\n"
123           << " Failed to test commit frames: " << delta.failed_kms_validate_
124           << "\n"
125           << " Failed to commit frames: " << delta.failed_kms_present_ << "\n"
126           << ((delta.failed_kms_present_ > 0)
127                   ? " !!! Internal failure, FIX it please\n"
128                   : "")
129           << " Flattened frames: " << delta.frames_flattened_ << "\n"
130           << " Pixel operations (free units)"
131           << " : [TOTAL: " << delta.total_pixops_
132           << " / GPU: " << delta.gpu_pixops_ << "]\n"
133           << " Composition efficiency: " << Ratio)
134       .str();
135 }
136 
Dump()137 std::string DrmHwcTwo::HwcDisplay::Dump() {
138   auto out = (std::stringstream()
139               << "- Display on: " << connector_->name() << "\n"
140               << "  Flattening state: " << compositor_.GetFlatteningState()
141               << "\n"
142               << "Statistics since system boot:\n"
143               << DumpDelta(total_stats_) << "\n\n"
144               << "Statistics since last dumpsys request:\n"
145               << DumpDelta(total_stats_.minus(prev_stats_)) << "\n\n")
146                  .str();
147 
148   memcpy(&prev_stats_, &total_stats_, sizeof(Stats));
149   return out;
150 }
151 
Dump(uint32_t * outSize,char * outBuffer)152 void DrmHwcTwo::Dump(uint32_t *outSize, char *outBuffer) {
153   supported(__func__);
154 
155   if (outBuffer != nullptr) {
156     auto copiedBytes = mDumpString.copy(outBuffer, *outSize);
157     *outSize = static_cast<uint32_t>(copiedBytes);
158     return;
159   }
160 
161   std::stringstream output;
162 
163   output << "-- drm_hwcomposer --\n\n";
164 
165   for (std::pair<const hwc2_display_t, DrmHwcTwo::HwcDisplay> &dp : displays_)
166     output << dp.second.Dump();
167 
168   mDumpString = output.str();
169   *outSize = static_cast<uint32_t>(mDumpString.size());
170 }
171 
GetMaxVirtualDisplayCount()172 uint32_t DrmHwcTwo::GetMaxVirtualDisplayCount() {
173   // TODO: Implement virtual display
174   unsupported(__func__);
175   return 0;
176 }
177 
RegisterCallback(int32_t descriptor,hwc2_callback_data_t data,hwc2_function_pointer_t function)178 HWC2::Error DrmHwcTwo::RegisterCallback(int32_t descriptor,
179                                         hwc2_callback_data_t data,
180                                         hwc2_function_pointer_t function) {
181   supported(__func__);
182 
183   switch (static_cast<HWC2::Callback>(descriptor)) {
184     case HWC2::Callback::Hotplug: {
185       SetHotplugCallback(data, function);
186       auto &drmDevices = resource_manager_.getDrmDevices();
187       for (auto &device : drmDevices)
188         HandleInitialHotplugState(device.get());
189       break;
190     }
191     case HWC2::Callback::Refresh: {
192       for (std::pair<const hwc2_display_t, DrmHwcTwo::HwcDisplay> &d :
193            displays_)
194         d.second.RegisterRefreshCallback(data, function);
195       break;
196     }
197     case HWC2::Callback::Vsync: {
198       for (std::pair<const hwc2_display_t, DrmHwcTwo::HwcDisplay> &d :
199            displays_)
200         d.second.RegisterVsyncCallback(data, function);
201       break;
202     }
203     default:
204       break;
205   }
206   return HWC2::Error::None;
207 }
208 
HwcDisplay(ResourceManager * resource_manager,DrmDevice * drm,std::shared_ptr<Importer> importer,hwc2_display_t handle,HWC2::DisplayType type)209 DrmHwcTwo::HwcDisplay::HwcDisplay(ResourceManager *resource_manager,
210                                   DrmDevice *drm,
211                                   std::shared_ptr<Importer> importer,
212                                   hwc2_display_t handle, HWC2::DisplayType type)
213     : resource_manager_(resource_manager),
214       drm_(drm),
215       importer_(importer),
216       handle_(handle),
217       type_(type),
218       color_transform_hint_(HAL_COLOR_TRANSFORM_IDENTITY) {
219   supported(__func__);
220 
221   // clang-format off
222   color_transform_matrix_ = {1.0, 0.0, 0.0, 0.0,
223                              0.0, 1.0, 0.0, 0.0,
224                              0.0, 0.0, 1.0, 0.0,
225                              0.0, 0.0, 0.0, 1.0};
226   // clang-format on
227 }
228 
ClearDisplay()229 void DrmHwcTwo::HwcDisplay::ClearDisplay() {
230   compositor_.ClearDisplay();
231 }
232 
Init(std::vector<DrmPlane * > * planes)233 HWC2::Error DrmHwcTwo::HwcDisplay::Init(std::vector<DrmPlane *> *planes) {
234   supported(__func__);
235   planner_ = Planner::CreateInstance(drm_);
236   if (!planner_) {
237     ALOGE("Failed to create planner instance for composition");
238     return HWC2::Error::NoResources;
239   }
240 
241   int display = static_cast<int>(handle_);
242   int ret = compositor_.Init(resource_manager_, display);
243   if (ret) {
244     ALOGE("Failed display compositor init for display %d (%d)", display, ret);
245     return HWC2::Error::NoResources;
246   }
247 
248   // Split up the given display planes into primary and overlay to properly
249   // interface with the composition
250   char use_overlay_planes_prop[PROPERTY_VALUE_MAX];
251   property_get("vendor.hwc.drm.use_overlay_planes", use_overlay_planes_prop,
252                "1");
253   bool use_overlay_planes = atoi(use_overlay_planes_prop);
254   for (auto &plane : *planes) {
255     if (plane->type() == DRM_PLANE_TYPE_PRIMARY)
256       primary_planes_.push_back(plane);
257     else if (use_overlay_planes && (plane)->type() == DRM_PLANE_TYPE_OVERLAY)
258       overlay_planes_.push_back(plane);
259   }
260 
261   crtc_ = drm_->GetCrtcForDisplay(display);
262   if (!crtc_) {
263     ALOGE("Failed to get crtc for display %d", display);
264     return HWC2::Error::BadDisplay;
265   }
266 
267   connector_ = drm_->GetConnectorForDisplay(display);
268   if (!connector_) {
269     ALOGE("Failed to get connector for display %d", display);
270     return HWC2::Error::BadDisplay;
271   }
272 
273   ret = vsync_worker_.Init(drm_, display);
274   if (ret) {
275     ALOGE("Failed to create event worker for d=%d %d\n", display, ret);
276     return HWC2::Error::BadDisplay;
277   }
278 
279   ret = BackendManager::GetInstance().SetBackendForDisplay(this);
280   if (ret) {
281     ALOGE("Failed to set backend for d=%d %d\n", display, ret);
282     return HWC2::Error::BadDisplay;
283   }
284 
285   return ChosePreferredConfig();
286 }
287 
ChosePreferredConfig()288 HWC2::Error DrmHwcTwo::HwcDisplay::ChosePreferredConfig() {
289   // Fetch the number of modes from the display
290   uint32_t num_configs;
291   HWC2::Error err = GetDisplayConfigs(&num_configs, NULL);
292   if (err != HWC2::Error::None || !num_configs)
293     return err;
294 
295   return SetActiveConfig(connector_->get_preferred_mode_id());
296 }
297 
RegisterVsyncCallback(hwc2_callback_data_t data,hwc2_function_pointer_t func)298 void DrmHwcTwo::HwcDisplay::RegisterVsyncCallback(
299     hwc2_callback_data_t data, hwc2_function_pointer_t func) {
300   supported(__func__);
301   vsync_worker_.RegisterClientCallback(data, func);
302 }
303 
RegisterRefreshCallback(hwc2_callback_data_t data,hwc2_function_pointer_t func)304 void DrmHwcTwo::HwcDisplay::RegisterRefreshCallback(
305     hwc2_callback_data_t data, hwc2_function_pointer_t func) {
306   supported(__func__);
307   compositor_.SetRefreshCallback(data, func);
308 }
309 
AcceptDisplayChanges()310 HWC2::Error DrmHwcTwo::HwcDisplay::AcceptDisplayChanges() {
311   supported(__func__);
312   for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : layers_)
313     l.second.accept_type_change();
314   return HWC2::Error::None;
315 }
316 
CreateLayer(hwc2_layer_t * layer)317 HWC2::Error DrmHwcTwo::HwcDisplay::CreateLayer(hwc2_layer_t *layer) {
318   supported(__func__);
319   layers_.emplace(static_cast<hwc2_layer_t>(layer_idx_), HwcLayer());
320   *layer = static_cast<hwc2_layer_t>(layer_idx_);
321   ++layer_idx_;
322   return HWC2::Error::None;
323 }
324 
DestroyLayer(hwc2_layer_t layer)325 HWC2::Error DrmHwcTwo::HwcDisplay::DestroyLayer(hwc2_layer_t layer) {
326   supported(__func__);
327   if (!get_layer(layer))
328     return HWC2::Error::BadLayer;
329 
330   layers_.erase(layer);
331   return HWC2::Error::None;
332 }
333 
GetActiveConfig(hwc2_config_t * config)334 HWC2::Error DrmHwcTwo::HwcDisplay::GetActiveConfig(hwc2_config_t *config) {
335   supported(__func__);
336   DrmMode const &mode = connector_->active_mode();
337   if (mode.id() == 0)
338     return HWC2::Error::BadConfig;
339 
340   *config = mode.id();
341   return HWC2::Error::None;
342 }
343 
GetChangedCompositionTypes(uint32_t * num_elements,hwc2_layer_t * layers,int32_t * types)344 HWC2::Error DrmHwcTwo::HwcDisplay::GetChangedCompositionTypes(
345     uint32_t *num_elements, hwc2_layer_t *layers, int32_t *types) {
346   supported(__func__);
347   uint32_t num_changes = 0;
348   for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : layers_) {
349     if (l.second.type_changed()) {
350       if (layers && num_changes < *num_elements)
351         layers[num_changes] = l.first;
352       if (types && num_changes < *num_elements)
353         types[num_changes] = static_cast<int32_t>(l.second.validated_type());
354       ++num_changes;
355     }
356   }
357   if (!layers && !types)
358     *num_elements = num_changes;
359   return HWC2::Error::None;
360 }
361 
GetClientTargetSupport(uint32_t width,uint32_t height,int32_t,int32_t dataspace)362 HWC2::Error DrmHwcTwo::HwcDisplay::GetClientTargetSupport(uint32_t width,
363                                                           uint32_t height,
364                                                           int32_t /*format*/,
365                                                           int32_t dataspace) {
366   supported(__func__);
367   std::pair<uint32_t, uint32_t> min = drm_->min_resolution();
368   std::pair<uint32_t, uint32_t> max = drm_->max_resolution();
369 
370   if (width < min.first || height < min.second)
371     return HWC2::Error::Unsupported;
372 
373   if (width > max.first || height > max.second)
374     return HWC2::Error::Unsupported;
375 
376   if (dataspace != HAL_DATASPACE_UNKNOWN &&
377       dataspace != HAL_DATASPACE_STANDARD_UNSPECIFIED)
378     return HWC2::Error::Unsupported;
379 
380   // TODO: Validate format can be handled by either GL or planes
381   return HWC2::Error::None;
382 }
383 
GetColorModes(uint32_t * num_modes,int32_t * modes)384 HWC2::Error DrmHwcTwo::HwcDisplay::GetColorModes(uint32_t *num_modes,
385                                                  int32_t *modes) {
386   supported(__func__);
387   if (!modes)
388     *num_modes = 1;
389 
390   if (modes)
391     *modes = HAL_COLOR_MODE_NATIVE;
392 
393   return HWC2::Error::None;
394 }
395 
GetDisplayAttribute(hwc2_config_t config,int32_t attribute_in,int32_t * value)396 HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayAttribute(hwc2_config_t config,
397                                                        int32_t attribute_in,
398                                                        int32_t *value) {
399   supported(__func__);
400   auto mode = std::find_if(connector_->modes().begin(),
401                            connector_->modes().end(),
402                            [config](DrmMode const &m) {
403                              return m.id() == config;
404                            });
405   if (mode == connector_->modes().end()) {
406     ALOGE("Could not find active mode for %d", config);
407     return HWC2::Error::BadConfig;
408   }
409 
410   static const int32_t kUmPerInch = 25400;
411   uint32_t mm_width = connector_->mm_width();
412   uint32_t mm_height = connector_->mm_height();
413   auto attribute = static_cast<HWC2::Attribute>(attribute_in);
414   switch (attribute) {
415     case HWC2::Attribute::Width:
416       *value = mode->h_display();
417       break;
418     case HWC2::Attribute::Height:
419       *value = mode->v_display();
420       break;
421     case HWC2::Attribute::VsyncPeriod:
422       // in nanoseconds
423       *value = 1000 * 1000 * 1000 / mode->v_refresh();
424       break;
425     case HWC2::Attribute::DpiX:
426       // Dots per 1000 inches
427       *value = mm_width ? (mode->h_display() * kUmPerInch) / mm_width : -1;
428       break;
429     case HWC2::Attribute::DpiY:
430       // Dots per 1000 inches
431       *value = mm_height ? (mode->v_display() * kUmPerInch) / mm_height : -1;
432       break;
433     default:
434       *value = -1;
435       return HWC2::Error::BadConfig;
436   }
437   return HWC2::Error::None;
438 }
439 
GetDisplayConfigs(uint32_t * num_configs,hwc2_config_t * configs)440 HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayConfigs(uint32_t *num_configs,
441                                                      hwc2_config_t *configs) {
442   supported(__func__);
443   // Since this callback is normally invoked twice (once to get the count, and
444   // once to populate configs), we don't really want to read the edid
445   // redundantly. Instead, only update the modes on the first invocation. While
446   // it's possible this will result in stale modes, it'll all come out in the
447   // wash when we try to set the active config later.
448   if (!configs) {
449     int ret = connector_->UpdateModes();
450     if (ret) {
451       ALOGE("Failed to update display modes %d", ret);
452       return HWC2::Error::BadDisplay;
453     }
454   }
455 
456   // Since the upper layers only look at vactive/hactive/refresh, height and
457   // width, it doesn't differentiate interlaced from progressive and other
458   // similar modes. Depending on the order of modes we return to SF, it could
459   // end up choosing a suboptimal configuration and dropping the preferred
460   // mode. To workaround this, don't offer interlaced modes to SF if there is
461   // at least one non-interlaced alternative and only offer a single WxH@R
462   // mode with at least the prefered mode from in DrmConnector::UpdateModes()
463 
464   // TODO: Remove the following block of code until AOSP handles all modes
465   std::vector<DrmMode> sel_modes;
466 
467   // Add the preferred mode first to be sure it's not dropped
468   auto mode = std::find_if(connector_->modes().begin(),
469                            connector_->modes().end(), [&](DrmMode const &m) {
470                              return m.id() ==
471                                     connector_->get_preferred_mode_id();
472                            });
473   if (mode != connector_->modes().end())
474     sel_modes.push_back(*mode);
475 
476   // Add the active mode if different from preferred mode
477   if (connector_->active_mode().id() != connector_->get_preferred_mode_id())
478     sel_modes.push_back(connector_->active_mode());
479 
480   // Cycle over the modes and filter out "similar" modes, keeping only the
481   // first ones in the order given by DRM (from CEA ids and timings order)
482   for (const DrmMode &mode : connector_->modes()) {
483     // TODO: Remove this when 3D Attributes are in AOSP
484     if (mode.flags() & DRM_MODE_FLAG_3D_MASK)
485       continue;
486 
487     // TODO: Remove this when the Interlaced attribute is in AOSP
488     if (mode.flags() & DRM_MODE_FLAG_INTERLACE) {
489       auto m = std::find_if(connector_->modes().begin(),
490                             connector_->modes().end(),
491                             [&mode](DrmMode const &m) {
492                               return !(m.flags() & DRM_MODE_FLAG_INTERLACE) &&
493                                      m.h_display() == mode.h_display() &&
494                                      m.v_display() == mode.v_display();
495                             });
496       if (m == connector_->modes().end())
497         sel_modes.push_back(mode);
498 
499       continue;
500     }
501 
502     // Search for a similar WxH@R mode in the filtered list and drop it if
503     // another mode with the same WxH@R has already been selected
504     // TODO: Remove this when AOSP handles duplicates modes
505     auto m = std::find_if(sel_modes.begin(), sel_modes.end(),
506                           [&mode](DrmMode const &m) {
507                             return m.h_display() == mode.h_display() &&
508                                    m.v_display() == mode.v_display() &&
509                                    m.v_refresh() == mode.v_refresh();
510                           });
511     if (m == sel_modes.end())
512       sel_modes.push_back(mode);
513   }
514 
515   auto num_modes = static_cast<uint32_t>(sel_modes.size());
516   if (!configs) {
517     *num_configs = num_modes;
518     return HWC2::Error::None;
519   }
520 
521   uint32_t idx = 0;
522   for (const DrmMode &mode : sel_modes) {
523     if (idx >= *num_configs)
524       break;
525     configs[idx++] = mode.id();
526   }
527   *num_configs = idx;
528   return HWC2::Error::None;
529 }
530 
GetDisplayName(uint32_t * size,char * name)531 HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayName(uint32_t *size, char *name) {
532   supported(__func__);
533   std::ostringstream stream;
534   stream << "display-" << connector_->id();
535   std::string string = stream.str();
536   size_t length = string.length();
537   if (!name) {
538     *size = length;
539     return HWC2::Error::None;
540   }
541 
542   *size = std::min<uint32_t>(static_cast<uint32_t>(length - 1), *size);
543   strncpy(name, string.c_str(), *size);
544   return HWC2::Error::None;
545 }
546 
GetDisplayRequests(int32_t * display_requests,uint32_t * num_elements,hwc2_layer_t * layers,int32_t * layer_requests)547 HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayRequests(int32_t *display_requests,
548                                                       uint32_t *num_elements,
549                                                       hwc2_layer_t *layers,
550                                                       int32_t *layer_requests) {
551   supported(__func__);
552   // TODO: I think virtual display should request
553   //      HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT here
554   unsupported(__func__, display_requests, num_elements, layers, layer_requests);
555   *num_elements = 0;
556   return HWC2::Error::None;
557 }
558 
GetDisplayType(int32_t * type)559 HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayType(int32_t *type) {
560   supported(__func__);
561   *type = static_cast<int32_t>(type_);
562   return HWC2::Error::None;
563 }
564 
GetDozeSupport(int32_t * support)565 HWC2::Error DrmHwcTwo::HwcDisplay::GetDozeSupport(int32_t *support) {
566   supported(__func__);
567   *support = 0;
568   return HWC2::Error::None;
569 }
570 
GetHdrCapabilities(uint32_t * num_types,int32_t *,float *,float *,float *)571 HWC2::Error DrmHwcTwo::HwcDisplay::GetHdrCapabilities(
572     uint32_t *num_types, int32_t * /*types*/, float * /*max_luminance*/,
573     float * /*max_average_luminance*/, float * /*min_luminance*/) {
574   supported(__func__);
575   *num_types = 0;
576   return HWC2::Error::None;
577 }
578 
GetReleaseFences(uint32_t * num_elements,hwc2_layer_t * layers,int32_t * fences)579 HWC2::Error DrmHwcTwo::HwcDisplay::GetReleaseFences(uint32_t *num_elements,
580                                                     hwc2_layer_t *layers,
581                                                     int32_t *fences) {
582   supported(__func__);
583   uint32_t num_layers = 0;
584 
585   for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : layers_) {
586     ++num_layers;
587     if (layers == NULL || fences == NULL) {
588       continue;
589     } else if (num_layers > *num_elements) {
590       ALOGW("Overflow num_elements %d/%d", num_layers, *num_elements);
591       return HWC2::Error::None;
592     }
593 
594     layers[num_layers - 1] = l.first;
595     fences[num_layers - 1] = l.second.take_release_fence();
596   }
597   *num_elements = num_layers;
598   return HWC2::Error::None;
599 }
600 
AddFenceToPresentFence(int fd)601 void DrmHwcTwo::HwcDisplay::AddFenceToPresentFence(int fd) {
602   if (fd < 0)
603     return;
604 
605   if (present_fence_.get() >= 0) {
606     int old_fence = present_fence_.get();
607     present_fence_.Set(sync_merge("dc_present", old_fence, fd));
608     close(fd);
609   } else {
610     present_fence_.Set(fd);
611   }
612 }
613 
HardwareSupportsLayerType(HWC2::Composition comp_type)614 bool DrmHwcTwo::HwcDisplay::HardwareSupportsLayerType(
615     HWC2::Composition comp_type) {
616   return comp_type == HWC2::Composition::Device ||
617          comp_type == HWC2::Composition::Cursor;
618 }
619 
CreateComposition(bool test)620 HWC2::Error DrmHwcTwo::HwcDisplay::CreateComposition(bool test) {
621   std::vector<DrmCompositionDisplayLayersMap> layers_map;
622   layers_map.emplace_back();
623   DrmCompositionDisplayLayersMap &map = layers_map.back();
624 
625   map.display = static_cast<int>(handle_);
626   map.geometry_changed = true;  // TODO: Fix this
627 
628   // order the layers by z-order
629   bool use_client_layer = false;
630   uint32_t client_z_order = UINT32_MAX;
631   std::map<uint32_t, DrmHwcTwo::HwcLayer *> z_map;
632   for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : layers_) {
633     switch (l.second.validated_type()) {
634       case HWC2::Composition::Device:
635         z_map.emplace(std::make_pair(l.second.z_order(), &l.second));
636         break;
637       case HWC2::Composition::Client:
638         // Place it at the z_order of the lowest client layer
639         use_client_layer = true;
640         client_z_order = std::min(client_z_order, l.second.z_order());
641         break;
642       default:
643         continue;
644     }
645   }
646   if (use_client_layer)
647     z_map.emplace(std::make_pair(client_z_order, &client_layer_));
648 
649   if (z_map.empty())
650     return HWC2::Error::BadLayer;
651 
652   // now that they're ordered by z, add them to the composition
653   for (std::pair<const uint32_t, DrmHwcTwo::HwcLayer *> &l : z_map) {
654     DrmHwcLayer layer;
655     l.second->PopulateDrmLayer(&layer);
656     int ret = layer.ImportBuffer(importer_.get());
657     if (ret) {
658       ALOGE("Failed to import layer, ret=%d", ret);
659       return HWC2::Error::NoResources;
660     }
661     map.layers.emplace_back(std::move(layer));
662   }
663 
664   std::unique_ptr<DrmDisplayComposition> composition = compositor_
665                                                            .CreateComposition();
666   composition->Init(drm_, crtc_, importer_.get(), planner_.get(), frame_no_);
667 
668   // TODO: Don't always assume geometry changed
669   int ret = composition->SetLayers(map.layers.data(), map.layers.size(), true);
670   if (ret) {
671     ALOGE("Failed to set layers in the composition ret=%d", ret);
672     return HWC2::Error::BadLayer;
673   }
674 
675   std::vector<DrmPlane *> primary_planes(primary_planes_);
676   std::vector<DrmPlane *> overlay_planes(overlay_planes_);
677   ret = composition->Plan(&primary_planes, &overlay_planes);
678   if (ret) {
679     ALOGE("Failed to plan the composition ret=%d", ret);
680     return HWC2::Error::BadConfig;
681   }
682 
683   // Disable the planes we're not using
684   for (auto i = primary_planes.begin(); i != primary_planes.end();) {
685     composition->AddPlaneDisable(*i);
686     i = primary_planes.erase(i);
687   }
688   for (auto i = overlay_planes.begin(); i != overlay_planes.end();) {
689     composition->AddPlaneDisable(*i);
690     i = overlay_planes.erase(i);
691   }
692 
693   if (test) {
694     ret = compositor_.TestComposition(composition.get());
695   } else {
696     ret = compositor_.ApplyComposition(std::move(composition));
697     AddFenceToPresentFence(compositor_.TakeOutFence());
698   }
699   if (ret) {
700     if (!test)
701       ALOGE("Failed to apply the frame composition ret=%d", ret);
702     return HWC2::Error::BadParameter;
703   }
704   return HWC2::Error::None;
705 }
706 
PresentDisplay(int32_t * present_fence)707 HWC2::Error DrmHwcTwo::HwcDisplay::PresentDisplay(int32_t *present_fence) {
708   supported(__func__);
709   HWC2::Error ret;
710 
711   ++total_stats_.total_frames_;
712 
713   ret = CreateComposition(false);
714   if (ret != HWC2::Error::None)
715     ++total_stats_.failed_kms_present_;
716 
717   if (ret == HWC2::Error::BadLayer) {
718     // Can we really have no client or device layers?
719     *present_fence = -1;
720     return HWC2::Error::None;
721   }
722   if (ret != HWC2::Error::None)
723     return ret;
724 
725   *present_fence = present_fence_.Release();
726 
727   ++frame_no_;
728   return HWC2::Error::None;
729 }
730 
SetActiveConfig(hwc2_config_t config)731 HWC2::Error DrmHwcTwo::HwcDisplay::SetActiveConfig(hwc2_config_t config) {
732   supported(__func__);
733   auto mode = std::find_if(connector_->modes().begin(),
734                            connector_->modes().end(),
735                            [config](DrmMode const &m) {
736                              return m.id() == config;
737                            });
738   if (mode == connector_->modes().end()) {
739     ALOGE("Could not find active mode for %d", config);
740     return HWC2::Error::BadConfig;
741   }
742 
743   std::unique_ptr<DrmDisplayComposition> composition = compositor_
744                                                            .CreateComposition();
745   composition->Init(drm_, crtc_, importer_.get(), planner_.get(), frame_no_);
746   int ret = composition->SetDisplayMode(*mode);
747   ret = compositor_.ApplyComposition(std::move(composition));
748   if (ret) {
749     ALOGE("Failed to queue dpms composition on %d", ret);
750     return HWC2::Error::BadConfig;
751   }
752 
753   connector_->set_active_mode(*mode);
754 
755   // Setup the client layer's dimensions
756   hwc_rect_t display_frame = {.left = 0,
757                               .top = 0,
758                               .right = static_cast<int>(mode->h_display()),
759                               .bottom = static_cast<int>(mode->v_display())};
760   client_layer_.SetLayerDisplayFrame(display_frame);
761 
762   return HWC2::Error::None;
763 }
764 
SetClientTarget(buffer_handle_t target,int32_t acquire_fence,int32_t dataspace,hwc_region_t)765 HWC2::Error DrmHwcTwo::HwcDisplay::SetClientTarget(buffer_handle_t target,
766                                                    int32_t acquire_fence,
767                                                    int32_t dataspace,
768                                                    hwc_region_t /*damage*/) {
769   supported(__func__);
770   UniqueFd uf(acquire_fence);
771 
772   client_layer_.set_buffer(target);
773   client_layer_.set_acquire_fence(uf.get());
774   client_layer_.SetLayerDataspace(dataspace);
775 
776   /* TODO: Do not update source_crop every call.
777    * It makes sense to do it once after every hotplug event. */
778   hwc_drm_bo bo{};
779   BufferInfoGetter::GetInstance()->ConvertBoInfo(target, &bo);
780 
781   hwc_frect_t source_crop = {.left = 0.0f,
782                              .top = 0.0f,
783                              .right = bo.width + 0.0f,
784                              .bottom = bo.height + 0.0f};
785   client_layer_.SetLayerSourceCrop(source_crop);
786 
787   return HWC2::Error::None;
788 }
789 
SetColorMode(int32_t mode)790 HWC2::Error DrmHwcTwo::HwcDisplay::SetColorMode(int32_t mode) {
791   supported(__func__);
792 
793   if (mode < HAL_COLOR_MODE_NATIVE || mode > HAL_COLOR_MODE_BT2100_HLG)
794     return HWC2::Error::BadParameter;
795 
796   if (mode != HAL_COLOR_MODE_NATIVE)
797     return HWC2::Error::Unsupported;
798 
799   color_mode_ = mode;
800   return HWC2::Error::None;
801 }
802 
SetColorTransform(const float * matrix,int32_t hint)803 HWC2::Error DrmHwcTwo::HwcDisplay::SetColorTransform(const float *matrix,
804                                                      int32_t hint) {
805   supported(__func__);
806   if (hint < HAL_COLOR_TRANSFORM_IDENTITY ||
807       hint > HAL_COLOR_TRANSFORM_CORRECT_TRITANOPIA)
808     return HWC2::Error::BadParameter;
809 
810   if (!matrix && hint == HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX)
811     return HWC2::Error::BadParameter;
812 
813   color_transform_hint_ = static_cast<android_color_transform_t>(hint);
814   if (color_transform_hint_ == HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX)
815     std::copy(matrix, matrix + MATRIX_SIZE, color_transform_matrix_.begin());
816 
817   return HWC2::Error::None;
818 }
819 
SetOutputBuffer(buffer_handle_t buffer,int32_t release_fence)820 HWC2::Error DrmHwcTwo::HwcDisplay::SetOutputBuffer(buffer_handle_t buffer,
821                                                    int32_t release_fence) {
822   supported(__func__);
823   // TODO: Need virtual display support
824   return unsupported(__func__, buffer, release_fence);
825 }
826 
SetPowerMode(int32_t mode_in)827 HWC2::Error DrmHwcTwo::HwcDisplay::SetPowerMode(int32_t mode_in) {
828   supported(__func__);
829   uint64_t dpms_value = 0;
830   auto mode = static_cast<HWC2::PowerMode>(mode_in);
831   switch (mode) {
832     case HWC2::PowerMode::Off:
833       dpms_value = DRM_MODE_DPMS_OFF;
834       break;
835     case HWC2::PowerMode::On:
836       dpms_value = DRM_MODE_DPMS_ON;
837       break;
838     case HWC2::PowerMode::Doze:
839     case HWC2::PowerMode::DozeSuspend:
840       return HWC2::Error::Unsupported;
841     default:
842       ALOGI("Power mode %d is unsupported\n", mode);
843       return HWC2::Error::BadParameter;
844   };
845 
846   std::unique_ptr<DrmDisplayComposition> composition = compositor_
847                                                            .CreateComposition();
848   composition->Init(drm_, crtc_, importer_.get(), planner_.get(), frame_no_);
849   composition->SetDpmsMode(dpms_value);
850   int ret = compositor_.ApplyComposition(std::move(composition));
851   if (ret) {
852     ALOGE("Failed to apply the dpms composition ret=%d", ret);
853     return HWC2::Error::BadParameter;
854   }
855   return HWC2::Error::None;
856 }
857 
SetVsyncEnabled(int32_t enabled)858 HWC2::Error DrmHwcTwo::HwcDisplay::SetVsyncEnabled(int32_t enabled) {
859   supported(__func__);
860   vsync_worker_.VSyncControl(HWC2_VSYNC_ENABLE == enabled);
861   return HWC2::Error::None;
862 }
863 
CalcPixOps(std::map<uint32_t,DrmHwcTwo::HwcLayer * > & z_map,size_t first_z,size_t size)864 uint32_t DrmHwcTwo::HwcDisplay::CalcPixOps(
865     std::map<uint32_t, DrmHwcTwo::HwcLayer *> &z_map, size_t first_z,
866     size_t size) {
867   uint32_t pixops = 0;
868   for (std::pair<const uint32_t, DrmHwcTwo::HwcLayer *> &l : z_map) {
869     if (l.first >= first_z && l.first < first_z + size) {
870       hwc_rect_t df = l.second->display_frame();
871       pixops += (df.right - df.left) * (df.bottom - df.top);
872     }
873   }
874   return pixops;
875 }
876 
MarkValidated(std::map<uint32_t,DrmHwcTwo::HwcLayer * > & z_map,size_t client_first_z,size_t client_size)877 void DrmHwcTwo::HwcDisplay::MarkValidated(
878     std::map<uint32_t, DrmHwcTwo::HwcLayer *> &z_map, size_t client_first_z,
879     size_t client_size) {
880   for (std::pair<const uint32_t, DrmHwcTwo::HwcLayer *> &l : z_map) {
881     if (l.first >= client_first_z && l.first < client_first_z + client_size)
882       l.second->set_validated_type(HWC2::Composition::Client);
883     else
884       l.second->set_validated_type(HWC2::Composition::Device);
885   }
886 }
887 
ValidateDisplay(uint32_t * num_types,uint32_t * num_requests)888 HWC2::Error DrmHwcTwo::HwcDisplay::ValidateDisplay(uint32_t *num_types,
889                                                    uint32_t *num_requests) {
890   supported(__func__);
891 
892   return backend_->ValidateDisplay(this, num_types, num_requests);
893 }
894 
895 #if PLATFORM_SDK_VERSION > 28
GetDisplayIdentificationData(uint8_t * outPort,uint32_t * outDataSize,uint8_t * outData)896 HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayIdentificationData(
897     uint8_t *outPort, uint32_t *outDataSize, uint8_t *outData) {
898   supported(__func__);
899 
900   drmModePropertyBlobPtr blob;
901 
902   if (connector_->GetEdidBlob(blob)) {
903     ALOGE("Failed to get edid property value.");
904     return HWC2::Error::Unsupported;
905   }
906 
907   if (outData) {
908     *outDataSize = std::min(*outDataSize, blob->length);
909     memcpy(outData, blob->data, *outDataSize);
910   } else {
911     *outDataSize = blob->length;
912   }
913   *outPort = connector_->id();
914 
915   return HWC2::Error::None;
916 }
917 
GetDisplayCapabilities(uint32_t * outNumCapabilities,uint32_t * outCapabilities)918 HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayCapabilities(
919     uint32_t *outNumCapabilities, uint32_t *outCapabilities) {
920   unsupported(__func__, outCapabilities);
921 
922   if (outNumCapabilities == NULL) {
923     return HWC2::Error::BadParameter;
924   }
925 
926   *outNumCapabilities = 0;
927 
928   return HWC2::Error::None;
929 }
930 
GetDisplayBrightnessSupport(bool * supported)931 HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayBrightnessSupport(
932     bool *supported) {
933   *supported = false;
934   return HWC2::Error::None;
935 }
936 
SetDisplayBrightness(float)937 HWC2::Error DrmHwcTwo::HwcDisplay::SetDisplayBrightness(
938     float /* brightness */) {
939   return HWC2::Error::Unsupported;
940 }
941 
942 #endif /* PLATFORM_SDK_VERSION > 28 */
943 
944 #if PLATFORM_SDK_VERSION > 27
945 
GetRenderIntents(int32_t mode,uint32_t * outNumIntents,int32_t * outIntents)946 HWC2::Error DrmHwcTwo::HwcDisplay::GetRenderIntents(
947     int32_t mode, uint32_t *outNumIntents,
948     int32_t * /*android_render_intent_v1_1_t*/ outIntents) {
949   if (mode != HAL_COLOR_MODE_NATIVE) {
950     return HWC2::Error::BadParameter;
951   }
952 
953   if (outIntents == nullptr) {
954     *outNumIntents = 1;
955     return HWC2::Error::None;
956   }
957   *outNumIntents = 1;
958   outIntents[0] = HAL_RENDER_INTENT_COLORIMETRIC;
959   return HWC2::Error::None;
960 }
961 
SetColorModeWithIntent(int32_t mode,int32_t intent)962 HWC2::Error DrmHwcTwo::HwcDisplay::SetColorModeWithIntent(int32_t mode,
963                                                           int32_t intent) {
964   if (intent < HAL_RENDER_INTENT_COLORIMETRIC ||
965       intent > HAL_RENDER_INTENT_TONE_MAP_ENHANCE)
966     return HWC2::Error::BadParameter;
967 
968   if (mode < HAL_COLOR_MODE_NATIVE || mode > HAL_COLOR_MODE_BT2100_HLG)
969     return HWC2::Error::BadParameter;
970 
971   if (mode != HAL_COLOR_MODE_NATIVE)
972     return HWC2::Error::Unsupported;
973 
974   if (intent != HAL_RENDER_INTENT_COLORIMETRIC)
975     return HWC2::Error::Unsupported;
976 
977   color_mode_ = mode;
978   return HWC2::Error::None;
979 }
980 
981 #endif /* PLATFORM_SDK_VERSION > 27 */
982 
SetCursorPosition(int32_t x,int32_t y)983 HWC2::Error DrmHwcTwo::HwcLayer::SetCursorPosition(int32_t x, int32_t y) {
984   supported(__func__);
985   cursor_x_ = x;
986   cursor_y_ = y;
987   return HWC2::Error::None;
988 }
989 
SetLayerBlendMode(int32_t mode)990 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerBlendMode(int32_t mode) {
991   supported(__func__);
992   blending_ = static_cast<HWC2::BlendMode>(mode);
993   return HWC2::Error::None;
994 }
995 
SetLayerBuffer(buffer_handle_t buffer,int32_t acquire_fence)996 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerBuffer(buffer_handle_t buffer,
997                                                 int32_t acquire_fence) {
998   supported(__func__);
999   UniqueFd uf(acquire_fence);
1000 
1001   set_buffer(buffer);
1002   set_acquire_fence(uf.get());
1003   return HWC2::Error::None;
1004 }
1005 
SetLayerColor(hwc_color_t color)1006 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerColor(hwc_color_t color) {
1007   // TODO: Put to client composition here?
1008   supported(__func__);
1009   layer_color_ = color;
1010   return HWC2::Error::None;
1011 }
1012 
SetLayerCompositionType(int32_t type)1013 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerCompositionType(int32_t type) {
1014   sf_type_ = static_cast<HWC2::Composition>(type);
1015   return HWC2::Error::None;
1016 }
1017 
SetLayerDataspace(int32_t dataspace)1018 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerDataspace(int32_t dataspace) {
1019   supported(__func__);
1020   dataspace_ = static_cast<android_dataspace_t>(dataspace);
1021   return HWC2::Error::None;
1022 }
1023 
SetLayerDisplayFrame(hwc_rect_t frame)1024 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerDisplayFrame(hwc_rect_t frame) {
1025   supported(__func__);
1026   display_frame_ = frame;
1027   return HWC2::Error::None;
1028 }
1029 
SetLayerPlaneAlpha(float alpha)1030 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerPlaneAlpha(float alpha) {
1031   supported(__func__);
1032   alpha_ = alpha;
1033   return HWC2::Error::None;
1034 }
1035 
SetLayerSidebandStream(const native_handle_t * stream)1036 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerSidebandStream(
1037     const native_handle_t *stream) {
1038   supported(__func__);
1039   // TODO: We don't support sideband
1040   return unsupported(__func__, stream);
1041 }
1042 
SetLayerSourceCrop(hwc_frect_t crop)1043 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerSourceCrop(hwc_frect_t crop) {
1044   supported(__func__);
1045   source_crop_ = crop;
1046   return HWC2::Error::None;
1047 }
1048 
SetLayerSurfaceDamage(hwc_region_t damage)1049 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerSurfaceDamage(hwc_region_t damage) {
1050   supported(__func__);
1051   // TODO: We don't use surface damage, marking as unsupported
1052   unsupported(__func__, damage);
1053   return HWC2::Error::None;
1054 }
1055 
SetLayerTransform(int32_t transform)1056 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerTransform(int32_t transform) {
1057   supported(__func__);
1058   transform_ = static_cast<HWC2::Transform>(transform);
1059   return HWC2::Error::None;
1060 }
1061 
SetLayerVisibleRegion(hwc_region_t visible)1062 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerVisibleRegion(hwc_region_t visible) {
1063   supported(__func__);
1064   // TODO: We don't use this information, marking as unsupported
1065   unsupported(__func__, visible);
1066   return HWC2::Error::None;
1067 }
1068 
SetLayerZOrder(uint32_t order)1069 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerZOrder(uint32_t order) {
1070   supported(__func__);
1071   z_order_ = order;
1072   return HWC2::Error::None;
1073 }
1074 
PopulateDrmLayer(DrmHwcLayer * layer)1075 void DrmHwcTwo::HwcLayer::PopulateDrmLayer(DrmHwcLayer *layer) {
1076   supported(__func__);
1077   switch (blending_) {
1078     case HWC2::BlendMode::None:
1079       layer->blending = DrmHwcBlending::kNone;
1080       break;
1081     case HWC2::BlendMode::Premultiplied:
1082       layer->blending = DrmHwcBlending::kPreMult;
1083       break;
1084     case HWC2::BlendMode::Coverage:
1085       layer->blending = DrmHwcBlending::kCoverage;
1086       break;
1087     default:
1088       ALOGE("Unknown blending mode b=%d", blending_);
1089       layer->blending = DrmHwcBlending::kNone;
1090       break;
1091   }
1092 
1093   OutputFd release_fence = release_fence_output();
1094 
1095   layer->sf_handle = buffer_;
1096   layer->acquire_fence = acquire_fence_.Release();
1097   layer->release_fence = std::move(release_fence);
1098   layer->SetDisplayFrame(display_frame_);
1099   layer->alpha = static_cast<uint16_t>(65535.0f * alpha_ + 0.5f);
1100   layer->SetSourceCrop(source_crop_);
1101   layer->SetTransform(static_cast<int32_t>(transform_));
1102 }
1103 
HandleDisplayHotplug(hwc2_display_t displayid,int state)1104 void DrmHwcTwo::HandleDisplayHotplug(hwc2_display_t displayid, int state) {
1105   const std::lock_guard<std::mutex> lock(hotplug_callback_lock);
1106 
1107   if (hotplug_callback_hook_ && hotplug_callback_data_)
1108     hotplug_callback_hook_(hotplug_callback_data_, displayid,
1109                            state == DRM_MODE_CONNECTED
1110                                ? HWC2_CONNECTION_CONNECTED
1111                                : HWC2_CONNECTION_DISCONNECTED);
1112 }
1113 
HandleInitialHotplugState(DrmDevice * drmDevice)1114 void DrmHwcTwo::HandleInitialHotplugState(DrmDevice *drmDevice) {
1115   for (auto &conn : drmDevice->connectors()) {
1116     if (conn->state() != DRM_MODE_CONNECTED)
1117       continue;
1118     HandleDisplayHotplug(conn->display(), conn->state());
1119   }
1120 }
1121 
HandleEvent(uint64_t timestamp_us)1122 void DrmHwcTwo::DrmHotplugHandler::HandleEvent(uint64_t timestamp_us) {
1123   for (auto &conn : drm_->connectors()) {
1124     drmModeConnection old_state = conn->state();
1125     drmModeConnection cur_state = conn->UpdateModes()
1126                                       ? DRM_MODE_UNKNOWNCONNECTION
1127                                       : conn->state();
1128 
1129     if (cur_state == old_state)
1130       continue;
1131 
1132     ALOGI("%s event @%" PRIu64 " for connector %u on display %d",
1133           cur_state == DRM_MODE_CONNECTED ? "Plug" : "Unplug", timestamp_us,
1134           conn->id(), conn->display());
1135 
1136     int display_id = conn->display();
1137     if (cur_state == DRM_MODE_CONNECTED) {
1138       auto &display = hwc2_->displays_.at(display_id);
1139       display.ChosePreferredConfig();
1140     } else {
1141       auto &display = hwc2_->displays_.at(display_id);
1142       display.ClearDisplay();
1143     }
1144 
1145     hwc2_->HandleDisplayHotplug(display_id, cur_state);
1146   }
1147 }
1148 
1149 // static
HookDevClose(hw_device_t *)1150 int DrmHwcTwo::HookDevClose(hw_device_t * /*dev*/) {
1151   unsupported(__func__);
1152   return 0;
1153 }
1154 
1155 // static
HookDevGetCapabilities(hwc2_device_t *,uint32_t * out_count,int32_t *)1156 void DrmHwcTwo::HookDevGetCapabilities(hwc2_device_t * /*dev*/,
1157                                        uint32_t *out_count,
1158                                        int32_t * /*out_capabilities*/) {
1159   supported(__func__);
1160   *out_count = 0;
1161 }
1162 
1163 // static
HookDevGetFunction(struct hwc2_device *,int32_t descriptor)1164 hwc2_function_pointer_t DrmHwcTwo::HookDevGetFunction(
1165     struct hwc2_device * /*dev*/, int32_t descriptor) {
1166   supported(__func__);
1167   auto func = static_cast<HWC2::FunctionDescriptor>(descriptor);
1168   switch (func) {
1169     // Device functions
1170     case HWC2::FunctionDescriptor::CreateVirtualDisplay:
1171       return ToHook<HWC2_PFN_CREATE_VIRTUAL_DISPLAY>(
1172           DeviceHook<int32_t, decltype(&DrmHwcTwo::CreateVirtualDisplay),
1173                      &DrmHwcTwo::CreateVirtualDisplay, uint32_t, uint32_t,
1174                      int32_t *, hwc2_display_t *>);
1175     case HWC2::FunctionDescriptor::DestroyVirtualDisplay:
1176       return ToHook<HWC2_PFN_DESTROY_VIRTUAL_DISPLAY>(
1177           DeviceHook<int32_t, decltype(&DrmHwcTwo::DestroyVirtualDisplay),
1178                      &DrmHwcTwo::DestroyVirtualDisplay, hwc2_display_t>);
1179     case HWC2::FunctionDescriptor::Dump:
1180       return ToHook<HWC2_PFN_DUMP>(
1181           DeviceHook<void, decltype(&DrmHwcTwo::Dump), &DrmHwcTwo::Dump,
1182                      uint32_t *, char *>);
1183     case HWC2::FunctionDescriptor::GetMaxVirtualDisplayCount:
1184       return ToHook<HWC2_PFN_GET_MAX_VIRTUAL_DISPLAY_COUNT>(
1185           DeviceHook<uint32_t, decltype(&DrmHwcTwo::GetMaxVirtualDisplayCount),
1186                      &DrmHwcTwo::GetMaxVirtualDisplayCount>);
1187     case HWC2::FunctionDescriptor::RegisterCallback:
1188       return ToHook<HWC2_PFN_REGISTER_CALLBACK>(
1189           DeviceHook<int32_t, decltype(&DrmHwcTwo::RegisterCallback),
1190                      &DrmHwcTwo::RegisterCallback, int32_t,
1191                      hwc2_callback_data_t, hwc2_function_pointer_t>);
1192 
1193     // Display functions
1194     case HWC2::FunctionDescriptor::AcceptDisplayChanges:
1195       return ToHook<HWC2_PFN_ACCEPT_DISPLAY_CHANGES>(
1196           DisplayHook<decltype(&HwcDisplay::AcceptDisplayChanges),
1197                       &HwcDisplay::AcceptDisplayChanges>);
1198     case HWC2::FunctionDescriptor::CreateLayer:
1199       return ToHook<HWC2_PFN_CREATE_LAYER>(
1200           DisplayHook<decltype(&HwcDisplay::CreateLayer),
1201                       &HwcDisplay::CreateLayer, hwc2_layer_t *>);
1202     case HWC2::FunctionDescriptor::DestroyLayer:
1203       return ToHook<HWC2_PFN_DESTROY_LAYER>(
1204           DisplayHook<decltype(&HwcDisplay::DestroyLayer),
1205                       &HwcDisplay::DestroyLayer, hwc2_layer_t>);
1206     case HWC2::FunctionDescriptor::GetActiveConfig:
1207       return ToHook<HWC2_PFN_GET_ACTIVE_CONFIG>(
1208           DisplayHook<decltype(&HwcDisplay::GetActiveConfig),
1209                       &HwcDisplay::GetActiveConfig, hwc2_config_t *>);
1210     case HWC2::FunctionDescriptor::GetChangedCompositionTypes:
1211       return ToHook<HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES>(
1212           DisplayHook<decltype(&HwcDisplay::GetChangedCompositionTypes),
1213                       &HwcDisplay::GetChangedCompositionTypes, uint32_t *,
1214                       hwc2_layer_t *, int32_t *>);
1215     case HWC2::FunctionDescriptor::GetClientTargetSupport:
1216       return ToHook<HWC2_PFN_GET_CLIENT_TARGET_SUPPORT>(
1217           DisplayHook<decltype(&HwcDisplay::GetClientTargetSupport),
1218                       &HwcDisplay::GetClientTargetSupport, uint32_t, uint32_t,
1219                       int32_t, int32_t>);
1220     case HWC2::FunctionDescriptor::GetColorModes:
1221       return ToHook<HWC2_PFN_GET_COLOR_MODES>(
1222           DisplayHook<decltype(&HwcDisplay::GetColorModes),
1223                       &HwcDisplay::GetColorModes, uint32_t *, int32_t *>);
1224     case HWC2::FunctionDescriptor::GetDisplayAttribute:
1225       return ToHook<HWC2_PFN_GET_DISPLAY_ATTRIBUTE>(
1226           DisplayHook<decltype(&HwcDisplay::GetDisplayAttribute),
1227                       &HwcDisplay::GetDisplayAttribute, hwc2_config_t, int32_t,
1228                       int32_t *>);
1229     case HWC2::FunctionDescriptor::GetDisplayConfigs:
1230       return ToHook<HWC2_PFN_GET_DISPLAY_CONFIGS>(
1231           DisplayHook<decltype(&HwcDisplay::GetDisplayConfigs),
1232                       &HwcDisplay::GetDisplayConfigs, uint32_t *,
1233                       hwc2_config_t *>);
1234     case HWC2::FunctionDescriptor::GetDisplayName:
1235       return ToHook<HWC2_PFN_GET_DISPLAY_NAME>(
1236           DisplayHook<decltype(&HwcDisplay::GetDisplayName),
1237                       &HwcDisplay::GetDisplayName, uint32_t *, char *>);
1238     case HWC2::FunctionDescriptor::GetDisplayRequests:
1239       return ToHook<HWC2_PFN_GET_DISPLAY_REQUESTS>(
1240           DisplayHook<decltype(&HwcDisplay::GetDisplayRequests),
1241                       &HwcDisplay::GetDisplayRequests, int32_t *, uint32_t *,
1242                       hwc2_layer_t *, int32_t *>);
1243     case HWC2::FunctionDescriptor::GetDisplayType:
1244       return ToHook<HWC2_PFN_GET_DISPLAY_TYPE>(
1245           DisplayHook<decltype(&HwcDisplay::GetDisplayType),
1246                       &HwcDisplay::GetDisplayType, int32_t *>);
1247     case HWC2::FunctionDescriptor::GetDozeSupport:
1248       return ToHook<HWC2_PFN_GET_DOZE_SUPPORT>(
1249           DisplayHook<decltype(&HwcDisplay::GetDozeSupport),
1250                       &HwcDisplay::GetDozeSupport, int32_t *>);
1251     case HWC2::FunctionDescriptor::GetHdrCapabilities:
1252       return ToHook<HWC2_PFN_GET_HDR_CAPABILITIES>(
1253           DisplayHook<decltype(&HwcDisplay::GetHdrCapabilities),
1254                       &HwcDisplay::GetHdrCapabilities, uint32_t *, int32_t *,
1255                       float *, float *, float *>);
1256     case HWC2::FunctionDescriptor::GetReleaseFences:
1257       return ToHook<HWC2_PFN_GET_RELEASE_FENCES>(
1258           DisplayHook<decltype(&HwcDisplay::GetReleaseFences),
1259                       &HwcDisplay::GetReleaseFences, uint32_t *, hwc2_layer_t *,
1260                       int32_t *>);
1261     case HWC2::FunctionDescriptor::PresentDisplay:
1262       return ToHook<HWC2_PFN_PRESENT_DISPLAY>(
1263           DisplayHook<decltype(&HwcDisplay::PresentDisplay),
1264                       &HwcDisplay::PresentDisplay, int32_t *>);
1265     case HWC2::FunctionDescriptor::SetActiveConfig:
1266       return ToHook<HWC2_PFN_SET_ACTIVE_CONFIG>(
1267           DisplayHook<decltype(&HwcDisplay::SetActiveConfig),
1268                       &HwcDisplay::SetActiveConfig, hwc2_config_t>);
1269     case HWC2::FunctionDescriptor::SetClientTarget:
1270       return ToHook<HWC2_PFN_SET_CLIENT_TARGET>(
1271           DisplayHook<decltype(&HwcDisplay::SetClientTarget),
1272                       &HwcDisplay::SetClientTarget, buffer_handle_t, int32_t,
1273                       int32_t, hwc_region_t>);
1274     case HWC2::FunctionDescriptor::SetColorMode:
1275       return ToHook<HWC2_PFN_SET_COLOR_MODE>(
1276           DisplayHook<decltype(&HwcDisplay::SetColorMode),
1277                       &HwcDisplay::SetColorMode, int32_t>);
1278     case HWC2::FunctionDescriptor::SetColorTransform:
1279       return ToHook<HWC2_PFN_SET_COLOR_TRANSFORM>(
1280           DisplayHook<decltype(&HwcDisplay::SetColorTransform),
1281                       &HwcDisplay::SetColorTransform, const float *, int32_t>);
1282     case HWC2::FunctionDescriptor::SetOutputBuffer:
1283       return ToHook<HWC2_PFN_SET_OUTPUT_BUFFER>(
1284           DisplayHook<decltype(&HwcDisplay::SetOutputBuffer),
1285                       &HwcDisplay::SetOutputBuffer, buffer_handle_t, int32_t>);
1286     case HWC2::FunctionDescriptor::SetPowerMode:
1287       return ToHook<HWC2_PFN_SET_POWER_MODE>(
1288           DisplayHook<decltype(&HwcDisplay::SetPowerMode),
1289                       &HwcDisplay::SetPowerMode, int32_t>);
1290     case HWC2::FunctionDescriptor::SetVsyncEnabled:
1291       return ToHook<HWC2_PFN_SET_VSYNC_ENABLED>(
1292           DisplayHook<decltype(&HwcDisplay::SetVsyncEnabled),
1293                       &HwcDisplay::SetVsyncEnabled, int32_t>);
1294     case HWC2::FunctionDescriptor::ValidateDisplay:
1295       return ToHook<HWC2_PFN_VALIDATE_DISPLAY>(
1296           DisplayHook<decltype(&HwcDisplay::ValidateDisplay),
1297                       &HwcDisplay::ValidateDisplay, uint32_t *, uint32_t *>);
1298 #if PLATFORM_SDK_VERSION > 27
1299     case HWC2::FunctionDescriptor::GetRenderIntents:
1300       return ToHook<HWC2_PFN_GET_RENDER_INTENTS>(
1301           DisplayHook<decltype(&HwcDisplay::GetRenderIntents),
1302                       &HwcDisplay::GetRenderIntents, int32_t, uint32_t *,
1303                       int32_t *>);
1304     case HWC2::FunctionDescriptor::SetColorModeWithRenderIntent:
1305       return ToHook<HWC2_PFN_SET_COLOR_MODE_WITH_RENDER_INTENT>(
1306           DisplayHook<decltype(&HwcDisplay::SetColorModeWithIntent),
1307                       &HwcDisplay::SetColorModeWithIntent, int32_t, int32_t>);
1308 #endif
1309 #if PLATFORM_SDK_VERSION > 28
1310     case HWC2::FunctionDescriptor::GetDisplayIdentificationData:
1311       return ToHook<HWC2_PFN_GET_DISPLAY_IDENTIFICATION_DATA>(
1312           DisplayHook<decltype(&HwcDisplay::GetDisplayIdentificationData),
1313                       &HwcDisplay::GetDisplayIdentificationData, uint8_t *,
1314                       uint32_t *, uint8_t *>);
1315     case HWC2::FunctionDescriptor::GetDisplayCapabilities:
1316       return ToHook<HWC2_PFN_GET_DISPLAY_CAPABILITIES>(
1317           DisplayHook<decltype(&HwcDisplay::GetDisplayCapabilities),
1318                       &HwcDisplay::GetDisplayCapabilities, uint32_t *,
1319                       uint32_t *>);
1320     case HWC2::FunctionDescriptor::GetDisplayBrightnessSupport:
1321       return ToHook<HWC2_PFN_GET_DISPLAY_BRIGHTNESS_SUPPORT>(
1322           DisplayHook<decltype(&HwcDisplay::GetDisplayBrightnessSupport),
1323                       &HwcDisplay::GetDisplayBrightnessSupport, bool *>);
1324     case HWC2::FunctionDescriptor::SetDisplayBrightness:
1325       return ToHook<HWC2_PFN_SET_DISPLAY_BRIGHTNESS>(
1326           DisplayHook<decltype(&HwcDisplay::SetDisplayBrightness),
1327                       &HwcDisplay::SetDisplayBrightness, float>);
1328 #endif /* PLATFORM_SDK_VERSION > 28 */
1329     // Layer functions
1330     case HWC2::FunctionDescriptor::SetCursorPosition:
1331       return ToHook<HWC2_PFN_SET_CURSOR_POSITION>(
1332           LayerHook<decltype(&HwcLayer::SetCursorPosition),
1333                     &HwcLayer::SetCursorPosition, int32_t, int32_t>);
1334     case HWC2::FunctionDescriptor::SetLayerBlendMode:
1335       return ToHook<HWC2_PFN_SET_LAYER_BLEND_MODE>(
1336           LayerHook<decltype(&HwcLayer::SetLayerBlendMode),
1337                     &HwcLayer::SetLayerBlendMode, int32_t>);
1338     case HWC2::FunctionDescriptor::SetLayerBuffer:
1339       return ToHook<HWC2_PFN_SET_LAYER_BUFFER>(
1340           LayerHook<decltype(&HwcLayer::SetLayerBuffer),
1341                     &HwcLayer::SetLayerBuffer, buffer_handle_t, int32_t>);
1342     case HWC2::FunctionDescriptor::SetLayerColor:
1343       return ToHook<HWC2_PFN_SET_LAYER_COLOR>(
1344           LayerHook<decltype(&HwcLayer::SetLayerColor),
1345                     &HwcLayer::SetLayerColor, hwc_color_t>);
1346     case HWC2::FunctionDescriptor::SetLayerCompositionType:
1347       return ToHook<HWC2_PFN_SET_LAYER_COMPOSITION_TYPE>(
1348           LayerHook<decltype(&HwcLayer::SetLayerCompositionType),
1349                     &HwcLayer::SetLayerCompositionType, int32_t>);
1350     case HWC2::FunctionDescriptor::SetLayerDataspace:
1351       return ToHook<HWC2_PFN_SET_LAYER_DATASPACE>(
1352           LayerHook<decltype(&HwcLayer::SetLayerDataspace),
1353                     &HwcLayer::SetLayerDataspace, int32_t>);
1354     case HWC2::FunctionDescriptor::SetLayerDisplayFrame:
1355       return ToHook<HWC2_PFN_SET_LAYER_DISPLAY_FRAME>(
1356           LayerHook<decltype(&HwcLayer::SetLayerDisplayFrame),
1357                     &HwcLayer::SetLayerDisplayFrame, hwc_rect_t>);
1358     case HWC2::FunctionDescriptor::SetLayerPlaneAlpha:
1359       return ToHook<HWC2_PFN_SET_LAYER_PLANE_ALPHA>(
1360           LayerHook<decltype(&HwcLayer::SetLayerPlaneAlpha),
1361                     &HwcLayer::SetLayerPlaneAlpha, float>);
1362     case HWC2::FunctionDescriptor::SetLayerSidebandStream:
1363       return ToHook<HWC2_PFN_SET_LAYER_SIDEBAND_STREAM>(
1364           LayerHook<decltype(&HwcLayer::SetLayerSidebandStream),
1365                     &HwcLayer::SetLayerSidebandStream,
1366                     const native_handle_t *>);
1367     case HWC2::FunctionDescriptor::SetLayerSourceCrop:
1368       return ToHook<HWC2_PFN_SET_LAYER_SOURCE_CROP>(
1369           LayerHook<decltype(&HwcLayer::SetLayerSourceCrop),
1370                     &HwcLayer::SetLayerSourceCrop, hwc_frect_t>);
1371     case HWC2::FunctionDescriptor::SetLayerSurfaceDamage:
1372       return ToHook<HWC2_PFN_SET_LAYER_SURFACE_DAMAGE>(
1373           LayerHook<decltype(&HwcLayer::SetLayerSurfaceDamage),
1374                     &HwcLayer::SetLayerSurfaceDamage, hwc_region_t>);
1375     case HWC2::FunctionDescriptor::SetLayerTransform:
1376       return ToHook<HWC2_PFN_SET_LAYER_TRANSFORM>(
1377           LayerHook<decltype(&HwcLayer::SetLayerTransform),
1378                     &HwcLayer::SetLayerTransform, int32_t>);
1379     case HWC2::FunctionDescriptor::SetLayerVisibleRegion:
1380       return ToHook<HWC2_PFN_SET_LAYER_VISIBLE_REGION>(
1381           LayerHook<decltype(&HwcLayer::SetLayerVisibleRegion),
1382                     &HwcLayer::SetLayerVisibleRegion, hwc_region_t>);
1383     case HWC2::FunctionDescriptor::SetLayerZOrder:
1384       return ToHook<HWC2_PFN_SET_LAYER_Z_ORDER>(
1385           LayerHook<decltype(&HwcLayer::SetLayerZOrder),
1386                     &HwcLayer::SetLayerZOrder, uint32_t>);
1387     case HWC2::FunctionDescriptor::Invalid:
1388     default:
1389       return NULL;
1390   }
1391 }
1392 
1393 // static
HookDevOpen(const struct hw_module_t * module,const char * name,struct hw_device_t ** dev)1394 int DrmHwcTwo::HookDevOpen(const struct hw_module_t *module, const char *name,
1395                            struct hw_device_t **dev) {
1396   supported(__func__);
1397   if (strcmp(name, HWC_HARDWARE_COMPOSER)) {
1398     ALOGE("Invalid module name- %s", name);
1399     return -EINVAL;
1400   }
1401 
1402   std::unique_ptr<DrmHwcTwo> ctx(new DrmHwcTwo());
1403   if (!ctx) {
1404     ALOGE("Failed to allocate DrmHwcTwo");
1405     return -ENOMEM;
1406   }
1407 
1408   HWC2::Error err = ctx->Init();
1409   if (err != HWC2::Error::None) {
1410     ALOGE("Failed to initialize DrmHwcTwo err=%d\n", err);
1411     return -EINVAL;
1412   }
1413 
1414   ctx->common.module = const_cast<hw_module_t *>(module);
1415   *dev = &ctx->common;
1416   ctx.release();
1417   return 0;
1418 }
1419 }  // namespace android
1420 
1421 static struct hw_module_methods_t hwc2_module_methods = {
1422     .open = android::DrmHwcTwo::HookDevOpen,
1423 };
1424 
1425 hw_module_t HAL_MODULE_INFO_SYM = {
1426     .tag = HARDWARE_MODULE_TAG,
1427     .module_api_version = HARDWARE_MODULE_API_VERSION(2, 0),
1428     .id = HWC_HARDWARE_MODULE_ID,
1429     .name = "DrmHwcTwo module",
1430     .author = "The Android Open Source Project",
1431     .methods = &hwc2_module_methods,
1432     .dso = NULL,
1433     .reserved = {0},
1434 };
1435