• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/Backend.h"
24 #include "backend/BackendManager.h"
25 #include "bufferinfo/BufferInfoGetter.h"
26 #include "utils/log.h"
27 #include "utils/properties.h"
28 
29 namespace android {
30 
DumpDelta(HwcDisplay::Stats delta)31 std::string HwcDisplay::DumpDelta(HwcDisplay::Stats delta) {
32   if (delta.total_pixops_ == 0)
33     return "No stats yet";
34   auto ratio = 1.0 - double(delta.gpu_pixops_) / double(delta.total_pixops_);
35 
36   std::stringstream ss;
37   ss << " Total frames count: " << delta.total_frames_ << "\n"
38      << " Failed to test commit frames: " << delta.failed_kms_validate_ << "\n"
39      << " Failed to commit frames: " << delta.failed_kms_present_ << "\n"
40      << ((delta.failed_kms_present_ > 0)
41              ? " !!! Internal failure, FIX it please\n"
42              : "")
43      << " Flattened frames: " << delta.frames_flattened_ << "\n"
44      << " Pixel operations (free units)"
45      << " : [TOTAL: " << delta.total_pixops_ << " / GPU: " << delta.gpu_pixops_
46      << "]\n"
47      << " Composition efficiency: " << ratio;
48 
49   return ss.str();
50 }
51 
Dump()52 std::string HwcDisplay::Dump() {
53   auto connector_name = IsInHeadlessMode()
54                             ? std::string("NULL-DISPLAY")
55                             : GetPipe().connector->Get()->GetName();
56 
57   std::stringstream ss;
58   ss << "- Display on: " << connector_name << "\n"
59      << "Statistics since system boot:\n"
60      << DumpDelta(total_stats_) << "\n\n"
61      << "Statistics since last dumpsys request:\n"
62      << DumpDelta(total_stats_.minus(prev_stats_)) << "\n\n";
63 
64   memcpy(&prev_stats_, &total_stats_, sizeof(Stats));
65   return ss.str();
66 }
67 
HwcDisplay(hwc2_display_t handle,HWC2::DisplayType type,DrmHwcTwo * hwc2)68 HwcDisplay::HwcDisplay(hwc2_display_t handle, HWC2::DisplayType type,
69                        DrmHwcTwo *hwc2)
70     : hwc2_(hwc2), handle_(handle), type_(type), client_layer_(this) {
71   if (type_ == HWC2::DisplayType::Virtual) {
72     writeback_layer_ = std::make_unique<HwcLayer>(this);
73   }
74 }
75 
SetColorMarixToIdentity()76 void HwcDisplay::SetColorMarixToIdentity() {
77   color_matrix_ = std::make_shared<drm_color_ctm>();
78   for (int i = 0; i < kCtmCols; i++) {
79     for (int j = 0; j < kCtmRows; j++) {
80       constexpr uint64_t kOne = (1ULL << 32); /* 1.0 in s31.32 format */
81       color_matrix_->matrix[i * kCtmRows + j] = (i == j) ? kOne : 0;
82     }
83   }
84 
85   color_transform_hint_ = HAL_COLOR_TRANSFORM_IDENTITY;
86 }
87 
88 HwcDisplay::~HwcDisplay() = default;
89 
SetPipeline(std::shared_ptr<DrmDisplayPipeline> pipeline)90 void HwcDisplay::SetPipeline(std::shared_ptr<DrmDisplayPipeline> pipeline) {
91   Deinit();
92 
93   pipeline_ = std::move(pipeline);
94 
95   if (pipeline_ != nullptr || handle_ == kPrimaryDisplay) {
96     Init();
97     hwc2_->ScheduleHotplugEvent(handle_, /*connected = */ true);
98   } else {
99     hwc2_->ScheduleHotplugEvent(handle_, /*connected = */ false);
100   }
101 }
102 
Deinit()103 void HwcDisplay::Deinit() {
104   if (pipeline_ != nullptr) {
105     AtomicCommitArgs a_args{};
106     a_args.composition = std::make_shared<DrmKmsPlan>();
107     GetPipe().atomic_state_manager->ExecuteAtomicCommit(a_args);
108 /*
109  *  TODO:
110  *  Unfortunately the following causes regressions on db845c
111  *  with VtsHalGraphicsComposerV2_3TargetTest due to the display
112  *  never coming back. Patches to avoiding that issue on the
113  *  the kernel side unfortunately causes further crashes in
114  *  drm_hwcomposer, because the client detach takes longer then the
115  *  1 second max VTS expects. So for now as a workaround, lets skip
116  *  deactivating the display on deinit, which matches previous
117  *  behavior prior to commit d0494d9b8097
118  */
119 #if 0
120     a_args.composition = {};
121     a_args.active = false;
122     GetPipe().atomic_state_manager->ExecuteAtomicCommit(a_args);
123 #endif
124 
125     current_plan_.reset();
126     backend_.reset();
127     if (flatcon_) {
128       flatcon_->StopThread();
129       flatcon_.reset();
130     }
131   }
132 
133   if (vsync_worker_) {
134     vsync_worker_->StopThread();
135     vsync_worker_ = {};
136   }
137 
138   SetClientTarget(nullptr, -1, 0, {});
139 }
140 
Init()141 HWC2::Error HwcDisplay::Init() {
142   ChosePreferredConfig();
143 
144   auto vsw_callbacks = (VSyncWorkerCallbacks){
145       .out_event =
146           [this](int64_t timestamp) {
147             const std::unique_lock lock(hwc2_->GetResMan().GetMainLock());
148             if (vsync_event_en_) {
149               uint32_t period_ns{};
150               GetDisplayVsyncPeriod(&period_ns);
151               hwc2_->SendVsyncEventToClient(handle_, timestamp, period_ns);
152             }
153             if (vsync_tracking_en_) {
154               last_vsync_ts_ = timestamp;
155             }
156             if (!vsync_event_en_ && !vsync_tracking_en_) {
157               vsync_worker_->VSyncControl(false);
158             }
159           },
160       .get_vperiod_ns = [this]() -> uint32_t {
161         uint32_t outVsyncPeriod = 0;
162         GetDisplayVsyncPeriod(&outVsyncPeriod);
163         return outVsyncPeriod;
164       },
165   };
166 
167   if (type_ != HWC2::DisplayType::Virtual) {
168     vsync_worker_ = VSyncWorker::CreateInstance(pipeline_, vsw_callbacks);
169     if (!vsync_worker_) {
170       ALOGE("Failed to create event worker for d=%d\n", int(handle_));
171       return HWC2::Error::BadDisplay;
172     }
173   }
174 
175   if (!IsInHeadlessMode()) {
176     auto ret = BackendManager::GetInstance().SetBackendForDisplay(this);
177     if (ret) {
178       ALOGE("Failed to set backend for d=%d %d\n", int(handle_), ret);
179       return HWC2::Error::BadDisplay;
180     }
181     auto flatcbk = (struct FlatConCallbacks){.trigger = [this]() {
182       if (hwc2_->refresh_callback_.first != nullptr &&
183           hwc2_->refresh_callback_.second != nullptr)
184         hwc2_->refresh_callback_.first(hwc2_->refresh_callback_.second,
185                                        handle_);
186     }};
187     flatcon_ = FlatteningController::CreateInstance(flatcbk);
188   }
189 
190   client_layer_.SetLayerBlendMode(HWC2_BLEND_MODE_PREMULTIPLIED);
191 
192   SetColorMarixToIdentity();
193 
194   return HWC2::Error::None;
195 }
196 
ChosePreferredConfig()197 HWC2::Error HwcDisplay::ChosePreferredConfig() {
198   HWC2::Error err{};
199   if (type_ == HWC2::DisplayType::Virtual) {
200     configs_.GenFakeMode(virtual_disp_width_, virtual_disp_height_);
201   } else if (!IsInHeadlessMode()) {
202     err = configs_.Update(*pipeline_->connector->Get());
203   } else {
204     configs_.GenFakeMode(0, 0);
205   }
206   if (!IsInHeadlessMode() && err != HWC2::Error::None) {
207     return HWC2::Error::BadDisplay;
208   }
209 
210   return SetActiveConfig(configs_.preferred_config_id);
211 }
212 
AcceptDisplayChanges()213 HWC2::Error HwcDisplay::AcceptDisplayChanges() {
214   for (std::pair<const hwc2_layer_t, HwcLayer> &l : layers_)
215     l.second.AcceptTypeChange();
216   return HWC2::Error::None;
217 }
218 
CreateLayer(hwc2_layer_t * layer)219 HWC2::Error HwcDisplay::CreateLayer(hwc2_layer_t *layer) {
220   layers_.emplace(static_cast<hwc2_layer_t>(layer_idx_), HwcLayer(this));
221   *layer = static_cast<hwc2_layer_t>(layer_idx_);
222   ++layer_idx_;
223   return HWC2::Error::None;
224 }
225 
DestroyLayer(hwc2_layer_t layer)226 HWC2::Error HwcDisplay::DestroyLayer(hwc2_layer_t layer) {
227   if (!get_layer(layer)) {
228     return HWC2::Error::BadLayer;
229   }
230 
231   layers_.erase(layer);
232   return HWC2::Error::None;
233 }
234 
GetActiveConfig(hwc2_config_t * config) const235 HWC2::Error HwcDisplay::GetActiveConfig(hwc2_config_t *config) const {
236   if (configs_.hwc_configs.count(staged_mode_config_id_) == 0)
237     return HWC2::Error::BadConfig;
238 
239   *config = staged_mode_config_id_;
240   return HWC2::Error::None;
241 }
242 
GetChangedCompositionTypes(uint32_t * num_elements,hwc2_layer_t * layers,int32_t * types)243 HWC2::Error HwcDisplay::GetChangedCompositionTypes(uint32_t *num_elements,
244                                                    hwc2_layer_t *layers,
245                                                    int32_t *types) {
246   if (IsInHeadlessMode()) {
247     *num_elements = 0;
248     return HWC2::Error::None;
249   }
250 
251   uint32_t num_changes = 0;
252   for (auto &l : layers_) {
253     if (l.second.IsTypeChanged()) {
254       if (layers && num_changes < *num_elements)
255         layers[num_changes] = l.first;
256       if (types && num_changes < *num_elements)
257         types[num_changes] = static_cast<int32_t>(l.second.GetValidatedType());
258       ++num_changes;
259     }
260   }
261   if (!layers && !types)
262     *num_elements = num_changes;
263   return HWC2::Error::None;
264 }
265 
GetClientTargetSupport(uint32_t width,uint32_t height,int32_t,int32_t dataspace)266 HWC2::Error HwcDisplay::GetClientTargetSupport(uint32_t width, uint32_t height,
267                                                int32_t /*format*/,
268                                                int32_t dataspace) {
269   if (IsInHeadlessMode()) {
270     return HWC2::Error::None;
271   }
272 
273   auto min = pipeline_->device->GetMinResolution();
274   auto max = pipeline_->device->GetMaxResolution();
275 
276   if (width < min.first || height < min.second)
277     return HWC2::Error::Unsupported;
278 
279   if (width > max.first || height > max.second)
280     return HWC2::Error::Unsupported;
281 
282   if (dataspace != HAL_DATASPACE_UNKNOWN)
283     return HWC2::Error::Unsupported;
284 
285   // TODO(nobody): Validate format can be handled by either GL or planes
286   return HWC2::Error::None;
287 }
288 
GetColorModes(uint32_t * num_modes,int32_t * modes)289 HWC2::Error HwcDisplay::GetColorModes(uint32_t *num_modes, int32_t *modes) {
290   if (!modes)
291     *num_modes = 1;
292 
293   if (modes)
294     *modes = HAL_COLOR_MODE_NATIVE;
295 
296   return HWC2::Error::None;
297 }
298 
GetDisplayAttribute(hwc2_config_t config,int32_t attribute_in,int32_t * value)299 HWC2::Error HwcDisplay::GetDisplayAttribute(hwc2_config_t config,
300                                             int32_t attribute_in,
301                                             int32_t *value) {
302   int conf = static_cast<int>(config);
303 
304   if (configs_.hwc_configs.count(conf) == 0) {
305     ALOGE("Could not find mode #%d", conf);
306     return HWC2::Error::BadConfig;
307   }
308 
309   auto &hwc_config = configs_.hwc_configs[conf];
310 
311   static const int32_t kUmPerInch = 25400;
312   auto mm_width = configs_.mm_width;
313   auto mm_height = configs_.mm_height;
314   auto attribute = static_cast<HWC2::Attribute>(attribute_in);
315   switch (attribute) {
316     case HWC2::Attribute::Width:
317       *value = static_cast<int>(hwc_config.mode.GetRawMode().hdisplay);
318       break;
319     case HWC2::Attribute::Height:
320       *value = static_cast<int>(hwc_config.mode.GetRawMode().vdisplay);
321       break;
322     case HWC2::Attribute::VsyncPeriod:
323       // in nanoseconds
324       *value = static_cast<int>(1E9 / hwc_config.mode.GetVRefresh());
325       break;
326     case HWC2::Attribute::DpiX:
327       // Dots per 1000 inches
328       *value = mm_width ? int(hwc_config.mode.GetRawMode().hdisplay *
329                               kUmPerInch / mm_width)
330                         : -1;
331       break;
332     case HWC2::Attribute::DpiY:
333       // Dots per 1000 inches
334       *value = mm_height ? int(hwc_config.mode.GetRawMode().vdisplay *
335                                kUmPerInch / mm_height)
336                          : -1;
337       break;
338 #if __ANDROID_API__ > 29
339     case HWC2::Attribute::ConfigGroup:
340       /* Dispite ConfigGroup is a part of HWC2.4 API, framework
341        * able to request it even if service @2.1 is used */
342       *value = int(hwc_config.group_id);
343       break;
344 #endif
345     default:
346       *value = -1;
347       return HWC2::Error::BadConfig;
348   }
349   return HWC2::Error::None;
350 }
351 
GetDisplayConfigs(uint32_t * num_configs,hwc2_config_t * configs)352 HWC2::Error HwcDisplay::GetDisplayConfigs(uint32_t *num_configs,
353                                           hwc2_config_t *configs) {
354   uint32_t idx = 0;
355   for (auto &hwc_config : configs_.hwc_configs) {
356     if (hwc_config.second.disabled) {
357       continue;
358     }
359 
360     if (configs != nullptr) {
361       if (idx >= *num_configs) {
362         break;
363       }
364       configs[idx] = hwc_config.second.id;
365     }
366 
367     idx++;
368   }
369   *num_configs = idx;
370   return HWC2::Error::None;
371 }
372 
GetDisplayName(uint32_t * size,char * name)373 HWC2::Error HwcDisplay::GetDisplayName(uint32_t *size, char *name) {
374   std::ostringstream stream;
375   if (IsInHeadlessMode()) {
376     stream << "null-display";
377   } else {
378     stream << "display-" << GetPipe().connector->Get()->GetId();
379   }
380   auto string = stream.str();
381   auto length = string.length();
382   if (!name) {
383     *size = length;
384     return HWC2::Error::None;
385   }
386 
387   *size = std::min<uint32_t>(static_cast<uint32_t>(length - 1), *size);
388   strncpy(name, string.c_str(), *size);
389   return HWC2::Error::None;
390 }
391 
GetDisplayRequests(int32_t *,uint32_t * num_elements,hwc2_layer_t *,int32_t *)392 HWC2::Error HwcDisplay::GetDisplayRequests(int32_t * /*display_requests*/,
393                                            uint32_t *num_elements,
394                                            hwc2_layer_t * /*layers*/,
395                                            int32_t * /*layer_requests*/) {
396   // TODO(nobody): I think virtual display should request
397   //      HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT here
398   *num_elements = 0;
399   return HWC2::Error::None;
400 }
401 
GetDisplayType(int32_t * type)402 HWC2::Error HwcDisplay::GetDisplayType(int32_t *type) {
403   *type = static_cast<int32_t>(type_);
404   return HWC2::Error::None;
405 }
406 
GetDozeSupport(int32_t * support)407 HWC2::Error HwcDisplay::GetDozeSupport(int32_t *support) {
408   *support = 0;
409   return HWC2::Error::None;
410 }
411 
GetHdrCapabilities(uint32_t * num_types,int32_t *,float *,float *,float *)412 HWC2::Error HwcDisplay::GetHdrCapabilities(uint32_t *num_types,
413                                            int32_t * /*types*/,
414                                            float * /*max_luminance*/,
415                                            float * /*max_average_luminance*/,
416                                            float * /*min_luminance*/) {
417   *num_types = 0;
418   return HWC2::Error::None;
419 }
420 
421 /* Find API details at:
422  * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r3:hardware/libhardware/include/hardware/hwcomposer2.h;l=1767
423  *
424  * Called after PresentDisplay(), CLIENT is expecting release fence for the
425  * prior buffer (not the one assigned to the layer at the moment).
426  */
GetReleaseFences(uint32_t * num_elements,hwc2_layer_t * layers,int32_t * fences)427 HWC2::Error HwcDisplay::GetReleaseFences(uint32_t *num_elements,
428                                          hwc2_layer_t *layers,
429                                          int32_t *fences) {
430   if (IsInHeadlessMode()) {
431     *num_elements = 0;
432     return HWC2::Error::None;
433   }
434 
435   uint32_t num_layers = 0;
436 
437   for (auto &l : layers_) {
438     if (!l.second.GetPriorBufferScanOutFlag() || !present_fence_) {
439       continue;
440     }
441 
442     ++num_layers;
443 
444     if (layers == nullptr || fences == nullptr)
445       continue;
446 
447     if (num_layers > *num_elements) {
448       ALOGW("Overflow num_elements %d/%d", num_layers, *num_elements);
449       return HWC2::Error::None;
450     }
451 
452     layers[num_layers - 1] = l.first;
453     fences[num_layers - 1] = DupFd(present_fence_);
454   }
455   *num_elements = num_layers;
456 
457   return HWC2::Error::None;
458 }
459 
CreateComposition(AtomicCommitArgs & a_args)460 HWC2::Error HwcDisplay::CreateComposition(AtomicCommitArgs &a_args) {
461   if (IsInHeadlessMode()) {
462     ALOGE("%s: Display is in headless mode, should never reach here", __func__);
463     return HWC2::Error::None;
464   }
465 
466   a_args.color_matrix = color_matrix_;
467 
468   uint32_t prev_vperiod_ns = 0;
469   GetDisplayVsyncPeriod(&prev_vperiod_ns);
470 
471   auto mode_update_commited_ = false;
472   if (staged_mode_ &&
473       staged_mode_change_time_ <= ResourceManager::GetTimeMonotonicNs()) {
474     client_layer_.SetLayerDisplayFrame(
475         (hwc_rect_t){.left = 0,
476                      .top = 0,
477                      .right = int(staged_mode_->GetRawMode().hdisplay),
478                      .bottom = int(staged_mode_->GetRawMode().vdisplay)});
479 
480     configs_.active_config_id = staged_mode_config_id_;
481 
482     a_args.display_mode = *staged_mode_;
483     if (!a_args.test_only) {
484       mode_update_commited_ = true;
485     }
486   }
487 
488   // order the layers by z-order
489   bool use_client_layer = false;
490   uint32_t client_z_order = UINT32_MAX;
491   std::map<uint32_t, HwcLayer *> z_map;
492   for (std::pair<const hwc2_layer_t, HwcLayer> &l : layers_) {
493     switch (l.second.GetValidatedType()) {
494       case HWC2::Composition::Device:
495         z_map.emplace(l.second.GetZOrder(), &l.second);
496         break;
497       case HWC2::Composition::Client:
498         // Place it at the z_order of the lowest client layer
499         use_client_layer = true;
500         client_z_order = std::min(client_z_order, l.second.GetZOrder());
501         break;
502       default:
503         continue;
504     }
505   }
506   if (use_client_layer)
507     z_map.emplace(client_z_order, &client_layer_);
508 
509   if (z_map.empty())
510     return HWC2::Error::BadLayer;
511 
512   std::vector<LayerData> composition_layers;
513 
514   /* Import & populate */
515   for (std::pair<const uint32_t, HwcLayer *> &l : z_map) {
516     l.second->PopulateLayerData();
517   }
518 
519   // now that they're ordered by z, add them to the composition
520   for (std::pair<const uint32_t, HwcLayer *> &l : z_map) {
521     if (!l.second->IsLayerUsableAsDevice()) {
522       /* This will be normally triggered on validation of the first frame
523        * containing CLIENT layer. At this moment client buffer is not yet
524        * provided by the CLIENT.
525        * This may be triggered once in HwcLayer lifecycle in case FB can't be
526        * imported. For example when non-contiguous buffer is imported into
527        * contiguous-only DRM/KMS driver.
528        */
529       return HWC2::Error::BadLayer;
530     }
531     composition_layers.emplace_back(l.second->GetLayerData());
532   }
533 
534   /* Store plan to ensure shared planes won't be stolen by other display
535    * in between of ValidateDisplay() and PresentDisplay() calls
536    */
537   current_plan_ = DrmKmsPlan::CreateDrmKmsPlan(GetPipe(),
538                                                std::move(composition_layers));
539 
540   if (type_ == HWC2::DisplayType::Virtual) {
541     a_args.writeback_fb = writeback_layer_->GetLayerData().fb;
542     a_args.writeback_release_fence = writeback_layer_->GetLayerData()
543                                          .acquire_fence;
544   }
545 
546   if (!current_plan_) {
547     if (!a_args.test_only) {
548       ALOGE("Failed to create DrmKmsPlan");
549     }
550     return HWC2::Error::BadConfig;
551   }
552 
553   a_args.composition = current_plan_;
554 
555   auto ret = GetPipe().atomic_state_manager->ExecuteAtomicCommit(a_args);
556 
557   if (ret) {
558     if (!a_args.test_only)
559       ALOGE("Failed to apply the frame composition ret=%d", ret);
560     return HWC2::Error::BadParameter;
561   }
562 
563   if (mode_update_commited_) {
564     staged_mode_.reset();
565     vsync_tracking_en_ = false;
566     if (last_vsync_ts_ != 0) {
567       hwc2_->SendVsyncPeriodTimingChangedEventToClient(handle_,
568                                                        last_vsync_ts_ +
569                                                            prev_vperiod_ns);
570     }
571   }
572 
573   return HWC2::Error::None;
574 }
575 
576 /* Find API details at:
577  * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r3:hardware/libhardware/include/hardware/hwcomposer2.h;l=1805
578  */
PresentDisplay(int32_t * out_present_fence)579 HWC2::Error HwcDisplay::PresentDisplay(int32_t *out_present_fence) {
580   if (IsInHeadlessMode()) {
581     *out_present_fence = -1;
582     return HWC2::Error::None;
583   }
584   HWC2::Error ret{};
585 
586   ++total_stats_.total_frames_;
587 
588   AtomicCommitArgs a_args{};
589   ret = CreateComposition(a_args);
590 
591   if (ret != HWC2::Error::None)
592     ++total_stats_.failed_kms_present_;
593 
594   if (ret == HWC2::Error::BadLayer) {
595     // Can we really have no client or device layers?
596     *out_present_fence = -1;
597     return HWC2::Error::None;
598   }
599   if (ret != HWC2::Error::None)
600     return ret;
601 
602   this->present_fence_ = a_args.out_fence;
603   *out_present_fence = DupFd(a_args.out_fence);
604 
605   // Reset the color matrix so we don't apply it over and over again.
606   color_matrix_ = {};
607 
608   ++frame_no_;
609   return HWC2::Error::None;
610 }
611 
SetActiveConfigInternal(uint32_t config,int64_t change_time)612 HWC2::Error HwcDisplay::SetActiveConfigInternal(uint32_t config,
613                                                 int64_t change_time) {
614   if (configs_.hwc_configs.count(config) == 0) {
615     ALOGE("Could not find active mode for %u", config);
616     return HWC2::Error::BadConfig;
617   }
618 
619   staged_mode_ = configs_.hwc_configs[config].mode;
620   staged_mode_change_time_ = change_time;
621   staged_mode_config_id_ = config;
622 
623   return HWC2::Error::None;
624 }
625 
SetActiveConfig(hwc2_config_t config)626 HWC2::Error HwcDisplay::SetActiveConfig(hwc2_config_t config) {
627   return SetActiveConfigInternal(config, ResourceManager::GetTimeMonotonicNs());
628 }
629 
630 /* Find API details at:
631  * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r3:hardware/libhardware/include/hardware/hwcomposer2.h;l=1861
632  */
SetClientTarget(buffer_handle_t target,int32_t acquire_fence,int32_t dataspace,hwc_region_t)633 HWC2::Error HwcDisplay::SetClientTarget(buffer_handle_t target,
634                                         int32_t acquire_fence,
635                                         int32_t dataspace,
636                                         hwc_region_t /*damage*/) {
637   client_layer_.SetLayerBuffer(target, acquire_fence);
638   client_layer_.SetLayerDataspace(dataspace);
639 
640   /*
641    * target can be nullptr, this does mean the Composer Service is calling
642    * cleanDisplayResources() on after receiving HOTPLUG event. See more at:
643    * 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
644    */
645   if (target == nullptr) {
646     client_layer_.SwChainClearCache();
647     return HWC2::Error::None;
648   }
649 
650   if (IsInHeadlessMode()) {
651     return HWC2::Error::None;
652   }
653 
654   client_layer_.PopulateLayerData();
655   if (!client_layer_.IsLayerUsableAsDevice()) {
656     ALOGE("Client layer must be always usable by DRM/KMS");
657     return HWC2::Error::BadLayer;
658   }
659 
660   auto &bi = client_layer_.GetLayerData().bi;
661   if (!bi) {
662     ALOGE("%s: Invalid state", __func__);
663     return HWC2::Error::BadLayer;
664   }
665 
666   auto source_crop = (hwc_frect_t){.left = 0.0F,
667                                    .top = 0.0F,
668                                    .right = static_cast<float>(bi->width),
669                                    .bottom = static_cast<float>(bi->height)};
670   client_layer_.SetLayerSourceCrop(source_crop);
671 
672   return HWC2::Error::None;
673 }
674 
SetColorMode(int32_t mode)675 HWC2::Error HwcDisplay::SetColorMode(int32_t mode) {
676   if (mode < HAL_COLOR_MODE_NATIVE || mode > HAL_COLOR_MODE_BT2100_HLG)
677     return HWC2::Error::BadParameter;
678 
679   if (mode != HAL_COLOR_MODE_NATIVE)
680     return HWC2::Error::Unsupported;
681 
682   color_mode_ = mode;
683   return HWC2::Error::None;
684 }
685 
686 #include <xf86drmMode.h>
687 
SetColorTransform(const float * matrix,int32_t hint)688 HWC2::Error HwcDisplay::SetColorTransform(const float *matrix, int32_t hint) {
689   if (hint < HAL_COLOR_TRANSFORM_IDENTITY ||
690       hint > HAL_COLOR_TRANSFORM_CORRECT_TRITANOPIA)
691     return HWC2::Error::BadParameter;
692 
693   if (!matrix && hint == HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX)
694     return HWC2::Error::BadParameter;
695 
696   color_transform_hint_ = static_cast<android_color_transform_t>(hint);
697 
698   if (IsInHeadlessMode())
699     return HWC2::Error::None;
700 
701   if (!GetPipe().crtc->Get()->GetCtmProperty())
702     return HWC2::Error::None;
703 
704   switch (color_transform_hint_) {
705     case HAL_COLOR_TRANSFORM_IDENTITY:
706       SetColorMarixToIdentity();
707       break;
708     case HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX:
709       color_matrix_ = std::make_shared<drm_color_ctm>();
710       /* DRM expects a 3x3 matrix, but the HAL provides a 4x4 matrix. */
711       for (int i = 0; i < kCtmCols; i++) {
712         for (int j = 0; j < kCtmRows; j++) {
713           constexpr int kInCtmRows = 4;
714           /* HAL matrix type is float, but DRM expects a s31.32 fix point */
715           auto value = uint64_t(matrix[i * kInCtmRows + j] * float(1ULL << 32));
716           color_matrix_->matrix[i * kCtmRows + j] = value;
717         }
718       }
719       break;
720     default:
721       return HWC2::Error::Unsupported;
722   }
723 
724   return HWC2::Error::None;
725 }
726 
CtmByGpu()727 bool HwcDisplay::CtmByGpu() {
728   if (color_transform_hint_ == HAL_COLOR_TRANSFORM_IDENTITY)
729     return false;
730 
731   if (GetPipe().crtc->Get()->GetCtmProperty())
732     return false;
733 
734   if (GetHwc2()->GetResMan().GetCtmHandling() == CtmHandling::kDrmOrIgnore)
735     return false;
736 
737   return true;
738 }
739 
SetOutputBuffer(buffer_handle_t buffer,int32_t release_fence)740 HWC2::Error HwcDisplay::SetOutputBuffer(buffer_handle_t buffer,
741                                         int32_t release_fence) {
742   writeback_layer_->SetLayerBuffer(buffer, release_fence);
743   writeback_layer_->PopulateLayerData();
744   if (!writeback_layer_->IsLayerUsableAsDevice()) {
745     ALOGE("Output layer must be always usable by DRM/KMS");
746     return HWC2::Error::BadLayer;
747   }
748   /* TODO: Check if format is supported by writeback connector */
749   return HWC2::Error::None;
750 }
751 
SetPowerMode(int32_t mode_in)752 HWC2::Error HwcDisplay::SetPowerMode(int32_t mode_in) {
753   auto mode = static_cast<HWC2::PowerMode>(mode_in);
754 
755   AtomicCommitArgs a_args{};
756 
757   switch (mode) {
758     case HWC2::PowerMode::Off:
759       a_args.active = false;
760       break;
761     case HWC2::PowerMode::On:
762       a_args.active = true;
763       break;
764     case HWC2::PowerMode::Doze:
765     case HWC2::PowerMode::DozeSuspend:
766       return HWC2::Error::Unsupported;
767     default:
768       ALOGE("Incorrect power mode value (%d)\n", mode_in);
769       return HWC2::Error::BadParameter;
770   }
771 
772   if (IsInHeadlessMode()) {
773     return HWC2::Error::None;
774   }
775 
776   if (a_args.active && *a_args.active) {
777     /*
778      * Setting the display to active before we have a composition
779      * can break some drivers, so skip setting a_args.active to
780      * true, as the next composition frame will implicitly activate
781      * the display
782      */
783     return GetPipe().atomic_state_manager->ActivateDisplayUsingDPMS() == 0
784                ? HWC2::Error::None
785                : HWC2::Error::BadParameter;
786   };
787 
788   auto err = GetPipe().atomic_state_manager->ExecuteAtomicCommit(a_args);
789   if (err) {
790     ALOGE("Failed to apply the dpms composition err=%d", err);
791     return HWC2::Error::BadParameter;
792   }
793   return HWC2::Error::None;
794 }
795 
SetVsyncEnabled(int32_t enabled)796 HWC2::Error HwcDisplay::SetVsyncEnabled(int32_t enabled) {
797   if (type_ == HWC2::DisplayType::Virtual) {
798     return HWC2::Error::None;
799   }
800 
801   vsync_event_en_ = HWC2_VSYNC_ENABLE == enabled;
802   if (vsync_event_en_) {
803     vsync_worker_->VSyncControl(true);
804   }
805   return HWC2::Error::None;
806 }
807 
ValidateDisplay(uint32_t * num_types,uint32_t * num_requests)808 HWC2::Error HwcDisplay::ValidateDisplay(uint32_t *num_types,
809                                         uint32_t *num_requests) {
810   if (IsInHeadlessMode()) {
811     *num_types = *num_requests = 0;
812     return HWC2::Error::None;
813   }
814 
815   /* In current drm_hwc design in case previous frame layer was not validated as
816    * a CLIENT, it is used by display controller (Front buffer). We have to store
817    * this state to provide the CLIENT with the release fences for such buffers.
818    */
819   for (auto &l : layers_) {
820     l.second.SetPriorBufferScanOutFlag(l.second.GetValidatedType() !=
821                                        HWC2::Composition::Client);
822   }
823 
824   return backend_->ValidateDisplay(this, num_types, num_requests);
825 }
826 
GetOrderLayersByZPos()827 std::vector<HwcLayer *> HwcDisplay::GetOrderLayersByZPos() {
828   std::vector<HwcLayer *> ordered_layers;
829   ordered_layers.reserve(layers_.size());
830 
831   for (auto &[handle, layer] : layers_) {
832     ordered_layers.emplace_back(&layer);
833   }
834 
835   std::sort(std::begin(ordered_layers), std::end(ordered_layers),
836             [](const HwcLayer *lhs, const HwcLayer *rhs) {
837               return lhs->GetZOrder() < rhs->GetZOrder();
838             });
839 
840   return ordered_layers;
841 }
842 
GetDisplayVsyncPeriod(uint32_t * outVsyncPeriod)843 HWC2::Error HwcDisplay::GetDisplayVsyncPeriod(
844     uint32_t *outVsyncPeriod /* ns */) {
845   return GetDisplayAttribute(configs_.active_config_id,
846                              HWC2_ATTRIBUTE_VSYNC_PERIOD,
847                              (int32_t *)(outVsyncPeriod));
848 }
849 
850 #if __ANDROID_API__ > 29
GetDisplayConnectionType(uint32_t * outType)851 HWC2::Error HwcDisplay::GetDisplayConnectionType(uint32_t *outType) {
852   if (IsInHeadlessMode()) {
853     *outType = static_cast<uint32_t>(HWC2::DisplayConnectionType::Internal);
854     return HWC2::Error::None;
855   }
856   /* Primary display should be always internal,
857    * otherwise SF will be unhappy and will crash
858    */
859   if (GetPipe().connector->Get()->IsInternal() || handle_ == kPrimaryDisplay)
860     *outType = static_cast<uint32_t>(HWC2::DisplayConnectionType::Internal);
861   else if (GetPipe().connector->Get()->IsExternal())
862     *outType = static_cast<uint32_t>(HWC2::DisplayConnectionType::External);
863   else
864     return HWC2::Error::BadConfig;
865 
866   return HWC2::Error::None;
867 }
868 
SetActiveConfigWithConstraints(hwc2_config_t config,hwc_vsync_period_change_constraints_t * vsyncPeriodChangeConstraints,hwc_vsync_period_change_timeline_t * outTimeline)869 HWC2::Error HwcDisplay::SetActiveConfigWithConstraints(
870     hwc2_config_t config,
871     hwc_vsync_period_change_constraints_t *vsyncPeriodChangeConstraints,
872     hwc_vsync_period_change_timeline_t *outTimeline) {
873   if (type_ == HWC2::DisplayType::Virtual) {
874     return HWC2::Error::None;
875   }
876 
877   if (vsyncPeriodChangeConstraints == nullptr || outTimeline == nullptr) {
878     return HWC2::Error::BadParameter;
879   }
880 
881   uint32_t current_vsync_period{};
882   GetDisplayVsyncPeriod(&current_vsync_period);
883 
884   if (vsyncPeriodChangeConstraints->seamlessRequired) {
885     return HWC2::Error::SeamlessNotAllowed;
886   }
887 
888   outTimeline->refreshTimeNanos = vsyncPeriodChangeConstraints
889                                       ->desiredTimeNanos -
890                                   current_vsync_period;
891   auto ret = SetActiveConfigInternal(config, outTimeline->refreshTimeNanos);
892   if (ret != HWC2::Error::None) {
893     return ret;
894   }
895 
896   outTimeline->refreshRequired = true;
897   outTimeline->newVsyncAppliedTimeNanos = vsyncPeriodChangeConstraints
898                                               ->desiredTimeNanos;
899 
900   last_vsync_ts_ = 0;
901   vsync_tracking_en_ = true;
902   vsync_worker_->VSyncControl(true);
903 
904   return HWC2::Error::None;
905 }
906 
SetAutoLowLatencyMode(bool)907 HWC2::Error HwcDisplay::SetAutoLowLatencyMode(bool /*on*/) {
908   return HWC2::Error::Unsupported;
909 }
910 
GetSupportedContentTypes(uint32_t * outNumSupportedContentTypes,const uint32_t * outSupportedContentTypes)911 HWC2::Error HwcDisplay::GetSupportedContentTypes(
912     uint32_t *outNumSupportedContentTypes,
913     const uint32_t *outSupportedContentTypes) {
914   if (outSupportedContentTypes == nullptr)
915     *outNumSupportedContentTypes = 0;
916 
917   return HWC2::Error::None;
918 }
919 
SetContentType(int32_t contentType)920 HWC2::Error HwcDisplay::SetContentType(int32_t contentType) {
921   if (contentType != HWC2_CONTENT_TYPE_NONE)
922     return HWC2::Error::Unsupported;
923 
924   /* TODO: Map to the DRM Connector property:
925    * https://elixir.bootlin.com/linux/v5.4-rc5/source/drivers/gpu/drm/drm_connector.c#L809
926    */
927 
928   return HWC2::Error::None;
929 }
930 #endif
931 
932 #if __ANDROID_API__ > 28
GetDisplayIdentificationData(uint8_t * outPort,uint32_t * outDataSize,uint8_t * outData)933 HWC2::Error HwcDisplay::GetDisplayIdentificationData(uint8_t *outPort,
934                                                      uint32_t *outDataSize,
935                                                      uint8_t *outData) {
936   if (IsInHeadlessMode()) {
937     return HWC2::Error::Unsupported;
938   }
939 
940   auto blob = GetPipe().connector->Get()->GetEdidBlob();
941   if (!blob) {
942     return HWC2::Error::Unsupported;
943   }
944 
945   *outPort = handle_; /* TDOD(nobody): What should be here? */
946 
947   if (outData) {
948     *outDataSize = std::min(*outDataSize, blob->length);
949     memcpy(outData, blob->data, *outDataSize);
950   } else {
951     *outDataSize = blob->length;
952   }
953 
954   return HWC2::Error::None;
955 }
956 
GetDisplayCapabilities(uint32_t * outNumCapabilities,uint32_t * outCapabilities)957 HWC2::Error HwcDisplay::GetDisplayCapabilities(uint32_t *outNumCapabilities,
958                                                uint32_t *outCapabilities) {
959   if (outNumCapabilities == nullptr) {
960     return HWC2::Error::BadParameter;
961   }
962 
963   bool skip_ctm = false;
964 
965   // Skip client CTM if user requested DRM_OR_IGNORE
966   if (GetHwc2()->GetResMan().GetCtmHandling() == CtmHandling::kDrmOrIgnore)
967     skip_ctm = true;
968 
969   // Skip client CTM if DRM can handle it
970   if (!skip_ctm && !IsInHeadlessMode() &&
971       GetPipe().crtc->Get()->GetCtmProperty())
972     skip_ctm = true;
973 
974   if (!skip_ctm) {
975     *outNumCapabilities = 0;
976     return HWC2::Error::None;
977   }
978 
979   *outNumCapabilities = 1;
980   if (outCapabilities) {
981     outCapabilities[0] = HWC2_DISPLAY_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM;
982   }
983 
984   return HWC2::Error::None;
985 }
986 
GetDisplayBrightnessSupport(bool * supported)987 HWC2::Error HwcDisplay::GetDisplayBrightnessSupport(bool *supported) {
988   *supported = false;
989   return HWC2::Error::None;
990 }
991 
SetDisplayBrightness(float)992 HWC2::Error HwcDisplay::SetDisplayBrightness(float /* brightness */) {
993   return HWC2::Error::Unsupported;
994 }
995 
996 #endif /* __ANDROID_API__ > 28 */
997 
998 #if __ANDROID_API__ > 27
999 
GetRenderIntents(int32_t mode,uint32_t * outNumIntents,int32_t * outIntents)1000 HWC2::Error HwcDisplay::GetRenderIntents(
1001     int32_t mode, uint32_t *outNumIntents,
1002     int32_t * /*android_render_intent_v1_1_t*/ outIntents) {
1003   if (mode != HAL_COLOR_MODE_NATIVE) {
1004     return HWC2::Error::BadParameter;
1005   }
1006 
1007   if (outIntents == nullptr) {
1008     *outNumIntents = 1;
1009     return HWC2::Error::None;
1010   }
1011   *outNumIntents = 1;
1012   outIntents[0] = HAL_RENDER_INTENT_COLORIMETRIC;
1013   return HWC2::Error::None;
1014 }
1015 
SetColorModeWithIntent(int32_t mode,int32_t intent)1016 HWC2::Error HwcDisplay::SetColorModeWithIntent(int32_t mode, int32_t intent) {
1017   if (intent < HAL_RENDER_INTENT_COLORIMETRIC ||
1018       intent > HAL_RENDER_INTENT_TONE_MAP_ENHANCE)
1019     return HWC2::Error::BadParameter;
1020 
1021   if (mode < HAL_COLOR_MODE_NATIVE || mode > HAL_COLOR_MODE_BT2100_HLG)
1022     return HWC2::Error::BadParameter;
1023 
1024   if (mode != HAL_COLOR_MODE_NATIVE)
1025     return HWC2::Error::Unsupported;
1026 
1027   if (intent != HAL_RENDER_INTENT_COLORIMETRIC)
1028     return HWC2::Error::Unsupported;
1029 
1030   color_mode_ = mode;
1031   return HWC2::Error::None;
1032 }
1033 
1034 #endif /* __ANDROID_API__ > 27 */
1035 
backend() const1036 const Backend *HwcDisplay::backend() const {
1037   return backend_.get();
1038 }
1039 
set_backend(std::unique_ptr<Backend> backend)1040 void HwcDisplay::set_backend(std::unique_ptr<Backend> backend) {
1041   backend_ = std::move(backend);
1042 }
1043 
1044 }  // namespace android
1045