OSDN Git Service

drm_hwcomposer: Add out-fence support
[android-x86/external-drm_hwcomposer.git] / drmhwctwo.cpp
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 "drmdisplaycomposition.h"
21 #include "drmhwcomposer.h"
22 #include "drmhwctwo.h"
23 #include "platform.h"
24 #include "vsyncworker.h"
25
26 #include <inttypes.h>
27 #include <string>
28
29 #include <cutils/log.h>
30 #include <cutils/properties.h>
31 #include <hardware/hardware.h>
32 #include <hardware/hwcomposer2.h>
33
34 namespace android {
35
36 class DrmVsyncCallback : public VsyncCallback {
37  public:
38   DrmVsyncCallback(hwc2_callback_data_t data, hwc2_function_pointer_t hook)
39       : data_(data), hook_(hook) {
40   }
41
42   void Callback(int display, int64_t timestamp) {
43     auto hook = reinterpret_cast<HWC2_PFN_VSYNC>(hook_);
44     hook(data_, display, timestamp);
45   }
46
47  private:
48   hwc2_callback_data_t data_;
49   hwc2_function_pointer_t hook_;
50 };
51
52 DrmHwcTwo::DrmHwcTwo() {
53   common.tag = HARDWARE_DEVICE_TAG;
54   common.version = HWC_DEVICE_API_VERSION_2_0;
55   common.close = HookDevClose;
56   getCapabilities = HookDevGetCapabilities;
57   getFunction = HookDevGetFunction;
58 }
59
60 HWC2::Error DrmHwcTwo::Init() {
61   int ret = drm_.Init();
62   if (ret) {
63     ALOGE("Can't initialize drm object %d", ret);
64     return HWC2::Error::NoResources;
65   }
66
67   importer_.reset(Importer::CreateInstance(&drm_));
68   if (!importer_) {
69     ALOGE("Failed to create importer instance");
70     return HWC2::Error::NoResources;
71   }
72
73   ret = hw_get_module(GRALLOC_HARDWARE_MODULE_ID,
74                       (const hw_module_t **)&gralloc_);
75   if (ret) {
76     ALOGE("Failed to open gralloc module %d", ret);
77     return HWC2::Error::NoResources;
78   }
79
80   displays_.emplace(std::piecewise_construct,
81                     std::forward_as_tuple(HWC_DISPLAY_PRIMARY),
82                     std::forward_as_tuple(&drm_, importer_, gralloc_,
83                                           HWC_DISPLAY_PRIMARY,
84                                           HWC2::DisplayType::Physical));
85
86   DrmCrtc *crtc = drm_.GetCrtcForDisplay(static_cast<int>(HWC_DISPLAY_PRIMARY));
87   if (!crtc) {
88     ALOGE("Failed to get crtc for display %d",
89           static_cast<int>(HWC_DISPLAY_PRIMARY));
90     return HWC2::Error::BadDisplay;
91   }
92
93   std::vector<DrmPlane *> display_planes;
94   for (auto &plane : drm_.planes()) {
95     if (plane->GetCrtcSupported(*crtc))
96       display_planes.push_back(plane.get());
97   }
98   displays_.at(HWC_DISPLAY_PRIMARY).Init(&display_planes);
99   return HWC2::Error::None;
100 }
101
102 template <typename... Args>
103 static inline HWC2::Error unsupported(char const *func, Args... /*args*/) {
104   ALOGV("Unsupported function: %s", func);
105   return HWC2::Error::Unsupported;
106 }
107
108 static inline void supported(char const *func) {
109   ALOGV("Supported function: %s", func);
110 }
111
112 HWC2::Error DrmHwcTwo::CreateVirtualDisplay(uint32_t width, uint32_t height,
113                                             int32_t *format,
114                                             hwc2_display_t *display) {
115   // TODO: Implement virtual display
116   return unsupported(__func__, width, height, format, display);
117 }
118
119 HWC2::Error DrmHwcTwo::DestroyVirtualDisplay(hwc2_display_t display) {
120   // TODO: Implement virtual display
121   return unsupported(__func__, display);
122 }
123
124 void DrmHwcTwo::Dump(uint32_t *size, char *buffer) {
125   // TODO: Implement dump
126   unsupported(__func__, size, buffer);
127 }
128
129 uint32_t DrmHwcTwo::GetMaxVirtualDisplayCount() {
130   // TODO: Implement virtual display
131   unsupported(__func__);
132   return 0;
133 }
134
135 HWC2::Error DrmHwcTwo::RegisterCallback(int32_t descriptor,
136                                         hwc2_callback_data_t data,
137                                         hwc2_function_pointer_t function) {
138   supported(__func__);
139   auto callback = static_cast<HWC2::Callback>(descriptor);
140   callbacks_.emplace(callback, HwcCallback(data, function));
141
142   switch (callback) {
143     case HWC2::Callback::Hotplug: {
144       auto hotplug = reinterpret_cast<HWC2_PFN_HOTPLUG>(function);
145       hotplug(data, HWC_DISPLAY_PRIMARY,
146               static_cast<int32_t>(HWC2::Connection::Connected));
147       break;
148     }
149     case HWC2::Callback::Vsync: {
150       for (std::pair<const hwc2_display_t, DrmHwcTwo::HwcDisplay> &d :
151            displays_)
152         d.second.RegisterVsyncCallback(data, function);
153       break;
154     }
155     default:
156       break;
157   }
158   return HWC2::Error::None;
159 }
160
161 DrmHwcTwo::HwcDisplay::HwcDisplay(DrmResources *drm,
162                                   std::shared_ptr<Importer> importer,
163                                   const gralloc_module_t *gralloc,
164                                   hwc2_display_t handle, HWC2::DisplayType type)
165     : drm_(drm),
166       importer_(importer),
167       gralloc_(gralloc),
168       handle_(handle),
169       type_(type) {
170   supported(__func__);
171 }
172
173 HWC2::Error DrmHwcTwo::HwcDisplay::Init(std::vector<DrmPlane *> *planes) {
174   supported(__func__);
175   planner_ = Planner::CreateInstance(drm_);
176   if (!planner_) {
177     ALOGE("Failed to create planner instance for composition");
178     return HWC2::Error::NoResources;
179   }
180
181   int display = static_cast<int>(handle_);
182   int ret = compositor_.Init(drm_, display);
183   if (ret) {
184     ALOGE("Failed display compositor init for display %d (%d)", display, ret);
185     return HWC2::Error::NoResources;
186   }
187
188   // Split up the given display planes into primary and overlay to properly
189   // interface with the composition
190   char use_overlay_planes_prop[PROPERTY_VALUE_MAX];
191   property_get("hwc.drm.use_overlay_planes", use_overlay_planes_prop, "1");
192   bool use_overlay_planes = atoi(use_overlay_planes_prop);
193   for (auto &plane : *planes) {
194     if (plane->type() == DRM_PLANE_TYPE_PRIMARY)
195       primary_planes_.push_back(plane);
196     else if (use_overlay_planes && (plane)->type() == DRM_PLANE_TYPE_OVERLAY)
197       overlay_planes_.push_back(plane);
198   }
199
200   crtc_ = drm_->GetCrtcForDisplay(display);
201   if (!crtc_) {
202     ALOGE("Failed to get crtc for display %d", display);
203     return HWC2::Error::BadDisplay;
204   }
205
206   connector_ = drm_->GetConnectorForDisplay(display);
207   if (!connector_) {
208     ALOGE("Failed to get connector for display %d", display);
209     return HWC2::Error::BadDisplay;
210   }
211
212   // Fetch the number of modes from the display
213   uint32_t num_configs;
214   HWC2::Error err = GetDisplayConfigs(&num_configs, NULL);
215   if (err != HWC2::Error::None || !num_configs)
216     return err;
217
218   // Grab the first mode, we'll choose this as the active mode
219   // TODO: Should choose the preferred mode here
220   hwc2_config_t default_config;
221   num_configs = 1;
222   err = GetDisplayConfigs(&num_configs, &default_config);
223   if (err != HWC2::Error::None)
224     return err;
225
226   ret = vsync_worker_.Init(drm_, display);
227   if (ret) {
228     ALOGE("Failed to create event worker for d=%d %d\n", display, ret);
229     return HWC2::Error::BadDisplay;
230   }
231
232   return SetActiveConfig(default_config);
233 }
234
235 HWC2::Error DrmHwcTwo::HwcDisplay::RegisterVsyncCallback(
236     hwc2_callback_data_t data, hwc2_function_pointer_t func) {
237   supported(__func__);
238   auto callback = std::make_shared<DrmVsyncCallback>(data, func);
239   vsync_worker_.RegisterCallback(std::move(callback));
240   return HWC2::Error::None;
241 }
242
243 HWC2::Error DrmHwcTwo::HwcDisplay::AcceptDisplayChanges() {
244   supported(__func__);
245   uint32_t num_changes = 0;
246   for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : layers_)
247     l.second.accept_type_change();
248   return HWC2::Error::None;
249 }
250
251 HWC2::Error DrmHwcTwo::HwcDisplay::CreateLayer(hwc2_layer_t *layer) {
252   supported(__func__);
253   layers_.emplace(static_cast<hwc2_layer_t>(layer_idx_), HwcLayer());
254   *layer = static_cast<hwc2_layer_t>(layer_idx_);
255   ++layer_idx_;
256   return HWC2::Error::None;
257 }
258
259 HWC2::Error DrmHwcTwo::HwcDisplay::DestroyLayer(hwc2_layer_t layer) {
260   supported(__func__);
261   layers_.erase(layer);
262   return HWC2::Error::None;
263 }
264
265 HWC2::Error DrmHwcTwo::HwcDisplay::GetActiveConfig(hwc2_config_t *config) {
266   supported(__func__);
267   DrmMode const &mode = connector_->active_mode();
268   if (mode.id() == 0)
269     return HWC2::Error::BadConfig;
270
271   *config = mode.id();
272   return HWC2::Error::None;
273 }
274
275 HWC2::Error DrmHwcTwo::HwcDisplay::GetChangedCompositionTypes(
276     uint32_t *num_elements, hwc2_layer_t *layers, int32_t *types) {
277   supported(__func__);
278   uint32_t num_changes = 0;
279   for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : layers_) {
280     if (l.second.type_changed()) {
281       if (layers && num_changes < *num_elements)
282         layers[num_changes] = l.first;
283       if (types && num_changes < *num_elements)
284         types[num_changes] = static_cast<int32_t>(l.second.validated_type());
285       ++num_changes;
286     }
287   }
288   if (!layers && !types)
289     *num_elements = num_changes;
290   return HWC2::Error::None;
291 }
292
293 HWC2::Error DrmHwcTwo::HwcDisplay::GetClientTargetSupport(uint32_t width,
294                                                           uint32_t height,
295                                                           int32_t /*format*/,
296                                                           int32_t dataspace) {
297   supported(__func__);
298   std::pair<uint32_t, uint32_t> min = drm_->min_resolution();
299   std::pair<uint32_t, uint32_t> max = drm_->max_resolution();
300
301   if (width < min.first || height < min.second)
302     return HWC2::Error::Unsupported;
303
304   if (width > max.first || height > max.second)
305     return HWC2::Error::Unsupported;
306
307   if (dataspace != HAL_DATASPACE_UNKNOWN &&
308       dataspace != HAL_DATASPACE_STANDARD_UNSPECIFIED)
309     return HWC2::Error::Unsupported;
310
311   // TODO: Validate format can be handled by either GL or planes
312   return HWC2::Error::None;
313 }
314
315 HWC2::Error DrmHwcTwo::HwcDisplay::GetColorModes(uint32_t *num_modes,
316                                                  int32_t *modes) {
317   supported(__func__);
318   if (!modes)
319     *num_modes = 1;
320
321   if (modes)
322     *modes = HAL_COLOR_MODE_NATIVE;
323
324   return HWC2::Error::None;
325 }
326
327 HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayAttribute(hwc2_config_t config,
328                                                        int32_t attribute_in,
329                                                        int32_t *value) {
330   supported(__func__);
331   auto mode =
332       std::find_if(connector_->modes().begin(), connector_->modes().end(),
333                    [config](DrmMode const &m) { return m.id() == config; });
334   if (mode == connector_->modes().end()) {
335     ALOGE("Could not find active mode for %d", config);
336     return HWC2::Error::BadConfig;
337   }
338
339   static const int32_t kUmPerInch = 25400;
340   uint32_t mm_width = connector_->mm_width();
341   uint32_t mm_height = connector_->mm_height();
342   auto attribute = static_cast<HWC2::Attribute>(attribute_in);
343   switch (attribute) {
344     case HWC2::Attribute::Width:
345       *value = mode->h_display();
346       break;
347     case HWC2::Attribute::Height:
348       *value = mode->v_display();
349       break;
350     case HWC2::Attribute::VsyncPeriod:
351       // in nanoseconds
352       *value = 1000 * 1000 * 1000 / mode->v_refresh();
353       break;
354     case HWC2::Attribute::DpiX:
355       // Dots per 1000 inches
356       *value = mm_width ? (mode->h_display() * kUmPerInch) / mm_width : -1;
357       break;
358     case HWC2::Attribute::DpiY:
359       // Dots per 1000 inches
360       *value = mm_height ? (mode->v_display() * kUmPerInch) / mm_height : -1;
361       break;
362     default:
363       *value = -1;
364       return HWC2::Error::BadConfig;
365   }
366   return HWC2::Error::None;
367 }
368
369 HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayConfigs(uint32_t *num_configs,
370                                                      hwc2_config_t *configs) {
371   supported(__func__);
372   // Since this callback is normally invoked twice (once to get the count, and
373   // once to populate configs), we don't really want to read the edid
374   // redundantly. Instead, only update the modes on the first invocation. While
375   // it's possible this will result in stale modes, it'll all come out in the
376   // wash when we try to set the active config later.
377   if (!configs) {
378     int ret = connector_->UpdateModes();
379     if (ret) {
380       ALOGE("Failed to update display modes %d", ret);
381       return HWC2::Error::BadDisplay;
382     }
383   }
384
385   auto num_modes = static_cast<uint32_t>(connector_->modes().size());
386   if (!configs) {
387     *num_configs = num_modes;
388     return HWC2::Error::None;
389   }
390
391   uint32_t idx = 0;
392   for (const DrmMode &mode : connector_->modes()) {
393     if (idx >= *num_configs)
394       break;
395     configs[idx++] = mode.id();
396   }
397   *num_configs = idx;
398   return HWC2::Error::None;
399 }
400
401 HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayName(uint32_t *size, char *name) {
402   supported(__func__);
403   std::ostringstream stream;
404   stream << "display-" << connector_->id();
405   std::string string = stream.str();
406   size_t length = string.length();
407   if (!name) {
408     *size = length;
409     return HWC2::Error::None;
410   }
411
412   *size = std::min<uint32_t>(static_cast<uint32_t>(length - 1), *size);
413   strncpy(name, string.c_str(), *size);
414   return HWC2::Error::None;
415 }
416
417 HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayRequests(int32_t *display_requests,
418                                                       uint32_t *num_elements,
419                                                       hwc2_layer_t *layers,
420                                                       int32_t *layer_requests) {
421   supported(__func__);
422   // TODO: I think virtual display should request
423   //      HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT here
424   unsupported(__func__, display_requests, num_elements, layers, layer_requests);
425   *num_elements = 0;
426   return HWC2::Error::None;
427 }
428
429 HWC2::Error DrmHwcTwo::HwcDisplay::GetDisplayType(int32_t *type) {
430   supported(__func__);
431   *type = static_cast<int32_t>(type_);
432   return HWC2::Error::None;
433 }
434
435 HWC2::Error DrmHwcTwo::HwcDisplay::GetDozeSupport(int32_t *support) {
436   supported(__func__);
437   *support = 0;
438   return HWC2::Error::None;
439 }
440
441 HWC2::Error DrmHwcTwo::HwcDisplay::GetHdrCapabilities(
442     uint32_t *num_types, int32_t */*types*/, float */*max_luminance*/,
443     float */*max_average_luminance*/, float */*min_luminance*/) {
444   supported(__func__);
445   *num_types = 0;
446   return HWC2::Error::None;
447 }
448
449 HWC2::Error DrmHwcTwo::HwcDisplay::GetReleaseFences(uint32_t *num_elements,
450                                                     hwc2_layer_t *layers,
451                                                     int32_t *fences) {
452   supported(__func__);
453   uint32_t num_layers = 0;
454
455   for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : layers_) {
456     ++num_layers;
457     if (layers == NULL || fences == NULL) {
458       continue;
459     } else if (num_layers > *num_elements) {
460       ALOGW("Overflow num_elements %d/%d", num_layers, *num_elements);
461       return HWC2::Error::None;
462     }
463
464     layers[num_layers - 1] = l.first;
465     fences[num_layers - 1] = l.second.take_release_fence();
466   }
467   *num_elements = num_layers;
468   return HWC2::Error::None;
469 }
470
471 void DrmHwcTwo::HwcDisplay::AddFenceToRetireFence(int fd) {
472   supported(__func__);
473   if (fd < 0)
474     return;
475
476   if (next_retire_fence_.get() >= 0) {
477     int old_fence = next_retire_fence_.get();
478     next_retire_fence_.Set(sync_merge("dc_retire", old_fence, fd));
479   } else {
480     next_retire_fence_.Set(dup(fd));
481   }
482 }
483
484 HWC2::Error DrmHwcTwo::HwcDisplay::PresentDisplay(int32_t *retire_fence) {
485   supported(__func__);
486   std::vector<DrmCompositionDisplayLayersMap> layers_map;
487   layers_map.emplace_back();
488   DrmCompositionDisplayLayersMap &map = layers_map.back();
489
490   map.display = static_cast<int>(handle_);
491   map.geometry_changed = true;  // TODO: Fix this
492
493   // order the layers by z-order
494   bool use_client_layer = false;
495   uint32_t client_z_order = 0;
496   std::map<uint32_t, DrmHwcTwo::HwcLayer *> z_map;
497   for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : layers_) {
498     switch (l.second.validated_type()) {
499       case HWC2::Composition::Device:
500         z_map.emplace(std::make_pair(l.second.z_order(), &l.second));
501         break;
502       case HWC2::Composition::Client:
503         // Place it at the z_order of the highest client layer
504         use_client_layer = true;
505         client_z_order = std::max(client_z_order, l.second.z_order());
506         break;
507       default:
508         continue;
509     }
510   }
511   if (use_client_layer)
512     z_map.emplace(std::make_pair(client_z_order, &client_layer_));
513
514   // now that they're ordered by z, add them to the composition
515   for (std::pair<const uint32_t, DrmHwcTwo::HwcLayer *> &l : z_map) {
516     DrmHwcLayer layer;
517     l.second->PopulateDrmLayer(&layer);
518     int ret = layer.ImportBuffer(importer_.get(), gralloc_);
519     if (ret) {
520       ALOGE("Failed to import layer, ret=%d", ret);
521       return HWC2::Error::NoResources;
522     }
523     map.layers.emplace_back(std::move(layer));
524   }
525   if (map.layers.empty()) {
526     *retire_fence = -1;
527     return HWC2::Error::None;
528   }
529
530   std::unique_ptr<DrmDisplayComposition> composition =
531       compositor_.CreateComposition();
532   composition->Init(drm_, crtc_, importer_.get(), planner_.get(), frame_no_);
533
534   // TODO: Don't always assume geometry changed
535   int ret = composition->SetLayers(map.layers.data(), map.layers.size(), true);
536   if (ret) {
537     ALOGE("Failed to set layers in the composition ret=%d", ret);
538     return HWC2::Error::BadLayer;
539   }
540
541   std::vector<DrmPlane *> primary_planes(primary_planes_);
542   std::vector<DrmPlane *> overlay_planes(overlay_planes_);
543   ret = composition->Plan(compositor_.squash_state(), &primary_planes,
544                          &overlay_planes);
545   if (ret) {
546     ALOGE("Failed to plan the composition ret=%d", ret);
547     return HWC2::Error::BadConfig;
548   }
549
550   // Disable the planes we're not using
551   for (auto i = primary_planes.begin(); i != primary_planes.end();) {
552     composition->AddPlaneDisable(*i);
553     i = primary_planes.erase(i);
554   }
555   for (auto i = overlay_planes.begin(); i != overlay_planes.end();) {
556     composition->AddPlaneDisable(*i);
557     i = overlay_planes.erase(i);
558   }
559
560   AddFenceToRetireFence(composition->take_out_fence());
561
562   ret = compositor_.QueueComposition(std::move(composition));
563   if (ret) {
564     ALOGE("Failed to apply the frame composition ret=%d", ret);
565     return HWC2::Error::BadParameter;
566   }
567
568   // The retire fence returned here is for the last frame, so return it and
569   // promote the next retire fence
570   *retire_fence = retire_fence_.Release();
571   retire_fence_ = std::move(next_retire_fence_);
572
573   ++frame_no_;
574   return HWC2::Error::None;
575 }
576
577 HWC2::Error DrmHwcTwo::HwcDisplay::SetActiveConfig(hwc2_config_t config) {
578   supported(__func__);
579   auto mode =
580       std::find_if(connector_->modes().begin(), connector_->modes().end(),
581                    [config](DrmMode const &m) { return m.id() == config; });
582   if (mode == connector_->modes().end()) {
583     ALOGE("Could not find active mode for %d", config);
584     return HWC2::Error::BadConfig;
585   }
586
587   std::unique_ptr<DrmDisplayComposition> composition =
588       compositor_.CreateComposition();
589   composition->Init(drm_, crtc_, importer_.get(), planner_.get(), frame_no_);
590   int ret = composition->SetDisplayMode(*mode);
591   ret = compositor_.QueueComposition(std::move(composition));
592   if (ret) {
593     ALOGE("Failed to queue dpms composition on %d", ret);
594     return HWC2::Error::BadConfig;
595   }
596   if (connector_->active_mode().id() == 0)
597     connector_->set_active_mode(*mode);
598
599   // Setup the client layer's dimensions
600   hwc_rect_t display_frame = {.left = 0,
601                               .top = 0,
602                               .right = static_cast<int>(mode->h_display()),
603                               .bottom = static_cast<int>(mode->v_display())};
604   client_layer_.SetLayerDisplayFrame(display_frame);
605   hwc_frect_t source_crop = {.left = 0.0f,
606                              .top = 0.0f,
607                              .right = mode->h_display() + 0.0f,
608                              .bottom = mode->v_display() + 0.0f};
609   client_layer_.SetLayerSourceCrop(source_crop);
610
611   return HWC2::Error::None;
612 }
613
614 HWC2::Error DrmHwcTwo::HwcDisplay::SetClientTarget(buffer_handle_t target,
615                                                    int32_t acquire_fence,
616                                                    int32_t dataspace,
617                                                    hwc_region_t damage) {
618   supported(__func__);
619   UniqueFd uf(acquire_fence);
620
621   client_layer_.set_buffer(target);
622   client_layer_.set_acquire_fence(uf.get());
623   client_layer_.SetLayerDataspace(dataspace);
624   return HWC2::Error::None;
625 }
626
627 HWC2::Error DrmHwcTwo::HwcDisplay::SetColorMode(int32_t mode) {
628   supported(__func__);
629
630   if (mode != HAL_COLOR_MODE_NATIVE)
631     return HWC2::Error::Unsupported;
632
633   color_mode_ = mode;
634   return HWC2::Error::None;
635 }
636
637 HWC2::Error DrmHwcTwo::HwcDisplay::SetColorTransform(const float *matrix,
638                                                      int32_t hint) {
639   supported(__func__);
640   // TODO: Force client composition if we get this
641   return unsupported(__func__, matrix, hint);
642 }
643
644 HWC2::Error DrmHwcTwo::HwcDisplay::SetOutputBuffer(buffer_handle_t buffer,
645                                                    int32_t release_fence) {
646   supported(__func__);
647   // TODO: Need virtual display support
648   return unsupported(__func__, buffer, release_fence);
649 }
650
651 HWC2::Error DrmHwcTwo::HwcDisplay::SetPowerMode(int32_t mode_in) {
652   supported(__func__);
653   uint64_t dpms_value = 0;
654   auto mode = static_cast<HWC2::PowerMode>(mode_in);
655   switch (mode) {
656     case HWC2::PowerMode::Off:
657       dpms_value = DRM_MODE_DPMS_OFF;
658       break;
659     case HWC2::PowerMode::On:
660       dpms_value = DRM_MODE_DPMS_ON;
661       break;
662     default:
663       ALOGI("Power mode %d is unsupported\n", mode);
664       return HWC2::Error::Unsupported;
665   };
666
667   std::unique_ptr<DrmDisplayComposition> composition =
668       compositor_.CreateComposition();
669   composition->Init(drm_, crtc_, importer_.get(), planner_.get(), frame_no_);
670   composition->SetDpmsMode(dpms_value);
671   int ret = compositor_.QueueComposition(std::move(composition));
672   if (ret) {
673     ALOGE("Failed to apply the dpms composition ret=%d", ret);
674     return HWC2::Error::BadParameter;
675   }
676   return HWC2::Error::None;
677 }
678
679 HWC2::Error DrmHwcTwo::HwcDisplay::SetVsyncEnabled(int32_t enabled) {
680   supported(__func__);
681   vsync_worker_.VSyncControl(enabled);
682   return HWC2::Error::None;
683 }
684
685 HWC2::Error DrmHwcTwo::HwcDisplay::ValidateDisplay(uint32_t *num_types,
686                                                    uint32_t *num_requests) {
687   supported(__func__);
688   *num_types = 0;
689   *num_requests = 0;
690   for (std::pair<const hwc2_layer_t, DrmHwcTwo::HwcLayer> &l : layers_) {
691     DrmHwcTwo::HwcLayer &layer = l.second;
692     switch (layer.sf_type()) {
693       case HWC2::Composition::SolidColor:
694       case HWC2::Composition::Cursor:
695       case HWC2::Composition::Sideband:
696         layer.set_validated_type(HWC2::Composition::Client);
697         ++*num_types;
698         break;
699       default:
700         layer.set_validated_type(layer.sf_type());
701         break;
702     }
703   }
704   return HWC2::Error::None;
705 }
706
707 HWC2::Error DrmHwcTwo::HwcLayer::SetCursorPosition(int32_t x, int32_t y) {
708   supported(__func__);
709   cursor_x_ = x;
710   cursor_y_ = y;
711   return HWC2::Error::None;
712 }
713
714 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerBlendMode(int32_t mode) {
715   supported(__func__);
716   blending_ = static_cast<HWC2::BlendMode>(mode);
717   return HWC2::Error::None;
718 }
719
720 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerBuffer(buffer_handle_t buffer,
721                                                 int32_t acquire_fence) {
722   supported(__func__);
723   UniqueFd uf(acquire_fence);
724
725   // The buffer and acquire_fence are handled elsewhere
726   if (sf_type_ == HWC2::Composition::Client ||
727       sf_type_ == HWC2::Composition::Sideband ||
728       sf_type_ == HWC2::Composition::SolidColor)
729     return HWC2::Error::None;
730
731   set_buffer(buffer);
732   set_acquire_fence(uf.get());
733   return HWC2::Error::None;
734 }
735
736 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerColor(hwc_color_t color) {
737   // TODO: Punt to client composition here?
738   return unsupported(__func__, color);
739 }
740
741 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerCompositionType(int32_t type) {
742   sf_type_ = static_cast<HWC2::Composition>(type);
743   return HWC2::Error::None;
744 }
745
746 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerDataspace(int32_t dataspace) {
747   supported(__func__);
748   dataspace_ = static_cast<android_dataspace_t>(dataspace);
749   return HWC2::Error::None;
750 }
751
752 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerDisplayFrame(hwc_rect_t frame) {
753   supported(__func__);
754   display_frame_ = frame;
755   return HWC2::Error::None;
756 }
757
758 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerPlaneAlpha(float alpha) {
759   supported(__func__);
760   alpha_ = alpha;
761   return HWC2::Error::None;
762 }
763
764 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerSidebandStream(
765     const native_handle_t *stream) {
766   supported(__func__);
767   // TODO: We don't support sideband
768   return unsupported(__func__, stream);
769 }
770
771 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerSourceCrop(hwc_frect_t crop) {
772   supported(__func__);
773   source_crop_ = crop;
774   return HWC2::Error::None;
775 }
776
777 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerSurfaceDamage(hwc_region_t damage) {
778   supported(__func__);
779   // TODO: We don't use surface damage, marking as unsupported
780   unsupported(__func__, damage);
781   return HWC2::Error::None;
782 }
783
784 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerTransform(int32_t transform) {
785   supported(__func__);
786   transform_ = static_cast<HWC2::Transform>(transform);
787   return HWC2::Error::None;
788 }
789
790 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerVisibleRegion(hwc_region_t visible) {
791   supported(__func__);
792   // TODO: We don't use this information, marking as unsupported
793   unsupported(__func__, visible);
794   return HWC2::Error::None;
795 }
796
797 HWC2::Error DrmHwcTwo::HwcLayer::SetLayerZOrder(uint32_t order) {
798   supported(__func__);
799   z_order_ = order;
800   return HWC2::Error::None;
801 }
802
803 void DrmHwcTwo::HwcLayer::PopulateDrmLayer(DrmHwcLayer *layer) {
804   supported(__func__);
805   switch (blending_) {
806     case HWC2::BlendMode::None:
807       layer->blending = DrmHwcBlending::kNone;
808       break;
809     case HWC2::BlendMode::Premultiplied:
810       layer->blending = DrmHwcBlending::kPreMult;
811       break;
812     case HWC2::BlendMode::Coverage:
813       layer->blending = DrmHwcBlending::kCoverage;
814       break;
815     default:
816       ALOGE("Unknown blending mode b=%d", blending_);
817       layer->blending = DrmHwcBlending::kNone;
818       break;
819   }
820
821   OutputFd release_fence = release_fence_output();
822
823   layer->sf_handle = buffer_;
824   layer->acquire_fence = acquire_fence_.Release();
825   layer->release_fence = std::move(release_fence);
826   layer->SetDisplayFrame(display_frame_);
827   layer->alpha = static_cast<uint8_t>(255.0f * alpha_ + 0.5f);
828   layer->SetSourceCrop(source_crop_);
829   layer->SetTransform(static_cast<int32_t>(transform_));
830 }
831
832 // static
833 int DrmHwcTwo::HookDevClose(hw_device_t * /*dev*/) {
834   unsupported(__func__);
835   return 0;
836 }
837
838 // static
839 void DrmHwcTwo::HookDevGetCapabilities(hwc2_device_t * /*dev*/,
840                                        uint32_t *out_count,
841                                        int32_t * /*out_capabilities*/) {
842   supported(__func__);
843   *out_count = 0;
844 }
845
846 // static
847 hwc2_function_pointer_t DrmHwcTwo::HookDevGetFunction(
848     struct hwc2_device * /*dev*/, int32_t descriptor) {
849   supported(__func__);
850   auto func = static_cast<HWC2::FunctionDescriptor>(descriptor);
851   switch (func) {
852     // Device functions
853     case HWC2::FunctionDescriptor::CreateVirtualDisplay:
854       return ToHook<HWC2_PFN_CREATE_VIRTUAL_DISPLAY>(
855           DeviceHook<int32_t, decltype(&DrmHwcTwo::CreateVirtualDisplay),
856                      &DrmHwcTwo::CreateVirtualDisplay, uint32_t, uint32_t,
857                      int32_t*, hwc2_display_t *>);
858     case HWC2::FunctionDescriptor::DestroyVirtualDisplay:
859       return ToHook<HWC2_PFN_DESTROY_VIRTUAL_DISPLAY>(
860           DeviceHook<int32_t, decltype(&DrmHwcTwo::DestroyVirtualDisplay),
861                      &DrmHwcTwo::DestroyVirtualDisplay, hwc2_display_t>);
862     case HWC2::FunctionDescriptor::Dump:
863       return ToHook<HWC2_PFN_DUMP>(
864           DeviceHook<void, decltype(&DrmHwcTwo::Dump), &DrmHwcTwo::Dump,
865                      uint32_t *, char *>);
866     case HWC2::FunctionDescriptor::GetMaxVirtualDisplayCount:
867       return ToHook<HWC2_PFN_GET_MAX_VIRTUAL_DISPLAY_COUNT>(
868           DeviceHook<uint32_t, decltype(&DrmHwcTwo::GetMaxVirtualDisplayCount),
869                      &DrmHwcTwo::GetMaxVirtualDisplayCount>);
870     case HWC2::FunctionDescriptor::RegisterCallback:
871       return ToHook<HWC2_PFN_REGISTER_CALLBACK>(
872           DeviceHook<int32_t, decltype(&DrmHwcTwo::RegisterCallback),
873                      &DrmHwcTwo::RegisterCallback, int32_t,
874                      hwc2_callback_data_t, hwc2_function_pointer_t>);
875
876     // Display functions
877     case HWC2::FunctionDescriptor::AcceptDisplayChanges:
878       return ToHook<HWC2_PFN_ACCEPT_DISPLAY_CHANGES>(
879           DisplayHook<decltype(&HwcDisplay::AcceptDisplayChanges),
880                       &HwcDisplay::AcceptDisplayChanges>);
881     case HWC2::FunctionDescriptor::CreateLayer:
882       return ToHook<HWC2_PFN_CREATE_LAYER>(
883           DisplayHook<decltype(&HwcDisplay::CreateLayer),
884                       &HwcDisplay::CreateLayer, hwc2_layer_t *>);
885     case HWC2::FunctionDescriptor::DestroyLayer:
886       return ToHook<HWC2_PFN_DESTROY_LAYER>(
887           DisplayHook<decltype(&HwcDisplay::DestroyLayer),
888                       &HwcDisplay::DestroyLayer, hwc2_layer_t>);
889     case HWC2::FunctionDescriptor::GetActiveConfig:
890       return ToHook<HWC2_PFN_GET_ACTIVE_CONFIG>(
891           DisplayHook<decltype(&HwcDisplay::GetActiveConfig),
892                       &HwcDisplay::GetActiveConfig, hwc2_config_t *>);
893     case HWC2::FunctionDescriptor::GetChangedCompositionTypes:
894       return ToHook<HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES>(
895           DisplayHook<decltype(&HwcDisplay::GetChangedCompositionTypes),
896                       &HwcDisplay::GetChangedCompositionTypes, uint32_t *,
897                       hwc2_layer_t *, int32_t *>);
898     case HWC2::FunctionDescriptor::GetClientTargetSupport:
899       return ToHook<HWC2_PFN_GET_CLIENT_TARGET_SUPPORT>(
900           DisplayHook<decltype(&HwcDisplay::GetClientTargetSupport),
901                       &HwcDisplay::GetClientTargetSupport, uint32_t, uint32_t,
902                       int32_t, int32_t>);
903     case HWC2::FunctionDescriptor::GetColorModes:
904       return ToHook<HWC2_PFN_GET_COLOR_MODES>(
905           DisplayHook<decltype(&HwcDisplay::GetColorModes),
906                       &HwcDisplay::GetColorModes, uint32_t *, int32_t *>);
907     case HWC2::FunctionDescriptor::GetDisplayAttribute:
908       return ToHook<HWC2_PFN_GET_DISPLAY_ATTRIBUTE>(DisplayHook<
909           decltype(&HwcDisplay::GetDisplayAttribute),
910           &HwcDisplay::GetDisplayAttribute, hwc2_config_t, int32_t, int32_t *>);
911     case HWC2::FunctionDescriptor::GetDisplayConfigs:
912       return ToHook<HWC2_PFN_GET_DISPLAY_CONFIGS>(DisplayHook<
913           decltype(&HwcDisplay::GetDisplayConfigs),
914           &HwcDisplay::GetDisplayConfigs, uint32_t *, hwc2_config_t *>);
915     case HWC2::FunctionDescriptor::GetDisplayName:
916       return ToHook<HWC2_PFN_GET_DISPLAY_NAME>(
917           DisplayHook<decltype(&HwcDisplay::GetDisplayName),
918                       &HwcDisplay::GetDisplayName, uint32_t *, char *>);
919     case HWC2::FunctionDescriptor::GetDisplayRequests:
920       return ToHook<HWC2_PFN_GET_DISPLAY_REQUESTS>(
921           DisplayHook<decltype(&HwcDisplay::GetDisplayRequests),
922                       &HwcDisplay::GetDisplayRequests, int32_t *, uint32_t *,
923                       hwc2_layer_t *, int32_t *>);
924     case HWC2::FunctionDescriptor::GetDisplayType:
925       return ToHook<HWC2_PFN_GET_DISPLAY_TYPE>(
926           DisplayHook<decltype(&HwcDisplay::GetDisplayType),
927                       &HwcDisplay::GetDisplayType, int32_t *>);
928     case HWC2::FunctionDescriptor::GetDozeSupport:
929       return ToHook<HWC2_PFN_GET_DOZE_SUPPORT>(
930           DisplayHook<decltype(&HwcDisplay::GetDozeSupport),
931                       &HwcDisplay::GetDozeSupport, int32_t *>);
932     case HWC2::FunctionDescriptor::GetHdrCapabilities:
933       return ToHook<HWC2_PFN_GET_HDR_CAPABILITIES>(
934           DisplayHook<decltype(&HwcDisplay::GetHdrCapabilities),
935                       &HwcDisplay::GetHdrCapabilities, uint32_t *, int32_t *,
936                       float *, float *, float *>);
937     case HWC2::FunctionDescriptor::GetReleaseFences:
938       return ToHook<HWC2_PFN_GET_RELEASE_FENCES>(
939           DisplayHook<decltype(&HwcDisplay::GetReleaseFences),
940                       &HwcDisplay::GetReleaseFences, uint32_t *, hwc2_layer_t *,
941                       int32_t *>);
942     case HWC2::FunctionDescriptor::PresentDisplay:
943       return ToHook<HWC2_PFN_PRESENT_DISPLAY>(
944           DisplayHook<decltype(&HwcDisplay::PresentDisplay),
945                       &HwcDisplay::PresentDisplay, int32_t *>);
946     case HWC2::FunctionDescriptor::SetActiveConfig:
947       return ToHook<HWC2_PFN_SET_ACTIVE_CONFIG>(
948           DisplayHook<decltype(&HwcDisplay::SetActiveConfig),
949                       &HwcDisplay::SetActiveConfig, hwc2_config_t>);
950     case HWC2::FunctionDescriptor::SetClientTarget:
951       return ToHook<HWC2_PFN_SET_CLIENT_TARGET>(DisplayHook<
952           decltype(&HwcDisplay::SetClientTarget), &HwcDisplay::SetClientTarget,
953           buffer_handle_t, int32_t, int32_t, hwc_region_t>);
954     case HWC2::FunctionDescriptor::SetColorMode:
955       return ToHook<HWC2_PFN_SET_COLOR_MODE>(
956           DisplayHook<decltype(&HwcDisplay::SetColorMode),
957                       &HwcDisplay::SetColorMode, int32_t>);
958     case HWC2::FunctionDescriptor::SetColorTransform:
959       return ToHook<HWC2_PFN_SET_COLOR_TRANSFORM>(
960           DisplayHook<decltype(&HwcDisplay::SetColorTransform),
961                       &HwcDisplay::SetColorTransform, const float *, int32_t>);
962     case HWC2::FunctionDescriptor::SetOutputBuffer:
963       return ToHook<HWC2_PFN_SET_OUTPUT_BUFFER>(
964           DisplayHook<decltype(&HwcDisplay::SetOutputBuffer),
965                       &HwcDisplay::SetOutputBuffer, buffer_handle_t, int32_t>);
966     case HWC2::FunctionDescriptor::SetPowerMode:
967       return ToHook<HWC2_PFN_SET_POWER_MODE>(
968           DisplayHook<decltype(&HwcDisplay::SetPowerMode),
969                       &HwcDisplay::SetPowerMode, int32_t>);
970     case HWC2::FunctionDescriptor::SetVsyncEnabled:
971       return ToHook<HWC2_PFN_SET_VSYNC_ENABLED>(
972           DisplayHook<decltype(&HwcDisplay::SetVsyncEnabled),
973                       &HwcDisplay::SetVsyncEnabled, int32_t>);
974     case HWC2::FunctionDescriptor::ValidateDisplay:
975       return ToHook<HWC2_PFN_VALIDATE_DISPLAY>(
976           DisplayHook<decltype(&HwcDisplay::ValidateDisplay),
977                       &HwcDisplay::ValidateDisplay, uint32_t *, uint32_t *>);
978
979     // Layer functions
980     case HWC2::FunctionDescriptor::SetCursorPosition:
981       return ToHook<HWC2_PFN_SET_CURSOR_POSITION>(
982           LayerHook<decltype(&HwcLayer::SetCursorPosition),
983                     &HwcLayer::SetCursorPosition, int32_t, int32_t>);
984     case HWC2::FunctionDescriptor::SetLayerBlendMode:
985       return ToHook<HWC2_PFN_SET_LAYER_BLEND_MODE>(
986           LayerHook<decltype(&HwcLayer::SetLayerBlendMode),
987                     &HwcLayer::SetLayerBlendMode, int32_t>);
988     case HWC2::FunctionDescriptor::SetLayerBuffer:
989       return ToHook<HWC2_PFN_SET_LAYER_BUFFER>(
990           LayerHook<decltype(&HwcLayer::SetLayerBuffer),
991                     &HwcLayer::SetLayerBuffer, buffer_handle_t, int32_t>);
992     case HWC2::FunctionDescriptor::SetLayerColor:
993       return ToHook<HWC2_PFN_SET_LAYER_COLOR>(
994           LayerHook<decltype(&HwcLayer::SetLayerColor),
995                     &HwcLayer::SetLayerColor, hwc_color_t>);
996     case HWC2::FunctionDescriptor::SetLayerCompositionType:
997       return ToHook<HWC2_PFN_SET_LAYER_COMPOSITION_TYPE>(
998           LayerHook<decltype(&HwcLayer::SetLayerCompositionType),
999                     &HwcLayer::SetLayerCompositionType, int32_t>);
1000     case HWC2::FunctionDescriptor::SetLayerDataspace:
1001       return ToHook<HWC2_PFN_SET_LAYER_DATASPACE>(
1002           LayerHook<decltype(&HwcLayer::SetLayerDataspace),
1003                     &HwcLayer::SetLayerDataspace, int32_t>);
1004     case HWC2::FunctionDescriptor::SetLayerDisplayFrame:
1005       return ToHook<HWC2_PFN_SET_LAYER_DISPLAY_FRAME>(
1006           LayerHook<decltype(&HwcLayer::SetLayerDisplayFrame),
1007                     &HwcLayer::SetLayerDisplayFrame, hwc_rect_t>);
1008     case HWC2::FunctionDescriptor::SetLayerPlaneAlpha:
1009       return ToHook<HWC2_PFN_SET_LAYER_PLANE_ALPHA>(
1010           LayerHook<decltype(&HwcLayer::SetLayerPlaneAlpha),
1011                     &HwcLayer::SetLayerPlaneAlpha, float>);
1012     case HWC2::FunctionDescriptor::SetLayerSidebandStream:
1013       return ToHook<HWC2_PFN_SET_LAYER_SIDEBAND_STREAM>(LayerHook<
1014           decltype(&HwcLayer::SetLayerSidebandStream),
1015           &HwcLayer::SetLayerSidebandStream, const native_handle_t *>);
1016     case HWC2::FunctionDescriptor::SetLayerSourceCrop:
1017       return ToHook<HWC2_PFN_SET_LAYER_SOURCE_CROP>(
1018           LayerHook<decltype(&HwcLayer::SetLayerSourceCrop),
1019                     &HwcLayer::SetLayerSourceCrop, hwc_frect_t>);
1020     case HWC2::FunctionDescriptor::SetLayerSurfaceDamage:
1021       return ToHook<HWC2_PFN_SET_LAYER_SURFACE_DAMAGE>(
1022           LayerHook<decltype(&HwcLayer::SetLayerSurfaceDamage),
1023                     &HwcLayer::SetLayerSurfaceDamage, hwc_region_t>);
1024     case HWC2::FunctionDescriptor::SetLayerTransform:
1025       return ToHook<HWC2_PFN_SET_LAYER_TRANSFORM>(
1026           LayerHook<decltype(&HwcLayer::SetLayerTransform),
1027                     &HwcLayer::SetLayerTransform, int32_t>);
1028     case HWC2::FunctionDescriptor::SetLayerVisibleRegion:
1029       return ToHook<HWC2_PFN_SET_LAYER_VISIBLE_REGION>(
1030           LayerHook<decltype(&HwcLayer::SetLayerVisibleRegion),
1031                     &HwcLayer::SetLayerVisibleRegion, hwc_region_t>);
1032     case HWC2::FunctionDescriptor::SetLayerZOrder:
1033       return ToHook<HWC2_PFN_SET_LAYER_Z_ORDER>(
1034           LayerHook<decltype(&HwcLayer::SetLayerZOrder),
1035                     &HwcLayer::SetLayerZOrder, uint32_t>);
1036     case HWC2::FunctionDescriptor::Invalid:
1037     default:
1038       return NULL;
1039   }
1040 }
1041
1042 // static
1043 int DrmHwcTwo::HookDevOpen(const struct hw_module_t *module, const char *name,
1044                            struct hw_device_t **dev) {
1045   supported(__func__);
1046   if (strcmp(name, HWC_HARDWARE_COMPOSER)) {
1047     ALOGE("Invalid module name- %s", name);
1048     return -EINVAL;
1049   }
1050
1051   std::unique_ptr<DrmHwcTwo> ctx(new DrmHwcTwo());
1052   if (!ctx) {
1053     ALOGE("Failed to allocate DrmHwcTwo");
1054     return -ENOMEM;
1055   }
1056
1057   HWC2::Error err = ctx->Init();
1058   if (err != HWC2::Error::None) {
1059     ALOGE("Failed to initialize DrmHwcTwo err=%d\n", err);
1060     return -EINVAL;
1061   }
1062
1063   ctx->common.module = const_cast<hw_module_t *>(module);
1064   *dev = &ctx->common;
1065   ctx.release();
1066   return 0;
1067 }
1068 }
1069
1070 static struct hw_module_methods_t hwc2_module_methods = {
1071     .open = android::DrmHwcTwo::HookDevOpen,
1072 };
1073
1074 hw_module_t HAL_MODULE_INFO_SYM = {
1075     .tag = HARDWARE_MODULE_TAG,
1076     .module_api_version = HARDWARE_MODULE_API_VERSION(2, 0),
1077     .id = HWC_HARDWARE_MODULE_ID,
1078     .name = "DrmHwcTwo module",
1079     .author = "The Android Open Source Project",
1080     .methods = &hwc2_module_methods,
1081     .dso = NULL,
1082     .reserved = {0},
1083 };