xref: /aosp_15_r20/external/drm_hwcomposer/hwc2_device/HwcDisplay.cpp (revision 0a9764fe0a15e71ebbeb85e87e10990c23aab47f)
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 "drmhwc"
18 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
19 
20 #include "HwcDisplay.h"
21 
22 #include <cinttypes>
23 
24 #include <hardware/gralloc.h>
25 #include <ui/GraphicBufferAllocator.h>
26 #include <ui/GraphicBufferMapper.h>
27 #include <ui/PixelFormat.h>
28 
29 #include "backend/Backend.h"
30 #include "backend/BackendManager.h"
31 #include "bufferinfo/BufferInfoGetter.h"
32 #include "compositor/DisplayInfo.h"
33 #include "drm/DrmConnector.h"
34 #include "drm/DrmDisplayPipeline.h"
35 #include "drm/DrmHwc.h"
36 #include "utils/log.h"
37 #include "utils/properties.h"
38 
39 using ::android::DrmDisplayPipeline;
40 
41 namespace android {
42 
43 namespace {
44 // Allocate a black buffer that can be used for an initial modeset when there.
45 // is no appropriate client buffer available to be used.
46 // Caller must free the returned buffer with GraphicBufferAllocator::free.
GetModesetBuffer(uint32_t width,uint32_t height)47 auto GetModesetBuffer(uint32_t width, uint32_t height) -> buffer_handle_t {
48   constexpr PixelFormat format = PIXEL_FORMAT_RGBA_8888;
49   constexpr uint64_t usage = GRALLOC_USAGE_SW_READ_OFTEN |
50                              GRALLOC_USAGE_SW_WRITE_OFTEN |
51                              GRALLOC_USAGE_HW_COMPOSER | GRALLOC_USAGE_HW_FB;
52 
53   constexpr uint32_t layer_count = 1;
54   const std::string name = "drm-hwcomposer";
55 
56   buffer_handle_t handle = nullptr;
57   uint32_t stride = 0;
58   status_t status = GraphicBufferAllocator::get().allocate(width, height,
59                                                            format, layer_count,
60                                                            usage, &handle,
61                                                            &stride, name);
62   if (status != OK) {
63     ALOGE("Failed to allocate modeset buffer.");
64     return nullptr;
65   }
66 
67   void *data = nullptr;
68   Rect bounds = {0, 0, static_cast<int32_t>(width),
69                  static_cast<int32_t>(height)};
70   status = GraphicBufferMapper::get().lock(handle, usage, bounds, &data);
71   if (status != OK) {
72     ALOGE("Failed to map modeset buffer.");
73     GraphicBufferAllocator::get().free(handle);
74     return nullptr;
75   }
76 
77   // Cast one of the multiplicands to ensure that the multiplication happens
78   // in a wider type (size_t).
79   const size_t buffer_size = static_cast<size_t>(height) * stride *
80                              bytesPerPixel(format);
81   memset(data, 0, buffer_size);
82   status = GraphicBufferMapper::get().unlock(handle);
83   ALOGW_IF(status != OK, "Failed to unmap buffer.");
84   return handle;
85 }
86 
GetModesetLayerProperties(buffer_handle_t buffer,uint32_t width,uint32_t height)87 auto GetModesetLayerProperties(buffer_handle_t buffer, uint32_t width,
88                                uint32_t height) -> HwcLayer::LayerProperties {
89   HwcLayer::LayerProperties properties;
90   properties.buffer = {.buffer_handle = buffer, .acquire_fence = {}};
91   properties.display_frame = {
92       .left = 0,
93       .top = 0,
94       .right = int(width),
95       .bottom = int(height),
96   };
97   properties.source_crop = (hwc_frect_t){
98       .left = 0.0F,
99       .top = 0.0F,
100       .right = static_cast<float>(width),
101       .bottom = static_cast<float>(height),
102   };
103   properties.blend_mode = BufferBlendMode::kNone;
104   return properties;
105 }
106 }  // namespace
107 
DumpDelta(HwcDisplay::Stats delta)108 std::string HwcDisplay::DumpDelta(HwcDisplay::Stats delta) {
109   if (delta.total_pixops_ == 0)
110     return "No stats yet";
111   auto ratio = 1.0 - double(delta.gpu_pixops_) / double(delta.total_pixops_);
112 
113   std::stringstream ss;
114   ss << " Total frames count: " << delta.total_frames_ << "\n"
115      << " Failed to test commit frames: " << delta.failed_kms_validate_ << "\n"
116      << " Failed to commit frames: " << delta.failed_kms_present_ << "\n"
117      << ((delta.failed_kms_present_ > 0)
118              ? " !!! Internal failure, FIX it please\n"
119              : "")
120      << " Flattened frames: " << delta.frames_flattened_ << "\n"
121      << " Pixel operations (free units)"
122      << " : [TOTAL: " << delta.total_pixops_ << " / GPU: " << delta.gpu_pixops_
123      << "]\n"
124      << " Composition efficiency: " << ratio;
125 
126   return ss.str();
127 }
128 
Dump()129 std::string HwcDisplay::Dump() {
130   auto connector_name = IsInHeadlessMode()
131                             ? std::string("NULL-DISPLAY")
132                             : GetPipe().connector->Get()->GetName();
133 
134   std::stringstream ss;
135   ss << "- Display on: " << connector_name << "\n"
136      << "Statistics since system boot:\n"
137      << DumpDelta(total_stats_) << "\n\n"
138      << "Statistics since last dumpsys request:\n"
139      << DumpDelta(total_stats_.minus(prev_stats_)) << "\n\n";
140 
141   memcpy(&prev_stats_, &total_stats_, sizeof(Stats));
142   return ss.str();
143 }
144 
HwcDisplay(hwc2_display_t handle,HWC2::DisplayType type,DrmHwc * hwc)145 HwcDisplay::HwcDisplay(hwc2_display_t handle, HWC2::DisplayType type,
146                        DrmHwc *hwc)
147     : hwc_(hwc), handle_(handle), type_(type), client_layer_(this) {
148   if (type_ == HWC2::DisplayType::Virtual) {
149     writeback_layer_ = std::make_unique<HwcLayer>(this);
150   }
151 }
152 
SetColorMatrixToIdentity()153 void HwcDisplay::SetColorMatrixToIdentity() {
154   color_matrix_ = std::make_shared<drm_color_ctm>();
155   for (int i = 0; i < kCtmCols; i++) {
156     for (int j = 0; j < kCtmRows; j++) {
157       constexpr uint64_t kOne = (1ULL << 32); /* 1.0 in s31.32 format */
158       color_matrix_->matrix[i * kCtmRows + j] = (i == j) ? kOne : 0;
159     }
160   }
161 
162   color_transform_hint_ = HAL_COLOR_TRANSFORM_IDENTITY;
163 }
164 
~HwcDisplay()165 HwcDisplay::~HwcDisplay() {
166   Deinit();
167 };
168 
GetConfig(hwc2_config_t config_id) const169 auto HwcDisplay::GetConfig(hwc2_config_t config_id) const
170     -> const HwcDisplayConfig * {
171   auto config_iter = configs_.hwc_configs.find(config_id);
172   if (config_iter == configs_.hwc_configs.end()) {
173     return nullptr;
174   }
175   return &config_iter->second;
176 }
177 
GetCurrentConfig() const178 auto HwcDisplay::GetCurrentConfig() const -> const HwcDisplayConfig * {
179   return GetConfig(configs_.active_config_id);
180 }
181 
GetLastRequestedConfig() const182 auto HwcDisplay::GetLastRequestedConfig() const -> const HwcDisplayConfig * {
183   return GetConfig(staged_mode_config_id_.value_or(configs_.active_config_id));
184 }
185 
SetConfig(hwc2_config_t config)186 HwcDisplay::ConfigError HwcDisplay::SetConfig(hwc2_config_t config) {
187   const HwcDisplayConfig *new_config = GetConfig(config);
188   if (new_config == nullptr) {
189     ALOGE("Could not find active mode for %u", config);
190     return ConfigError::kBadConfig;
191   }
192 
193   const HwcDisplayConfig *current_config = GetCurrentConfig();
194 
195   const uint32_t width = new_config->mode.GetRawMode().hdisplay;
196   const uint32_t height = new_config->mode.GetRawMode().vdisplay;
197 
198   std::optional<LayerData> modeset_layer_data;
199   // If a client layer has already been provided, and its size matches the
200   // new config, use it for the modeset.
201   if (client_layer_.IsLayerUsableAsDevice() && current_config &&
202       current_config->mode.GetRawMode().hdisplay == width &&
203       current_config->mode.GetRawMode().vdisplay == height) {
204     ALOGV("Use existing client_layer for blocking config.");
205     modeset_layer_data = client_layer_.GetLayerData();
206   } else {
207     ALOGV("Allocate modeset buffer.");
208     buffer_handle_t modeset_buffer = GetModesetBuffer(width, height);
209     if (modeset_buffer != nullptr) {
210       auto modeset_layer = std::make_unique<HwcLayer>(this);
211       modeset_layer->SetLayerProperties(
212           GetModesetLayerProperties(modeset_buffer, width, height));
213       modeset_layer->PopulateLayerData();
214       modeset_layer_data = modeset_layer->GetLayerData();
215       GraphicBufferAllocator::get().free(modeset_buffer);
216     }
217   }
218 
219   ALOGV("Create modeset commit.");
220   // Create atomic commit args for a blocking modeset. There's no need to do a
221   // separate test commit, since the commit does a test anyways.
222   AtomicCommitArgs commit_args = CreateModesetCommit(new_config,
223                                                      modeset_layer_data);
224   commit_args.blocking = true;
225   int ret = GetPipe().atomic_state_manager->ExecuteAtomicCommit(commit_args);
226 
227   if (ret) {
228     ALOGE("Blocking config failed: %d", ret);
229     return HwcDisplay::ConfigError::kBadConfig;
230   }
231 
232   ALOGV("Blocking config succeeded.");
233   configs_.active_config_id = config;
234   staged_mode_config_id_.reset();
235   return ConfigError::kNone;
236 }
237 
QueueConfig(hwc2_config_t config,int64_t desired_time,bool seamless,QueuedConfigTiming * out_timing)238 auto HwcDisplay::QueueConfig(hwc2_config_t config, int64_t desired_time,
239                              bool seamless, QueuedConfigTiming *out_timing)
240     -> ConfigError {
241   if (configs_.hwc_configs.count(config) == 0) {
242     ALOGE("Could not find active mode for %u", config);
243     return ConfigError::kBadConfig;
244   }
245 
246   // TODO: Add support for seamless configuration changes.
247   if (seamless) {
248     return ConfigError::kSeamlessNotAllowed;
249   }
250 
251   // Request a refresh from the client one vsync period before the desired
252   // time, or simply at the desired time if there is no active configuration.
253   const HwcDisplayConfig *current_config = GetCurrentConfig();
254   out_timing->refresh_time_ns = desired_time -
255                                 (current_config
256                                      ? current_config->mode.GetVSyncPeriodNs()
257                                      : 0);
258   out_timing->new_vsync_time_ns = desired_time;
259 
260   // Queue the config change timing to be consistent with the requested
261   // refresh time.
262   staged_mode_change_time_ = out_timing->refresh_time_ns;
263   staged_mode_config_id_ = config;
264 
265   // Enable vsync events until the mode has been applied.
266   last_vsync_ts_ = 0;
267   vsync_tracking_en_ = true;
268   vsync_worker_->VSyncControl(true);
269 
270   return ConfigError::kNone;
271 }
272 
SetPipeline(std::shared_ptr<DrmDisplayPipeline> pipeline)273 void HwcDisplay::SetPipeline(std::shared_ptr<DrmDisplayPipeline> pipeline) {
274   Deinit();
275 
276   pipeline_ = std::move(pipeline);
277 
278   if (pipeline_ != nullptr || handle_ == kPrimaryDisplay) {
279     Init();
280     hwc_->ScheduleHotplugEvent(handle_, DrmHwc::kConnected);
281   } else {
282     hwc_->ScheduleHotplugEvent(handle_, DrmHwc::kDisconnected);
283   }
284 }
285 
Deinit()286 void HwcDisplay::Deinit() {
287   if (pipeline_ != nullptr) {
288     AtomicCommitArgs a_args{};
289     a_args.composition = std::make_shared<DrmKmsPlan>();
290     GetPipe().atomic_state_manager->ExecuteAtomicCommit(a_args);
291     a_args.composition = {};
292     a_args.active = false;
293     GetPipe().atomic_state_manager->ExecuteAtomicCommit(a_args);
294 
295     current_plan_.reset();
296     backend_.reset();
297     if (flatcon_) {
298       flatcon_->StopThread();
299       flatcon_.reset();
300     }
301   }
302 
303   if (vsync_worker_) {
304     // TODO: There should be a mechanism to wait for this worker to complete,
305     // otherwise there is a race condition while destructing the HwcDisplay.
306     vsync_worker_->StopThread();
307     vsync_worker_ = {};
308   }
309 
310   SetClientTarget(nullptr, -1, 0, {});
311 }
312 
Init()313 HWC2::Error HwcDisplay::Init() {
314   ChosePreferredConfig();
315 
316   auto vsw_callbacks = (VSyncWorkerCallbacks){
317       .out_event =
318           [this](int64_t timestamp) {
319             const std::unique_lock lock(hwc_->GetResMan().GetMainLock());
320             if (vsync_event_en_) {
321               uint32_t period_ns{};
322               GetDisplayVsyncPeriod(&period_ns);
323               hwc_->SendVsyncEventToClient(handle_, timestamp, period_ns);
324             }
325             if (vsync_tracking_en_) {
326               last_vsync_ts_ = timestamp;
327             }
328             if (!vsync_event_en_ && !vsync_tracking_en_) {
329               vsync_worker_->VSyncControl(false);
330             }
331           },
332       .get_vperiod_ns = [this]() -> uint32_t {
333         uint32_t outVsyncPeriod = 0;
334         GetDisplayVsyncPeriod(&outVsyncPeriod);
335         return outVsyncPeriod;
336       },
337   };
338 
339   if (type_ != HWC2::DisplayType::Virtual) {
340     vsync_worker_ = VSyncWorker::CreateInstance(pipeline_, vsw_callbacks);
341     if (!vsync_worker_) {
342       ALOGE("Failed to create event worker for d=%d\n", int(handle_));
343       return HWC2::Error::BadDisplay;
344     }
345   }
346 
347   if (!IsInHeadlessMode()) {
348     auto ret = BackendManager::GetInstance().SetBackendForDisplay(this);
349     if (ret) {
350       ALOGE("Failed to set backend for d=%d %d\n", int(handle_), ret);
351       return HWC2::Error::BadDisplay;
352     }
353     auto flatcbk = (struct FlatConCallbacks){
354         .trigger = [this]() { hwc_->SendRefreshEventToClient(handle_); }};
355     flatcon_ = FlatteningController::CreateInstance(flatcbk);
356   }
357 
358   client_layer_.SetLayerBlendMode(HWC2_BLEND_MODE_PREMULTIPLIED);
359 
360   SetColorMatrixToIdentity();
361 
362   return HWC2::Error::None;
363 }
364 
getDisplayPhysicalOrientation()365 std::optional<PanelOrientation> HwcDisplay::getDisplayPhysicalOrientation() {
366   if (IsInHeadlessMode()) {
367     // The pipeline can be nullptr in headless mode, so return the default
368     // "normal" mode.
369     return PanelOrientation::kModePanelOrientationNormal;
370   }
371 
372   DrmDisplayPipeline &pipeline = GetPipe();
373   if (pipeline.connector == nullptr || pipeline.connector->Get() == nullptr) {
374     ALOGW(
375         "No display pipeline present to query the panel orientation property.");
376     return {};
377   }
378 
379   return pipeline.connector->Get()->GetPanelOrientation();
380 }
381 
ChosePreferredConfig()382 HWC2::Error HwcDisplay::ChosePreferredConfig() {
383   HWC2::Error err{};
384   if (type_ == HWC2::DisplayType::Virtual) {
385     configs_.GenFakeMode(virtual_disp_width_, virtual_disp_height_);
386   } else if (!IsInHeadlessMode()) {
387     err = configs_.Update(*pipeline_->connector->Get());
388   } else {
389     configs_.GenFakeMode(0, 0);
390   }
391   if (!IsInHeadlessMode() && err != HWC2::Error::None) {
392     return HWC2::Error::BadDisplay;
393   }
394 
395   return SetActiveConfig(configs_.preferred_config_id);
396 }
397 
AcceptDisplayChanges()398 HWC2::Error HwcDisplay::AcceptDisplayChanges() {
399   for (std::pair<const hwc2_layer_t, HwcLayer> &l : layers_)
400     l.second.AcceptTypeChange();
401   return HWC2::Error::None;
402 }
403 
CreateLayer(hwc2_layer_t * layer)404 HWC2::Error HwcDisplay::CreateLayer(hwc2_layer_t *layer) {
405   layers_.emplace(static_cast<hwc2_layer_t>(layer_idx_), HwcLayer(this));
406   *layer = static_cast<hwc2_layer_t>(layer_idx_);
407   ++layer_idx_;
408   return HWC2::Error::None;
409 }
410 
DestroyLayer(hwc2_layer_t layer)411 HWC2::Error HwcDisplay::DestroyLayer(hwc2_layer_t layer) {
412   if (!get_layer(layer)) {
413     return HWC2::Error::BadLayer;
414   }
415 
416   layers_.erase(layer);
417   return HWC2::Error::None;
418 }
419 
GetActiveConfig(hwc2_config_t * config) const420 HWC2::Error HwcDisplay::GetActiveConfig(hwc2_config_t *config) const {
421   // If a config has been queued, it is considered the "active" config.
422   const HwcDisplayConfig *hwc_config = GetLastRequestedConfig();
423   if (hwc_config == nullptr)
424     return HWC2::Error::BadConfig;
425 
426   *config = hwc_config->id;
427   return HWC2::Error::None;
428 }
429 
GetChangedCompositionTypes(uint32_t * num_elements,hwc2_layer_t * layers,int32_t * types)430 HWC2::Error HwcDisplay::GetChangedCompositionTypes(uint32_t *num_elements,
431                                                    hwc2_layer_t *layers,
432                                                    int32_t *types) {
433   if (IsInHeadlessMode()) {
434     *num_elements = 0;
435     return HWC2::Error::None;
436   }
437 
438   uint32_t num_changes = 0;
439   for (auto &l : layers_) {
440     if (l.second.IsTypeChanged()) {
441       if (layers && num_changes < *num_elements)
442         layers[num_changes] = l.first;
443       if (types && num_changes < *num_elements)
444         types[num_changes] = static_cast<int32_t>(l.second.GetValidatedType());
445       ++num_changes;
446     }
447   }
448   if (!layers && !types)
449     *num_elements = num_changes;
450   return HWC2::Error::None;
451 }
452 
GetClientTargetSupport(uint32_t width,uint32_t height,int32_t,int32_t dataspace)453 HWC2::Error HwcDisplay::GetClientTargetSupport(uint32_t width, uint32_t height,
454                                                int32_t /*format*/,
455                                                int32_t dataspace) {
456   if (IsInHeadlessMode()) {
457     return HWC2::Error::None;
458   }
459 
460   auto min = pipeline_->device->GetMinResolution();
461   auto max = pipeline_->device->GetMaxResolution();
462 
463   if (width < min.first || height < min.second)
464     return HWC2::Error::Unsupported;
465 
466   if (width > max.first || height > max.second)
467     return HWC2::Error::Unsupported;
468 
469   if (dataspace != HAL_DATASPACE_UNKNOWN)
470     return HWC2::Error::Unsupported;
471 
472   // TODO(nobody): Validate format can be handled by either GL or planes
473   return HWC2::Error::None;
474 }
475 
GetColorModes(uint32_t * num_modes,int32_t * modes)476 HWC2::Error HwcDisplay::GetColorModes(uint32_t *num_modes, int32_t *modes) {
477   if (!modes)
478     *num_modes = 1;
479 
480   if (modes)
481     *modes = HAL_COLOR_MODE_NATIVE;
482 
483   return HWC2::Error::None;
484 }
485 
GetDisplayAttribute(hwc2_config_t config,int32_t attribute_in,int32_t * value)486 HWC2::Error HwcDisplay::GetDisplayAttribute(hwc2_config_t config,
487                                             int32_t attribute_in,
488                                             int32_t *value) {
489   int conf = static_cast<int>(config);
490 
491   if (configs_.hwc_configs.count(conf) == 0) {
492     ALOGE("Could not find mode #%d", conf);
493     return HWC2::Error::BadConfig;
494   }
495 
496   auto &hwc_config = configs_.hwc_configs[conf];
497 
498   static const int32_t kUmPerInch = 25400;
499   auto mm_width = configs_.mm_width;
500   auto attribute = static_cast<HWC2::Attribute>(attribute_in);
501   switch (attribute) {
502     case HWC2::Attribute::Width:
503       *value = static_cast<int>(hwc_config.mode.GetRawMode().hdisplay);
504       break;
505     case HWC2::Attribute::Height:
506       *value = static_cast<int>(hwc_config.mode.GetRawMode().vdisplay);
507       break;
508     case HWC2::Attribute::VsyncPeriod:
509       // in nanoseconds
510       *value = hwc_config.mode.GetVSyncPeriodNs();
511       break;
512     case HWC2::Attribute::DpiY:
513       // ideally this should be vdisplay/mm_heigth, however mm_height
514       // comes from edid parsing and is highly unreliable. Viewing the
515       // rarity of anisotropic displays, falling back to a single value
516       // for dpi yield more correct output.
517     case HWC2::Attribute::DpiX:
518       // Dots per 1000 inches
519       *value = mm_width ? int(hwc_config.mode.GetRawMode().hdisplay *
520                               kUmPerInch / mm_width)
521                         : -1;
522       break;
523 #if __ANDROID_API__ > 29
524     case HWC2::Attribute::ConfigGroup:
525       /* Dispite ConfigGroup is a part of HWC2.4 API, framework
526        * able to request it even if service @2.1 is used */
527       *value = int(hwc_config.group_id);
528       break;
529 #endif
530     default:
531       *value = -1;
532       return HWC2::Error::BadConfig;
533   }
534   return HWC2::Error::None;
535 }
536 
LegacyGetDisplayConfigs(uint32_t * num_configs,hwc2_config_t * configs)537 HWC2::Error HwcDisplay::LegacyGetDisplayConfigs(uint32_t *num_configs,
538                                                 hwc2_config_t *configs) {
539   uint32_t idx = 0;
540   for (auto &hwc_config : configs_.hwc_configs) {
541     if (hwc_config.second.disabled) {
542       continue;
543     }
544 
545     if (configs != nullptr) {
546       if (idx >= *num_configs) {
547         break;
548       }
549       configs[idx] = hwc_config.second.id;
550     }
551 
552     idx++;
553   }
554   *num_configs = idx;
555   return HWC2::Error::None;
556 }
557 
GetDisplayName(uint32_t * size,char * name)558 HWC2::Error HwcDisplay::GetDisplayName(uint32_t *size, char *name) {
559   std::ostringstream stream;
560   if (IsInHeadlessMode()) {
561     stream << "null-display";
562   } else {
563     stream << "display-" << GetPipe().connector->Get()->GetId();
564   }
565   auto string = stream.str();
566   auto length = string.length();
567   if (!name) {
568     *size = length;
569     return HWC2::Error::None;
570   }
571 
572   *size = std::min<uint32_t>(static_cast<uint32_t>(length - 1), *size);
573   strncpy(name, string.c_str(), *size);
574   return HWC2::Error::None;
575 }
576 
GetDisplayRequests(int32_t *,uint32_t * num_elements,hwc2_layer_t *,int32_t *)577 HWC2::Error HwcDisplay::GetDisplayRequests(int32_t * /*display_requests*/,
578                                            uint32_t *num_elements,
579                                            hwc2_layer_t * /*layers*/,
580                                            int32_t * /*layer_requests*/) {
581   // TODO(nobody): I think virtual display should request
582   //      HWC2_DISPLAY_REQUEST_WRITE_CLIENT_TARGET_TO_OUTPUT here
583   *num_elements = 0;
584   return HWC2::Error::None;
585 }
586 
GetDisplayType(int32_t * type)587 HWC2::Error HwcDisplay::GetDisplayType(int32_t *type) {
588   *type = static_cast<int32_t>(type_);
589   return HWC2::Error::None;
590 }
591 
GetDozeSupport(int32_t * support)592 HWC2::Error HwcDisplay::GetDozeSupport(int32_t *support) {
593   *support = 0;
594   return HWC2::Error::None;
595 }
596 
GetHdrCapabilities(uint32_t * num_types,int32_t *,float *,float *,float *)597 HWC2::Error HwcDisplay::GetHdrCapabilities(uint32_t *num_types,
598                                            int32_t * /*types*/,
599                                            float * /*max_luminance*/,
600                                            float * /*max_average_luminance*/,
601                                            float * /*min_luminance*/) {
602   *num_types = 0;
603   return HWC2::Error::None;
604 }
605 
606 /* Find API details at:
607  * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r3:hardware/libhardware/include/hardware/hwcomposer2.h;l=1767
608  *
609  * Called after PresentDisplay(), CLIENT is expecting release fence for the
610  * prior buffer (not the one assigned to the layer at the moment).
611  */
GetReleaseFences(uint32_t * num_elements,hwc2_layer_t * layers,int32_t * fences)612 HWC2::Error HwcDisplay::GetReleaseFences(uint32_t *num_elements,
613                                          hwc2_layer_t *layers,
614                                          int32_t *fences) {
615   if (IsInHeadlessMode()) {
616     *num_elements = 0;
617     return HWC2::Error::None;
618   }
619 
620   uint32_t num_layers = 0;
621 
622   for (auto &l : layers_) {
623     if (!l.second.GetPriorBufferScanOutFlag() || !present_fence_) {
624       continue;
625     }
626 
627     ++num_layers;
628 
629     if (layers == nullptr || fences == nullptr)
630       continue;
631 
632     if (num_layers > *num_elements) {
633       ALOGW("Overflow num_elements %d/%d", num_layers, *num_elements);
634       return HWC2::Error::None;
635     }
636 
637     layers[num_layers - 1] = l.first;
638     fences[num_layers - 1] = DupFd(present_fence_);
639   }
640   *num_elements = num_layers;
641 
642   return HWC2::Error::None;
643 }
644 
CreateModesetCommit(const HwcDisplayConfig * config,const std::optional<LayerData> & modeset_layer)645 AtomicCommitArgs HwcDisplay::CreateModesetCommit(
646     const HwcDisplayConfig *config,
647     const std::optional<LayerData> &modeset_layer) {
648   AtomicCommitArgs args{};
649 
650   args.color_matrix = color_matrix_;
651   args.content_type = content_type_;
652   args.colorspace = colorspace_;
653 
654   std::vector<LayerData> composition_layers;
655   if (modeset_layer) {
656     composition_layers.emplace_back(modeset_layer.value());
657   }
658 
659   if (composition_layers.empty()) {
660     ALOGW("Attempting to create a modeset commit without a layer.");
661   }
662 
663   args.display_mode = config->mode;
664   args.active = true;
665   args.composition = DrmKmsPlan::CreateDrmKmsPlan(GetPipe(),
666                                                   std::move(
667                                                       composition_layers));
668   ALOGW_IF(!args.composition, "No composition for blocking modeset");
669 
670   return args;
671 }
672 
CreateComposition(AtomicCommitArgs & a_args)673 HWC2::Error HwcDisplay::CreateComposition(AtomicCommitArgs &a_args) {
674   if (IsInHeadlessMode()) {
675     ALOGE("%s: Display is in headless mode, should never reach here", __func__);
676     return HWC2::Error::None;
677   }
678 
679   a_args.color_matrix = color_matrix_;
680   a_args.content_type = content_type_;
681   a_args.colorspace = colorspace_;
682 
683   uint32_t prev_vperiod_ns = 0;
684   GetDisplayVsyncPeriod(&prev_vperiod_ns);
685 
686   auto mode_update_commited_ = false;
687   if (staged_mode_config_id_ &&
688       staged_mode_change_time_ <= ResourceManager::GetTimeMonotonicNs()) {
689     const HwcDisplayConfig *staged_config = GetConfig(
690         staged_mode_config_id_.value());
691     if (staged_config == nullptr) {
692       return HWC2::Error::BadConfig;
693     }
694     client_layer_.SetLayerDisplayFrame(
695         (hwc_rect_t){.left = 0,
696                      .top = 0,
697                      .right = int(staged_config->mode.GetRawMode().hdisplay),
698                      .bottom = int(staged_config->mode.GetRawMode().vdisplay)});
699 
700     configs_.active_config_id = staged_mode_config_id_.value();
701 
702     a_args.display_mode = staged_config->mode;
703     if (!a_args.test_only) {
704       mode_update_commited_ = true;
705     }
706   }
707 
708   // order the layers by z-order
709   bool use_client_layer = false;
710   uint32_t client_z_order = UINT32_MAX;
711   std::map<uint32_t, HwcLayer *> z_map;
712   for (std::pair<const hwc2_layer_t, HwcLayer> &l : layers_) {
713     switch (l.second.GetValidatedType()) {
714       case HWC2::Composition::Device:
715         z_map.emplace(l.second.GetZOrder(), &l.second);
716         break;
717       case HWC2::Composition::Client:
718         // Place it at the z_order of the lowest client layer
719         use_client_layer = true;
720         client_z_order = std::min(client_z_order, l.second.GetZOrder());
721         break;
722       default:
723         continue;
724     }
725   }
726   if (use_client_layer)
727     z_map.emplace(client_z_order, &client_layer_);
728 
729   if (z_map.empty())
730     return HWC2::Error::BadLayer;
731 
732   std::vector<LayerData> composition_layers;
733 
734   /* Import & populate */
735   for (std::pair<const uint32_t, HwcLayer *> &l : z_map) {
736     l.second->PopulateLayerData();
737   }
738 
739   // now that they're ordered by z, add them to the composition
740   for (std::pair<const uint32_t, HwcLayer *> &l : z_map) {
741     if (!l.second->IsLayerUsableAsDevice()) {
742       /* This will be normally triggered on validation of the first frame
743        * containing CLIENT layer. At this moment client buffer is not yet
744        * provided by the CLIENT.
745        * This may be triggered once in HwcLayer lifecycle in case FB can't be
746        * imported. For example when non-contiguous buffer is imported into
747        * contiguous-only DRM/KMS driver.
748        */
749       return HWC2::Error::BadLayer;
750     }
751     composition_layers.emplace_back(l.second->GetLayerData());
752   }
753 
754   /* Store plan to ensure shared planes won't be stolen by other display
755    * in between of ValidateDisplay() and PresentDisplay() calls
756    */
757   current_plan_ = DrmKmsPlan::CreateDrmKmsPlan(GetPipe(),
758                                                std::move(composition_layers));
759 
760   if (type_ == HWC2::DisplayType::Virtual) {
761     a_args.writeback_fb = writeback_layer_->GetLayerData().fb;
762     a_args.writeback_release_fence = writeback_layer_->GetLayerData()
763                                          .acquire_fence;
764   }
765 
766   if (!current_plan_) {
767     ALOGE_IF(!a_args.test_only, "Failed to create DrmKmsPlan");
768     return HWC2::Error::BadConfig;
769   }
770 
771   a_args.composition = current_plan_;
772 
773   auto ret = GetPipe().atomic_state_manager->ExecuteAtomicCommit(a_args);
774 
775   if (ret) {
776     ALOGE_IF(!a_args.test_only, "Failed to apply the frame composition ret=%d", ret);
777     return HWC2::Error::BadParameter;
778   }
779 
780   if (mode_update_commited_) {
781     staged_mode_config_id_.reset();
782     vsync_tracking_en_ = false;
783     if (last_vsync_ts_ != 0) {
784       hwc_->SendVsyncPeriodTimingChangedEventToClient(handle_,
785                                                       last_vsync_ts_ +
786                                                           prev_vperiod_ns);
787     }
788   }
789 
790   return HWC2::Error::None;
791 }
792 
793 /* Find API details at:
794  * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r3:hardware/libhardware/include/hardware/hwcomposer2.h;l=1805
795  */
PresentDisplay(int32_t * out_present_fence)796 HWC2::Error HwcDisplay::PresentDisplay(int32_t *out_present_fence) {
797   if (IsInHeadlessMode()) {
798     *out_present_fence = -1;
799     return HWC2::Error::None;
800   }
801   HWC2::Error ret{};
802 
803   ++total_stats_.total_frames_;
804 
805   AtomicCommitArgs a_args{};
806   ret = CreateComposition(a_args);
807 
808   if (ret != HWC2::Error::None)
809     ++total_stats_.failed_kms_present_;
810 
811   if (ret == HWC2::Error::BadLayer) {
812     // Can we really have no client or device layers?
813     *out_present_fence = -1;
814     return HWC2::Error::None;
815   }
816   if (ret != HWC2::Error::None)
817     return ret;
818 
819   this->present_fence_ = a_args.out_fence;
820   *out_present_fence = DupFd(a_args.out_fence);
821 
822   // Reset the color matrix so we don't apply it over and over again.
823   color_matrix_ = {};
824 
825   ++frame_no_;
826 
827   return HWC2::Error::None;
828 }
829 
SetActiveConfigInternal(uint32_t config,int64_t change_time)830 HWC2::Error HwcDisplay::SetActiveConfigInternal(uint32_t config,
831                                                 int64_t change_time) {
832   if (configs_.hwc_configs.count(config) == 0) {
833     ALOGE("Could not find active mode for %u", config);
834     return HWC2::Error::BadConfig;
835   }
836 
837   staged_mode_change_time_ = change_time;
838   staged_mode_config_id_ = config;
839 
840   return HWC2::Error::None;
841 }
842 
SetActiveConfig(hwc2_config_t config)843 HWC2::Error HwcDisplay::SetActiveConfig(hwc2_config_t config) {
844   return SetActiveConfigInternal(config, ResourceManager::GetTimeMonotonicNs());
845 }
846 
847 /* Find API details at:
848  * https://cs.android.com/android/platform/superproject/+/android-11.0.0_r3:hardware/libhardware/include/hardware/hwcomposer2.h;l=1861
849  */
SetClientTarget(buffer_handle_t target,int32_t acquire_fence,int32_t dataspace,hwc_region_t)850 HWC2::Error HwcDisplay::SetClientTarget(buffer_handle_t target,
851                                         int32_t acquire_fence,
852                                         int32_t dataspace,
853                                         hwc_region_t /*damage*/) {
854   client_layer_.SetLayerBuffer(target, acquire_fence);
855   client_layer_.SetLayerDataspace(dataspace);
856 
857   /*
858    * target can be nullptr, this does mean the Composer Service is calling
859    * cleanDisplayResources() on after receiving HOTPLUG event. See more at:
860    * 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
861    */
862   if (target == nullptr) {
863     client_layer_.SwChainClearCache();
864     return HWC2::Error::None;
865   }
866 
867   if (IsInHeadlessMode()) {
868     return HWC2::Error::None;
869   }
870 
871   client_layer_.PopulateLayerData();
872   if (!client_layer_.IsLayerUsableAsDevice()) {
873     ALOGE("Client layer must be always usable by DRM/KMS");
874     return HWC2::Error::BadLayer;
875   }
876 
877   auto &bi = client_layer_.GetLayerData().bi;
878   if (!bi) {
879     ALOGE("%s: Invalid state", __func__);
880     return HWC2::Error::BadLayer;
881   }
882 
883   auto source_crop = (hwc_frect_t){.left = 0.0F,
884                                    .top = 0.0F,
885                                    .right = static_cast<float>(bi->width),
886                                    .bottom = static_cast<float>(bi->height)};
887   client_layer_.SetLayerSourceCrop(source_crop);
888 
889   return HWC2::Error::None;
890 }
891 
SetColorMode(int32_t mode)892 HWC2::Error HwcDisplay::SetColorMode(int32_t mode) {
893   /* Maps to the Colorspace DRM connector property:
894    * https://elixir.bootlin.com/linux/v6.11/source/include/drm/drm_connector.h#L538
895    */
896   if (mode < HAL_COLOR_MODE_NATIVE || mode > HAL_COLOR_MODE_DISPLAY_P3)
897     return HWC2::Error::BadParameter;
898 
899   switch (mode) {
900     case HAL_COLOR_MODE_NATIVE:
901       colorspace_ = Colorspace::kDefault;
902       break;
903     case HAL_COLOR_MODE_STANDARD_BT601_625:
904     case HAL_COLOR_MODE_STANDARD_BT601_625_UNADJUSTED:
905     case HAL_COLOR_MODE_STANDARD_BT601_525:
906     case HAL_COLOR_MODE_STANDARD_BT601_525_UNADJUSTED:
907       // The DP spec does not say whether this is the 525 or the 625 line version.
908       colorspace_ = Colorspace::kBt601Ycc;
909       break;
910     case HAL_COLOR_MODE_STANDARD_BT709:
911     case HAL_COLOR_MODE_SRGB:
912       colorspace_ = Colorspace::kBt709Ycc;
913       break;
914     case HAL_COLOR_MODE_DCI_P3:
915     case HAL_COLOR_MODE_DISPLAY_P3:
916       colorspace_ = Colorspace::kDciP3RgbD65;
917       break;
918     case HAL_COLOR_MODE_ADOBE_RGB:
919     default:
920       return HWC2::Error::Unsupported;
921   }
922 
923   color_mode_ = mode;
924   return HWC2::Error::None;
925 }
926 
927 #include <xf86drmMode.h>
928 
To3132FixPt(float in)929 static uint64_t To3132FixPt(float in) {
930   constexpr uint64_t kSignMask = (1ULL << 63);
931   constexpr uint64_t kValueMask = ~(1ULL << 63);
932   constexpr auto kValueScale = static_cast<float>(1ULL << 32);
933   if (in < 0)
934     return (static_cast<uint64_t>(-in * kValueScale) & kValueMask) | kSignMask;
935   return static_cast<uint64_t>(in * kValueScale) & kValueMask;
936 }
937 
SetColorTransform(const float * matrix,int32_t hint)938 HWC2::Error HwcDisplay::SetColorTransform(const float *matrix, int32_t hint) {
939   if (hint < HAL_COLOR_TRANSFORM_IDENTITY ||
940       hint > HAL_COLOR_TRANSFORM_CORRECT_TRITANOPIA)
941     return HWC2::Error::BadParameter;
942 
943   if (!matrix && hint == HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX)
944     return HWC2::Error::BadParameter;
945 
946   color_transform_hint_ = static_cast<android_color_transform_t>(hint);
947 
948   if (IsInHeadlessMode())
949     return HWC2::Error::None;
950 
951   if (!GetPipe().crtc->Get()->GetCtmProperty())
952     return HWC2::Error::None;
953 
954   switch (color_transform_hint_) {
955     case HAL_COLOR_TRANSFORM_IDENTITY:
956       SetColorMatrixToIdentity();
957       break;
958     case HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX:
959       // Without HW support, we cannot correctly process matrices with an offset.
960       for (int i = 12; i < 14; i++) {
961         if (matrix[i] != 0.F)
962           return HWC2::Error::Unsupported;
963       }
964 
965       /* HAL provides a 4x4 float type matrix:
966        * | 0  1  2  3|
967        * | 4  5  6  7|
968        * | 8  9 10 11|
969        * |12 13 14 15|
970        *
971        * R_out = R*0 + G*4 + B*8 + 12
972        * G_out = R*1 + G*5 + B*9 + 13
973        * B_out = R*2 + G*6 + B*10 + 14
974        *
975        * DRM expects a 3x3 s31.32 fixed point matrix:
976        * out   matrix    in
977        * |R|   |0 1 2|   |R|
978        * |G| = |3 4 5| x |G|
979        * |B|   |6 7 8|   |B|
980        *
981        * R_out = R*0 + G*1 + B*2
982        * G_out = R*3 + G*4 + B*5
983        * B_out = R*6 + G*7 + B*8
984        */
985       color_matrix_ = std::make_shared<drm_color_ctm>();
986       for (int i = 0; i < kCtmCols; i++) {
987         for (int j = 0; j < kCtmRows; j++) {
988           constexpr int kInCtmRows = 4;
989           color_matrix_->matrix[i * kCtmRows + j] = To3132FixPt(matrix[j * kInCtmRows + i]);
990         }
991       }
992       break;
993     default:
994       return HWC2::Error::Unsupported;
995   }
996 
997   return HWC2::Error::None;
998 }
999 
CtmByGpu()1000 bool HwcDisplay::CtmByGpu() {
1001   if (color_transform_hint_ == HAL_COLOR_TRANSFORM_IDENTITY)
1002     return false;
1003 
1004   if (GetPipe().crtc->Get()->GetCtmProperty())
1005     return false;
1006 
1007   if (GetHwc()->GetResMan().GetCtmHandling() == CtmHandling::kDrmOrIgnore)
1008     return false;
1009 
1010   return true;
1011 }
1012 
SetOutputBuffer(buffer_handle_t buffer,int32_t release_fence)1013 HWC2::Error HwcDisplay::SetOutputBuffer(buffer_handle_t buffer,
1014                                         int32_t release_fence) {
1015   writeback_layer_->SetLayerBuffer(buffer, release_fence);
1016   writeback_layer_->PopulateLayerData();
1017   if (!writeback_layer_->IsLayerUsableAsDevice()) {
1018     ALOGE("Output layer must be always usable by DRM/KMS");
1019     return HWC2::Error::BadLayer;
1020   }
1021   /* TODO: Check if format is supported by writeback connector */
1022   return HWC2::Error::None;
1023 }
1024 
SetPowerMode(int32_t mode_in)1025 HWC2::Error HwcDisplay::SetPowerMode(int32_t mode_in) {
1026   auto mode = static_cast<HWC2::PowerMode>(mode_in);
1027 
1028   AtomicCommitArgs a_args{};
1029 
1030   switch (mode) {
1031     case HWC2::PowerMode::Off:
1032       a_args.active = false;
1033       break;
1034     case HWC2::PowerMode::On:
1035       a_args.active = true;
1036       break;
1037     case HWC2::PowerMode::Doze:
1038     case HWC2::PowerMode::DozeSuspend:
1039       return HWC2::Error::Unsupported;
1040     default:
1041       ALOGE("Incorrect power mode value (%d)\n", mode_in);
1042       return HWC2::Error::BadParameter;
1043   }
1044 
1045   if (IsInHeadlessMode()) {
1046     return HWC2::Error::None;
1047   }
1048 
1049   if (a_args.active && *a_args.active) {
1050     /*
1051      * Setting the display to active before we have a composition
1052      * can break some drivers, so skip setting a_args.active to
1053      * true, as the next composition frame will implicitly activate
1054      * the display
1055      */
1056     return GetPipe().atomic_state_manager->ActivateDisplayUsingDPMS() == 0
1057                ? HWC2::Error::None
1058                : HWC2::Error::BadParameter;
1059   };
1060 
1061   auto err = GetPipe().atomic_state_manager->ExecuteAtomicCommit(a_args);
1062   if (err) {
1063     ALOGE("Failed to apply the dpms composition err=%d", err);
1064     return HWC2::Error::BadParameter;
1065   }
1066   return HWC2::Error::None;
1067 }
1068 
SetVsyncEnabled(int32_t enabled)1069 HWC2::Error HwcDisplay::SetVsyncEnabled(int32_t enabled) {
1070   if (type_ == HWC2::DisplayType::Virtual) {
1071     return HWC2::Error::None;
1072   }
1073 
1074   vsync_event_en_ = HWC2_VSYNC_ENABLE == enabled;
1075   if (vsync_event_en_) {
1076     vsync_worker_->VSyncControl(true);
1077   }
1078   return HWC2::Error::None;
1079 }
1080 
ValidateDisplay(uint32_t * num_types,uint32_t * num_requests)1081 HWC2::Error HwcDisplay::ValidateDisplay(uint32_t *num_types,
1082                                         uint32_t *num_requests) {
1083   if (IsInHeadlessMode()) {
1084     *num_types = *num_requests = 0;
1085     return HWC2::Error::None;
1086   }
1087 
1088   /* In current drm_hwc design in case previous frame layer was not validated as
1089    * a CLIENT, it is used by display controller (Front buffer). We have to store
1090    * this state to provide the CLIENT with the release fences for such buffers.
1091    */
1092   for (auto &l : layers_) {
1093     l.second.SetPriorBufferScanOutFlag(l.second.GetValidatedType() !=
1094                                        HWC2::Composition::Client);
1095   }
1096 
1097   return backend_->ValidateDisplay(this, num_types, num_requests);
1098 }
1099 
GetOrderLayersByZPos()1100 std::vector<HwcLayer *> HwcDisplay::GetOrderLayersByZPos() {
1101   std::vector<HwcLayer *> ordered_layers;
1102   ordered_layers.reserve(layers_.size());
1103 
1104   for (auto &[handle, layer] : layers_) {
1105     ordered_layers.emplace_back(&layer);
1106   }
1107 
1108   std::sort(std::begin(ordered_layers), std::end(ordered_layers),
1109             [](const HwcLayer *lhs, const HwcLayer *rhs) {
1110               return lhs->GetZOrder() < rhs->GetZOrder();
1111             });
1112 
1113   return ordered_layers;
1114 }
1115 
GetDisplayVsyncPeriod(uint32_t * outVsyncPeriod)1116 HWC2::Error HwcDisplay::GetDisplayVsyncPeriod(
1117     uint32_t *outVsyncPeriod /* ns */) {
1118   return GetDisplayAttribute(configs_.active_config_id,
1119                              HWC2_ATTRIBUTE_VSYNC_PERIOD,
1120                              (int32_t *)(outVsyncPeriod));
1121 }
1122 
1123 #if __ANDROID_API__ > 29
GetDisplayConnectionType(uint32_t * outType)1124 HWC2::Error HwcDisplay::GetDisplayConnectionType(uint32_t *outType) {
1125   if (IsInHeadlessMode()) {
1126     *outType = static_cast<uint32_t>(HWC2::DisplayConnectionType::Internal);
1127     return HWC2::Error::None;
1128   }
1129   /* Primary display should be always internal,
1130    * otherwise SF will be unhappy and will crash
1131    */
1132   if (GetPipe().connector->Get()->IsInternal() || handle_ == kPrimaryDisplay)
1133     *outType = static_cast<uint32_t>(HWC2::DisplayConnectionType::Internal);
1134   else if (GetPipe().connector->Get()->IsExternal())
1135     *outType = static_cast<uint32_t>(HWC2::DisplayConnectionType::External);
1136   else
1137     return HWC2::Error::BadConfig;
1138 
1139   return HWC2::Error::None;
1140 }
1141 
SetActiveConfigWithConstraints(hwc2_config_t config,hwc_vsync_period_change_constraints_t * vsyncPeriodChangeConstraints,hwc_vsync_period_change_timeline_t * outTimeline)1142 HWC2::Error HwcDisplay::SetActiveConfigWithConstraints(
1143     hwc2_config_t config,
1144     hwc_vsync_period_change_constraints_t *vsyncPeriodChangeConstraints,
1145     hwc_vsync_period_change_timeline_t *outTimeline) {
1146   if (type_ == HWC2::DisplayType::Virtual) {
1147     return HWC2::Error::None;
1148   }
1149 
1150   if (vsyncPeriodChangeConstraints == nullptr || outTimeline == nullptr) {
1151     return HWC2::Error::BadParameter;
1152   }
1153 
1154   uint32_t current_vsync_period{};
1155   GetDisplayVsyncPeriod(&current_vsync_period);
1156 
1157   if (vsyncPeriodChangeConstraints->seamlessRequired) {
1158     return HWC2::Error::SeamlessNotAllowed;
1159   }
1160 
1161   outTimeline->refreshTimeNanos = vsyncPeriodChangeConstraints
1162                                       ->desiredTimeNanos -
1163                                   current_vsync_period;
1164   auto ret = SetActiveConfigInternal(config, outTimeline->refreshTimeNanos);
1165   if (ret != HWC2::Error::None) {
1166     return ret;
1167   }
1168 
1169   outTimeline->refreshRequired = true;
1170   outTimeline->newVsyncAppliedTimeNanos = vsyncPeriodChangeConstraints
1171                                               ->desiredTimeNanos;
1172 
1173   last_vsync_ts_ = 0;
1174   vsync_tracking_en_ = true;
1175   vsync_worker_->VSyncControl(true);
1176 
1177   return HWC2::Error::None;
1178 }
1179 
SetAutoLowLatencyMode(bool)1180 HWC2::Error HwcDisplay::SetAutoLowLatencyMode(bool /*on*/) {
1181   return HWC2::Error::Unsupported;
1182 }
1183 
GetSupportedContentTypes(uint32_t * outNumSupportedContentTypes,const uint32_t * outSupportedContentTypes)1184 HWC2::Error HwcDisplay::GetSupportedContentTypes(
1185     uint32_t *outNumSupportedContentTypes,
1186     const uint32_t *outSupportedContentTypes) {
1187   if (outSupportedContentTypes == nullptr)
1188     *outNumSupportedContentTypes = 0;
1189 
1190   return HWC2::Error::None;
1191 }
1192 
SetContentType(int32_t contentType)1193 HWC2::Error HwcDisplay::SetContentType(int32_t contentType) {
1194   /* Maps exactly to the content_type DRM connector property:
1195    * https://elixir.bootlin.com/linux/v6.11/source/include/uapi/drm/drm_mode.h#L107
1196    */
1197   if (contentType < HWC2_CONTENT_TYPE_NONE || contentType > HWC2_CONTENT_TYPE_GAME)
1198     return HWC2::Error::BadParameter;
1199 
1200   content_type_ = contentType;
1201 
1202   return HWC2::Error::None;
1203 }
1204 #endif
1205 
1206 #if __ANDROID_API__ > 28
GetDisplayIdentificationData(uint8_t * outPort,uint32_t * outDataSize,uint8_t * outData)1207 HWC2::Error HwcDisplay::GetDisplayIdentificationData(uint8_t *outPort,
1208                                                      uint32_t *outDataSize,
1209                                                      uint8_t *outData) {
1210   if (IsInHeadlessMode()) {
1211     return HWC2::Error::Unsupported;
1212   }
1213 
1214   auto blob = GetPipe().connector->Get()->GetEdidBlob();
1215   if (!blob) {
1216     return HWC2::Error::Unsupported;
1217   }
1218 
1219   *outPort = handle_; /* TDOD(nobody): What should be here? */
1220 
1221   if (outData) {
1222     *outDataSize = std::min(*outDataSize, blob->length);
1223     memcpy(outData, blob->data, *outDataSize);
1224   } else {
1225     *outDataSize = blob->length;
1226   }
1227 
1228   return HWC2::Error::None;
1229 }
1230 
GetDisplayCapabilities(uint32_t * outNumCapabilities,uint32_t * outCapabilities)1231 HWC2::Error HwcDisplay::GetDisplayCapabilities(uint32_t *outNumCapabilities,
1232                                                uint32_t *outCapabilities) {
1233   if (outNumCapabilities == nullptr) {
1234     return HWC2::Error::BadParameter;
1235   }
1236 
1237   bool skip_ctm = false;
1238 
1239   // Skip client CTM if user requested DRM_OR_IGNORE
1240   if (GetHwc()->GetResMan().GetCtmHandling() == CtmHandling::kDrmOrIgnore)
1241     skip_ctm = true;
1242 
1243   // Skip client CTM if DRM can handle it
1244   if (!skip_ctm && !IsInHeadlessMode() &&
1245       GetPipe().crtc->Get()->GetCtmProperty())
1246     skip_ctm = true;
1247 
1248   if (!skip_ctm) {
1249     *outNumCapabilities = 0;
1250     return HWC2::Error::None;
1251   }
1252 
1253   *outNumCapabilities = 1;
1254   if (outCapabilities) {
1255     outCapabilities[0] = HWC2_DISPLAY_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM;
1256   }
1257 
1258   return HWC2::Error::None;
1259 }
1260 
GetDisplayBrightnessSupport(bool * supported)1261 HWC2::Error HwcDisplay::GetDisplayBrightnessSupport(bool *supported) {
1262   *supported = false;
1263   return HWC2::Error::None;
1264 }
1265 
SetDisplayBrightness(float)1266 HWC2::Error HwcDisplay::SetDisplayBrightness(float /* brightness */) {
1267   return HWC2::Error::Unsupported;
1268 }
1269 
1270 #endif /* __ANDROID_API__ > 28 */
1271 
1272 #if __ANDROID_API__ > 27
1273 
GetRenderIntents(int32_t mode,uint32_t * outNumIntents,int32_t * outIntents)1274 HWC2::Error HwcDisplay::GetRenderIntents(
1275     int32_t mode, uint32_t *outNumIntents,
1276     int32_t * /*android_render_intent_v1_1_t*/ outIntents) {
1277   if (mode != HAL_COLOR_MODE_NATIVE) {
1278     return HWC2::Error::BadParameter;
1279   }
1280 
1281   if (outIntents == nullptr) {
1282     *outNumIntents = 1;
1283     return HWC2::Error::None;
1284   }
1285   *outNumIntents = 1;
1286   outIntents[0] = HAL_RENDER_INTENT_COLORIMETRIC;
1287   return HWC2::Error::None;
1288 }
1289 
SetColorModeWithIntent(int32_t mode,int32_t intent)1290 HWC2::Error HwcDisplay::SetColorModeWithIntent(int32_t mode, int32_t intent) {
1291   if (intent < HAL_RENDER_INTENT_COLORIMETRIC ||
1292       intent > HAL_RENDER_INTENT_TONE_MAP_ENHANCE)
1293     return HWC2::Error::BadParameter;
1294 
1295   if (intent != HAL_RENDER_INTENT_COLORIMETRIC)
1296     return HWC2::Error::Unsupported;
1297 
1298   auto err = SetColorMode(mode);
1299   if (err != HWC2::Error::None) return err;
1300 
1301   return HWC2::Error::None;
1302 }
1303 
1304 #endif /* __ANDROID_API__ > 27 */
1305 
backend() const1306 const Backend *HwcDisplay::backend() const {
1307   return backend_.get();
1308 }
1309 
set_backend(std::unique_ptr<Backend> backend)1310 void HwcDisplay::set_backend(std::unique_ptr<Backend> backend) {
1311   backend_ = std::move(backend);
1312 }
1313 
1314 }  // namespace android
1315