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