OSDN Git Service

drm_hwcomposer: Tidy-up DrmConnector class
[android-x86/external-drm_hwcomposer.git] / hwc2_device / HwcDisplay.cpp
1 /*
2  * Copyright (C) 2022 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 #define LOG_TAG "hwc-display"
18 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
19
20 #include "HwcDisplay.h"
21
22 #include "DrmHwcTwo.h"
23 #include "backend/BackendManager.h"
24 #include "bufferinfo/BufferInfoGetter.h"
25 #include "utils/log.h"
26 #include "utils/properties.h"
27
28 namespace android {
29
30 std::string HwcDisplay::DumpDelta(HwcDisplay::Stats delta) {
31   if (delta.total_pixops_ == 0)
32     return "No stats yet";
33   double ratio = 1.0 - double(delta.gpu_pixops_) / double(delta.total_pixops_);
34
35   std::stringstream ss;
36   ss << " Total frames count: " << delta.total_frames_ << "\n"
37      << " Failed to test commit frames: " << delta.failed_kms_validate_ << "\n"
38      << " Failed to commit frames: " << delta.failed_kms_present_ << "\n"
39      << ((delta.failed_kms_present_ > 0)
40              ? " !!! Internal failure, FIX it please\n"
41              : "")
42      << " Flattened frames: " << delta.frames_flattened_ << "\n"
43      << " Pixel operations (free units)"
44      << " : [TOTAL: " << delta.total_pixops_ << " / GPU: " << delta.gpu_pixops_
45      << "]\n"
46      << " Composition efficiency: " << ratio;
47
48   return ss.str();
49 }
50
51 std::string HwcDisplay::Dump() {
52   std::string flattening_state_str;
53   switch (flattenning_state_) {
54     case ClientFlattenningState::Disabled:
55       flattening_state_str = "Disabled";
56       break;
57     case ClientFlattenningState::NotRequired:
58       flattening_state_str = "Not needed";
59       break;
60     case ClientFlattenningState::Flattened:
61       flattening_state_str = "Active";
62       break;
63     case ClientFlattenningState::ClientRefreshRequested:
64       flattening_state_str = "Refresh requested";
65       break;
66     default:
67       flattening_state_str = std::to_string(flattenning_state_) +
68                              " VSync remains";
69   }
70
71   std::stringstream ss;
72   ss << "- Display on: " << connector_->GetName() << "\n"
73      << "  Flattening state: " << flattening_state_str << "\n"
74      << "Statistics since system boot:\n"
75      << DumpDelta(total_stats_) << "\n\n"
76      << "Statistics since last dumpsys request:\n"
77      << DumpDelta(total_stats_.minus(prev_stats_)) << "\n\n";
78
79   memcpy(&prev_stats_, &total_stats_, sizeof(Stats));
80   return ss.str();
81 }
82
83 HwcDisplay::HwcDisplay(ResourceManager *resource_manager, DrmDevice *drm,
84                        hwc2_display_t handle, HWC2::DisplayType type,
85                        DrmHwcTwo *hwc2)
86     : hwc2_(hwc2),
87       resource_manager_(resource_manager),
88       drm_(drm),
89       handle_(handle),
90       type_(type),
91       color_transform_hint_(HAL_COLOR_TRANSFORM_IDENTITY) {
92   // clang-format off
93   color_transform_matrix_ = {1.0, 0.0, 0.0, 0.0,
94                              0.0, 1.0, 0.0, 0.0,
95                              0.0, 0.0, 1.0, 0.0,
96                              0.0, 0.0, 0.0, 1.0};
97   // clang-format on
98 }
99
100 void HwcDisplay::ClearDisplay() {
101   if (IsInHeadlessMode()) {
102     ALOGE("%s: Headless mode, should never reach here: ", __func__);
103     return;
104   }
105
106   AtomicCommitArgs a_args = {.clear_active_composition = true};
107   compositor_.ExecuteAtomicCommit(a_args);
108 }
109
110 HWC2::Error HwcDisplay::Init(std::vector<DrmPlane *> *planes) {
111   int display = static_cast<int>(handle_);
112   int ret = compositor_.Init(resource_manager_, display);
113   if (ret) {
114     ALOGE("Failed display compositor init for display %d (%d)", display, ret);
115     return HWC2::Error::NoResources;
116   }
117
118   // Split up the given display planes into primary and overlay to properly
119   // interface with the composition
120   char use_overlay_planes_prop[PROPERTY_VALUE_MAX];
121   property_get("vendor.hwc.drm.use_overlay_planes", use_overlay_planes_prop,
122                "1");
123   bool use_overlay_planes = strtol(use_overlay_planes_prop, nullptr, 10);
124   for (auto &plane : *planes) {
125     if (plane->GetType() == DRM_PLANE_TYPE_PRIMARY)
126       primary_planes_.push_back(plane);
127     else if (use_overlay_planes && (plane)->GetType() == DRM_PLANE_TYPE_OVERLAY)
128       overlay_planes_.push_back(plane);
129   }
130
131   crtc_ = drm_->GetCrtcForDisplay(display);
132   if (!crtc_) {
133     ALOGE("Failed to get crtc for display %d", display);
134     return HWC2::Error::BadDisplay;
135   }
136
137   connector_ = drm_->GetConnectorForDisplay(display);
138   if (!connector_) {
139     ALOGE("Failed to get connector for display %d", display);
140     return HWC2::Error::BadDisplay;
141   }
142
143   ret = vsync_worker_.Init(drm_, display, [this](int64_t timestamp) {
144     const std::lock_guard<std::mutex> lock(hwc2_->GetResMan().GetMainLock());
145     /* vsync callback */
146 #if PLATFORM_SDK_VERSION > 29
147     if (hwc2_->vsync_2_4_callback_.first != nullptr &&
148         hwc2_->vsync_2_4_callback_.second != nullptr) {
149       hwc2_vsync_period_t period_ns{};
150       GetDisplayVsyncPeriod(&period_ns);
151       hwc2_->vsync_2_4_callback_.first(hwc2_->vsync_2_4_callback_.second,
152                                        handle_, timestamp, period_ns);
153     } else
154 #endif
155         if (hwc2_->vsync_callback_.first != nullptr &&
156             hwc2_->vsync_callback_.second != nullptr) {
157       hwc2_->vsync_callback_.first(hwc2_->vsync_callback_.second, handle_,
158                                    timestamp);
159     }
160   });
161   if (ret) {
162     ALOGE("Failed to create event worker for d=%d %d\n", display, ret);
163     return HWC2::Error::BadDisplay;
164   }
165
166   ret = flattening_vsync_worker_
167             .Init(drm_, display, [this](int64_t /*timestamp*/) {
168               const std::lock_guard<std::mutex> lock(
169                   hwc2_->GetResMan().GetMainLock());
170               /* Frontend flattening */
171               if (flattenning_state_ >
172                       ClientFlattenningState::ClientRefreshRequested &&
173                   --flattenning_state_ ==
174                       ClientFlattenningState::ClientRefreshRequested &&
175                   hwc2_->refresh_callback_.first != nullptr &&
176                   hwc2_->refresh_callback_.second != nullptr) {
177                 hwc2_->refresh_callback_.first(hwc2_->refresh_callback_.second,
178                                                handle_);
179                 flattening_vsync_worker_.VSyncControl(false);
180               }
181             });
182   if (ret) {
183     ALOGE("Failed to create event worker for d=%d %d\n", display, ret);
184     return HWC2::Error::BadDisplay;
185   }
186
187   ret = BackendManager::GetInstance().SetBackendForDisplay(this);
188   if (ret) {
189     ALOGE("Failed to set backend for d=%d %d\n", display, ret);
190     return HWC2::Error::BadDisplay;
191   }
192
193   client_layer_.SetLayerBlendMode(HWC2_BLEND_MODE_PREMULTIPLIED);
194
195   return ChosePreferredConfig();
196 }
197
198 HWC2::Error HwcDisplay::ChosePreferredConfig() {
199   HWC2::Error err = configs_.Update(*connector_);
200   if (!IsInHeadlessMode() && err != HWC2::Error::None)
201     return HWC2::Error::BadDisplay;
202
203   return SetActiveConfig(configs_.preferred_config_id);
204 }
205
206 HWC2::Error HwcDisplay::AcceptDisplayChanges() {
207   for (std::pair<const hwc2_layer_t, HwcLayer> &l : layers_)
208     l.second.AcceptTypeChange();
209   return HWC2::Error::None;
210 }
211
212 HWC2::Error HwcDisplay::CreateLayer(hwc2_layer_t *layer) {
213   layers_.emplace(static_cast<hwc2_layer_t>(layer_idx_), HwcLayer());
214   *layer = static_cast<hwc2_layer_t>(layer_idx_);
215   ++layer_idx_;
216   return HWC2::Error::None;
217 }
218
219 HWC2::Error HwcDisplay::DestroyLayer(hwc2_layer_t layer) {
220   if (!get_layer(layer))
221     return HWC2::Error::BadLayer;
222
223   layers_.erase(layer);
224   return HWC2::Error::None;
225 }
226
227 HWC2::Error HwcDisplay::GetActiveConfig(hwc2_config_t *config) const {
228   if (configs_.hwc_configs.count(configs_.active_config_id) == 0)
229     return HWC2::Error::BadConfig;
230
231   *config = configs_.active_config_id;
232   return HWC2::Error::None;
233 }
234
235 HWC2::Error HwcDisplay::GetChangedCompositionTypes(uint32_t *num_elements,
236                                                    hwc2_layer_t *layers,
237                                                    int32_t *types) {
238   if (IsInHeadlessMode()) {
239     *num_elements = 0;
240     return HWC2::Error::None;
241   }
242
243   uint32_t num_changes = 0;
244   for (std::pair<const hwc2_layer_t, HwcLayer> &l : layers_) {
245     if (l.second.IsTypeChanged()) {
246       if (layers && num_changes < *num_elements)
247         layers[num_changes] = l.first;
248       if (types && num_changes < *num_elements)
249         types[num_changes] = static_cast<int32_t>(l.second.GetValidatedType());
250       ++num_changes;
251     }
252   }
253   if (!layers && !types)
254     *num_elements = num_changes;
255   return HWC2::Error::None;
256 }
257
258 HWC2::Error HwcDisplay::GetClientTargetSupport(uint32_t width, uint32_t height,
259                                                int32_t /*format*/,
260                                                int32_t dataspace) {
261   std::pair<uint32_t, uint32_t> min = drm_->min_resolution();
262   std::pair<uint32_t, uint32_t> max = drm_->max_resolution();
263   if (IsInHeadlessMode()) {
264     return HWC2::Error::None;
265   }
266
267   if (width < min.first || height < min.second)
268     return HWC2::Error::Unsupported;
269
270   if (width > max.first || height > max.second)
271     return HWC2::Error::Unsupported;
272
273   if (dataspace != HAL_DATASPACE_UNKNOWN)
274     return HWC2::Error::Unsupported;
275
276   // TODO(nobody): Validate format can be handled by either GL or planes
277   return HWC2::Error::None;
278 }
279
280 HWC2::Error HwcDisplay::GetColorModes(uint32_t *num_modes, int32_t *modes) {
281   if (!modes)
282     *num_modes = 1;
283
284   if (modes)
285     *modes = HAL_COLOR_MODE_NATIVE;
286
287   return HWC2::Error::None;
288 }
289
290 HWC2::Error HwcDisplay::GetDisplayAttribute(hwc2_config_t config,
291                                             int32_t attribute_in,
292                                             int32_t *value) {
293   int conf = static_cast<int>(config);
294
295   if (configs_.hwc_configs.count(conf) == 0) {
296     ALOGE("Could not find active mode for %d", conf);
297     return HWC2::Error::BadConfig;
298   }
299
300   auto &hwc_config = configs_.hwc_configs[conf];
301
302   static const int32_t kUmPerInch = 25400;
303   uint32_t mm_width = configs_.mm_width;
304   uint32_t mm_height = configs_.mm_height;
305   auto attribute = static_cast<HWC2::Attribute>(attribute_in);
306   switch (attribute) {
307     case HWC2::Attribute::Width:
308       *value = static_cast<int>(hwc_config.mode.h_display());
309       break;
310     case HWC2::Attribute::Height:
311       *value = static_cast<int>(hwc_config.mode.v_display());
312       break;
313     case HWC2::Attribute::VsyncPeriod:
314       // in nanoseconds
315       *value = static_cast<int>(1E9 / hwc_config.mode.v_refresh());
316       break;
317     case HWC2::Attribute::DpiX:
318       // Dots per 1000 inches
319       *value = mm_width ? static_cast<int>(hwc_config.mode.h_display() *
320                                            kUmPerInch / mm_width)
321                         : -1;
322       break;
323     case HWC2::Attribute::DpiY:
324       // Dots per 1000 inches
325       *value = mm_height ? static_cast<int>(hwc_config.mode.v_display() *
326                                             kUmPerInch / mm_height)
327                          : -1;
328       break;
329 #if PLATFORM_SDK_VERSION > 29
330     case HWC2::Attribute::ConfigGroup:
331       /* Dispite ConfigGroup is a part of HWC2.4 API, framework
332        * able to request it even if service @2.1 is used */
333       *value = hwc_config.group_id;
334       break;
335 #endif
336     default:
337       *value = -1;
338       return HWC2::Error::BadConfig;
339   }
340   return HWC2::Error::None;
341 }
342
343 HWC2::Error HwcDisplay::GetDisplayConfigs(uint32_t *num_configs,
344                                           hwc2_config_t *configs) {
345   uint32_t idx = 0;
346   for (auto &hwc_config : configs_.hwc_configs) {
347     if (hwc_config.second.disabled) {
348       continue;
349     }
350
351     if (configs != nullptr) {
352       if (idx >= *num_configs) {
353         break;
354       }
355       configs[idx] = hwc_config.second.id;
356     }
357
358     idx++;
359   }
360   *num_configs = idx;
361   return HWC2::Error::None;
362 }
363
364 HWC2::Error HwcDisplay::GetDisplayName(uint32_t *size, char *name) {
365   std::ostringstream stream;
366   stream << "display-" << connector_->GetId();
367   std::string string = stream.str();
368   size_t length = string.length();
369   if (!name) {
370     *size = length;
371     return HWC2::Error::None;
372   }
373
374   *size = std::min<uint32_t>(static_cast<uint32_t>(length - 1), *size);
375   strncpy(name, string.c_str(), *size);
376   return HWC2::Error::None;
377 }
378
379 HWC2::Error HwcDisplay::GetDisplayRequests(int32_t * /*display_requests*/,
380                                            uint32_t *num_elements,
381                                            hwc2_layer_t * /*layers*/,
382                                            int32_t * /*layer_requests*/) {
383   // TODO(nobody): I think virtual display should request
384   //      HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT here
385   *num_elements = 0;
386   return HWC2::Error::None;
387 }
388
389 HWC2::Error HwcDisplay::GetDisplayType(int32_t *type) {
390   *type = static_cast<int32_t>(type_);
391   return HWC2::Error::None;
392 }
393
394 HWC2::Error HwcDisplay::GetDozeSupport(int32_t *support) {
395   *support = 0;
396   return HWC2::Error::None;
397 }
398
399 HWC2::Error HwcDisplay::GetHdrCapabilities(uint32_t *num_types,
400                                            int32_t * /*types*/,
401                                            float * /*max_luminance*/,
402                                            float * /*max_average_luminance*/,
403                                            float * /*min_luminance*/) {
404   *num_types = 0;
405   return HWC2::Error::None;
406 }
407
408 /* Find API details at:
409  * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r3:hardware/libhardware/include/hardware/hwcomposer2.h;l=1767
410  */
411 HWC2::Error HwcDisplay::GetReleaseFences(uint32_t *num_elements,
412                                          hwc2_layer_t *layers,
413                                          int32_t *fences) {
414   if (IsInHeadlessMode()) {
415     *num_elements = 0;
416     return HWC2::Error::None;
417   }
418
419   uint32_t num_layers = 0;
420
421   for (std::pair<const hwc2_layer_t, HwcLayer> &l : layers_) {
422     ++num_layers;
423     if (layers == nullptr || fences == nullptr)
424       continue;
425
426     if (num_layers > *num_elements) {
427       ALOGW("Overflow num_elements %d/%d", num_layers, *num_elements);
428       return HWC2::Error::None;
429     }
430
431     layers[num_layers - 1] = l.first;
432     fences[num_layers - 1] = l.second.GetReleaseFence().Release();
433   }
434   *num_elements = num_layers;
435   return HWC2::Error::None;
436 }
437
438 HWC2::Error HwcDisplay::CreateComposition(AtomicCommitArgs &a_args) {
439   if (IsInHeadlessMode()) {
440     ALOGE("%s: Display is in headless mode, should never reach here", __func__);
441     return HWC2::Error::None;
442   }
443
444   // order the layers by z-order
445   bool use_client_layer = false;
446   uint32_t client_z_order = UINT32_MAX;
447   std::map<uint32_t, HwcLayer *> z_map;
448   for (std::pair<const hwc2_layer_t, HwcLayer> &l : layers_) {
449     switch (l.second.GetValidatedType()) {
450       case HWC2::Composition::Device:
451         z_map.emplace(std::make_pair(l.second.GetZOrder(), &l.second));
452         break;
453       case HWC2::Composition::Client:
454         // Place it at the z_order of the lowest client layer
455         use_client_layer = true;
456         client_z_order = std::min(client_z_order, l.second.GetZOrder());
457         break;
458       default:
459         continue;
460     }
461   }
462   if (use_client_layer)
463     z_map.emplace(std::make_pair(client_z_order, &client_layer_));
464
465   if (z_map.empty())
466     return HWC2::Error::BadLayer;
467
468   std::vector<DrmHwcLayer> composition_layers;
469
470   // now that they're ordered by z, add them to the composition
471   for (std::pair<const uint32_t, HwcLayer *> &l : z_map) {
472     DrmHwcLayer layer;
473     l.second->PopulateDrmLayer(&layer);
474     int ret = layer.ImportBuffer(drm_);
475     if (ret) {
476       ALOGE("Failed to import layer, ret=%d", ret);
477       return HWC2::Error::NoResources;
478     }
479     composition_layers.emplace_back(std::move(layer));
480   }
481
482   auto composition = std::make_shared<DrmDisplayComposition>(crtc_);
483
484   // TODO(nobody): Don't always assume geometry changed
485   int ret = composition->SetLayers(composition_layers.data(),
486                                    composition_layers.size());
487   if (ret) {
488     ALOGE("Failed to set layers in the composition ret=%d", ret);
489     return HWC2::Error::BadLayer;
490   }
491
492   std::vector<DrmPlane *> primary_planes(primary_planes_);
493   std::vector<DrmPlane *> overlay_planes(overlay_planes_);
494   ret = composition->Plan(&primary_planes, &overlay_planes);
495   if (ret) {
496     ALOGV("Failed to plan the composition ret=%d", ret);
497     return HWC2::Error::BadConfig;
498   }
499
500   a_args.composition = composition;
501   if (staged_mode) {
502     a_args.display_mode = *staged_mode;
503   }
504   ret = compositor_.ExecuteAtomicCommit(a_args);
505
506   if (ret) {
507     if (!a_args.test_only)
508       ALOGE("Failed to apply the frame composition ret=%d", ret);
509     return HWC2::Error::BadParameter;
510   }
511
512   if (!a_args.test_only) {
513     staged_mode.reset();
514   }
515
516   return HWC2::Error::None;
517 }
518
519 /* Find API details at:
520  * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r3:hardware/libhardware/include/hardware/hwcomposer2.h;l=1805
521  */
522 HWC2::Error HwcDisplay::PresentDisplay(int32_t *present_fence) {
523   if (IsInHeadlessMode()) {
524     *present_fence = -1;
525     return HWC2::Error::None;
526   }
527   HWC2::Error ret{};
528
529   ++total_stats_.total_frames_;
530
531   AtomicCommitArgs a_args{};
532   ret = CreateComposition(a_args);
533
534   if (ret != HWC2::Error::None)
535     ++total_stats_.failed_kms_present_;
536
537   if (ret == HWC2::Error::BadLayer) {
538     // Can we really have no client or device layers?
539     *present_fence = -1;
540     return HWC2::Error::None;
541   }
542   if (ret != HWC2::Error::None)
543     return ret;
544
545   *present_fence = a_args.out_fence.Release();
546
547   ++frame_no_;
548   return HWC2::Error::None;
549 }
550
551 HWC2::Error HwcDisplay::SetActiveConfig(hwc2_config_t config) {
552   int conf = static_cast<int>(config);
553
554   if (configs_.hwc_configs.count(conf) == 0) {
555     ALOGE("Could not find active mode for %d", conf);
556     return HWC2::Error::BadConfig;
557   }
558
559   auto &mode = configs_.hwc_configs[conf].mode;
560
561   staged_mode = mode;
562
563   configs_.active_config_id = conf;
564
565   // Setup the client layer's dimensions
566   hwc_rect_t display_frame = {.left = 0,
567                               .top = 0,
568                               .right = static_cast<int>(mode.h_display()),
569                               .bottom = static_cast<int>(mode.v_display())};
570   client_layer_.SetLayerDisplayFrame(display_frame);
571
572   return HWC2::Error::None;
573 }
574
575 /* Find API details at:
576  * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r3:hardware/libhardware/include/hardware/hwcomposer2.h;l=1861
577  */
578 HWC2::Error HwcDisplay::SetClientTarget(buffer_handle_t target,
579                                         int32_t acquire_fence,
580                                         int32_t dataspace,
581                                         hwc_region_t /*damage*/) {
582   client_layer_.SetLayerBuffer(target, acquire_fence);
583   client_layer_.SetLayerDataspace(dataspace);
584
585   /*
586    * target can be nullptr, this does mean the Composer Service is calling
587    * cleanDisplayResources() on after receiving HOTPLUG event. See more at:
588    * https://cs.android.com/android/platform/superproject/+/master:hardware/interfaces/graphics/composer/2.1/utils/hal/include/composer-hal/2.1/ComposerClient.h;l=350;drc=944b68180b008456ed2eb4d4d329e33b19bd5166
589    */
590   if (target == nullptr) {
591     return HWC2::Error::None;
592   }
593
594   /* TODO: Do not update source_crop every call.
595    * It makes sense to do it once after every hotplug event. */
596   HwcDrmBo bo{};
597   BufferInfoGetter::GetInstance()->ConvertBoInfo(target, &bo);
598
599   hwc_frect_t source_crop = {.left = 0.0F,
600                              .top = 0.0F,
601                              .right = static_cast<float>(bo.width),
602                              .bottom = static_cast<float>(bo.height)};
603   client_layer_.SetLayerSourceCrop(source_crop);
604
605   return HWC2::Error::None;
606 }
607
608 HWC2::Error HwcDisplay::SetColorMode(int32_t mode) {
609   if (mode < HAL_COLOR_MODE_NATIVE || mode > HAL_COLOR_MODE_BT2100_HLG)
610     return HWC2::Error::BadParameter;
611
612   if (mode != HAL_COLOR_MODE_NATIVE)
613     return HWC2::Error::Unsupported;
614
615   color_mode_ = mode;
616   return HWC2::Error::None;
617 }
618
619 HWC2::Error HwcDisplay::SetColorTransform(const float *matrix, int32_t hint) {
620   if (hint < HAL_COLOR_TRANSFORM_IDENTITY ||
621       hint > HAL_COLOR_TRANSFORM_CORRECT_TRITANOPIA)
622     return HWC2::Error::BadParameter;
623
624   if (!matrix && hint == HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX)
625     return HWC2::Error::BadParameter;
626
627   color_transform_hint_ = static_cast<android_color_transform_t>(hint);
628   if (color_transform_hint_ == HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX)
629     std::copy(matrix, matrix + MATRIX_SIZE, color_transform_matrix_.begin());
630
631   return HWC2::Error::None;
632 }
633
634 HWC2::Error HwcDisplay::SetOutputBuffer(buffer_handle_t /*buffer*/,
635                                         int32_t /*release_fence*/) {
636   // TODO(nobody): Need virtual display support
637   return HWC2::Error::Unsupported;
638 }
639
640 HWC2::Error HwcDisplay::SetPowerMode(int32_t mode_in) {
641   if (IsInHeadlessMode()) {
642     return HWC2::Error::None;
643   }
644
645   auto mode = static_cast<HWC2::PowerMode>(mode_in);
646   AtomicCommitArgs a_args{};
647
648   switch (mode) {
649     case HWC2::PowerMode::Off:
650       a_args.active = false;
651       break;
652     case HWC2::PowerMode::On:
653       /*
654        * Setting the display to active before we have a composition
655        * can break some drivers, so skip setting a_args.active to
656        * true, as the next composition frame will implicitly activate
657        * the display
658        */
659       return compositor_.ActivateDisplayUsingDPMS() == 0
660                  ? HWC2::Error::None
661                  : HWC2::Error::BadParameter;
662       break;
663     case HWC2::PowerMode::Doze:
664     case HWC2::PowerMode::DozeSuspend:
665       return HWC2::Error::Unsupported;
666     default:
667       ALOGI("Power mode %d is unsupported\n", mode);
668       return HWC2::Error::BadParameter;
669   };
670
671   int err = compositor_.ExecuteAtomicCommit(a_args);
672   if (err) {
673     ALOGE("Failed to apply the dpms composition err=%d", err);
674     return HWC2::Error::BadParameter;
675   }
676   return HWC2::Error::None;
677 }
678
679 HWC2::Error HwcDisplay::SetVsyncEnabled(int32_t enabled) {
680   vsync_worker_.VSyncControl(HWC2_VSYNC_ENABLE == enabled);
681   return HWC2::Error::None;
682 }
683
684 HWC2::Error HwcDisplay::ValidateDisplay(uint32_t *num_types,
685                                         uint32_t *num_requests) {
686   if (IsInHeadlessMode()) {
687     *num_types = *num_requests = 0;
688     return HWC2::Error::None;
689   }
690   return backend_->ValidateDisplay(this, num_types, num_requests);
691 }
692
693 std::vector<HwcLayer *> HwcDisplay::GetOrderLayersByZPos() {
694   std::vector<HwcLayer *> ordered_layers;
695   ordered_layers.reserve(layers_.size());
696
697   for (auto &[handle, layer] : layers_) {
698     ordered_layers.emplace_back(&layer);
699   }
700
701   std::sort(std::begin(ordered_layers), std::end(ordered_layers),
702             [](const HwcLayer *lhs, const HwcLayer *rhs) {
703               return lhs->GetZOrder() < rhs->GetZOrder();
704             });
705
706   return ordered_layers;
707 }
708
709 #if PLATFORM_SDK_VERSION > 29
710 HWC2::Error HwcDisplay::GetDisplayConnectionType(uint32_t *outType) {
711   if (IsInHeadlessMode()) {
712     *outType = static_cast<uint32_t>(HWC2::DisplayConnectionType::Internal);
713     return HWC2::Error::None;
714   }
715   /* Primary display should be always internal,
716    * otherwise SF will be unhappy and will crash
717    */
718   if (connector_->IsInternal() || handle_ == kPrimaryDisplay)
719     *outType = static_cast<uint32_t>(HWC2::DisplayConnectionType::Internal);
720   else if (connector_->IsExternal())
721     *outType = static_cast<uint32_t>(HWC2::DisplayConnectionType::External);
722   else
723     return HWC2::Error::BadConfig;
724
725   return HWC2::Error::None;
726 }
727
728 HWC2::Error HwcDisplay::GetDisplayVsyncPeriod(
729     hwc2_vsync_period_t *outVsyncPeriod /* ns */) {
730   return GetDisplayAttribute(configs_.active_config_id,
731                              HWC2_ATTRIBUTE_VSYNC_PERIOD,
732                              (int32_t *)(outVsyncPeriod));
733 }
734
735 HWC2::Error HwcDisplay::SetActiveConfigWithConstraints(
736     hwc2_config_t /*config*/,
737     hwc_vsync_period_change_constraints_t *vsyncPeriodChangeConstraints,
738     hwc_vsync_period_change_timeline_t *outTimeline) {
739   if (vsyncPeriodChangeConstraints == nullptr || outTimeline == nullptr) {
740     return HWC2::Error::BadParameter;
741   }
742
743   return HWC2::Error::BadConfig;
744 }
745
746 HWC2::Error HwcDisplay::SetAutoLowLatencyMode(bool /*on*/) {
747   return HWC2::Error::Unsupported;
748 }
749
750 HWC2::Error HwcDisplay::GetSupportedContentTypes(
751     uint32_t *outNumSupportedContentTypes,
752     const uint32_t *outSupportedContentTypes) {
753   if (outSupportedContentTypes == nullptr)
754     *outNumSupportedContentTypes = 0;
755
756   return HWC2::Error::None;
757 }
758
759 HWC2::Error HwcDisplay::SetContentType(int32_t contentType) {
760   if (contentType != HWC2_CONTENT_TYPE_NONE)
761     return HWC2::Error::Unsupported;
762
763   /* TODO: Map to the DRM Connector property:
764    * https://elixir.bootlin.com/linux/v5.4-rc5/source/drivers/gpu/drm/drm_connector.c#L809
765    */
766
767   return HWC2::Error::None;
768 }
769 #endif
770
771 #if PLATFORM_SDK_VERSION > 28
772 HWC2::Error HwcDisplay::GetDisplayIdentificationData(uint8_t *outPort,
773                                                      uint32_t *outDataSize,
774                                                      uint8_t *outData) {
775   auto blob = connector_->GetEdidBlob();
776
777   if (!blob) {
778     ALOGE("Failed to get edid property value.");
779     return HWC2::Error::Unsupported;
780   }
781
782   if (outData) {
783     *outDataSize = std::min(*outDataSize, blob->length);
784     memcpy(outData, blob->data, *outDataSize);
785   } else {
786     *outDataSize = blob->length;
787   }
788   *outPort = connector_->GetId();
789
790   return HWC2::Error::None;
791 }
792
793 HWC2::Error HwcDisplay::GetDisplayCapabilities(uint32_t *outNumCapabilities,
794                                                uint32_t * /*outCapabilities*/) {
795   if (outNumCapabilities == nullptr) {
796     return HWC2::Error::BadParameter;
797   }
798
799   *outNumCapabilities = 0;
800
801   return HWC2::Error::None;
802 }
803
804 HWC2::Error HwcDisplay::GetDisplayBrightnessSupport(bool *supported) {
805   *supported = false;
806   return HWC2::Error::None;
807 }
808
809 HWC2::Error HwcDisplay::SetDisplayBrightness(float /* brightness */) {
810   return HWC2::Error::Unsupported;
811 }
812
813 #endif /* PLATFORM_SDK_VERSION > 28 */
814
815 #if PLATFORM_SDK_VERSION > 27
816
817 HWC2::Error HwcDisplay::GetRenderIntents(
818     int32_t mode, uint32_t *outNumIntents,
819     int32_t * /*android_render_intent_v1_1_t*/ outIntents) {
820   if (mode != HAL_COLOR_MODE_NATIVE) {
821     return HWC2::Error::BadParameter;
822   }
823
824   if (outIntents == nullptr) {
825     *outNumIntents = 1;
826     return HWC2::Error::None;
827   }
828   *outNumIntents = 1;
829   outIntents[0] = HAL_RENDER_INTENT_COLORIMETRIC;
830   return HWC2::Error::None;
831 }
832
833 HWC2::Error HwcDisplay::SetColorModeWithIntent(int32_t mode, int32_t intent) {
834   if (intent < HAL_RENDER_INTENT_COLORIMETRIC ||
835       intent > HAL_RENDER_INTENT_TONE_MAP_ENHANCE)
836     return HWC2::Error::BadParameter;
837
838   if (mode < HAL_COLOR_MODE_NATIVE || mode > HAL_COLOR_MODE_BT2100_HLG)
839     return HWC2::Error::BadParameter;
840
841   if (mode != HAL_COLOR_MODE_NATIVE)
842     return HWC2::Error::Unsupported;
843
844   if (intent != HAL_RENDER_INTENT_COLORIMETRIC)
845     return HWC2::Error::Unsupported;
846
847   color_mode_ = mode;
848   return HWC2::Error::None;
849 }
850
851 #endif /* PLATFORM_SDK_VERSION > 27 */
852
853 const Backend *HwcDisplay::backend() const {
854   return backend_.get();
855 }
856
857 void HwcDisplay::set_backend(std::unique_ptr<Backend> backend) {
858   backend_ = std::move(backend);
859 }
860
861 }  // namespace android