1 /*
2 * Copyright (c) 2014-2020, The Linux Foundation. All rights reserved.
3 * Not a Contribution.
4 *
5 * Copyright 2015 The Android Open Source Project
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 */
19
20 #include <cutils/properties.h>
21 #include <errno.h>
22 #include <math.h>
23 #include <sync/sync.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <utils/constants.h>
27 #include <utils/debug.h>
28 #include <utils/utils.h>
29 #include <utils/formats.h>
30 #include <utils/rect.h>
31 #include <qd_utils.h>
32
33 #include <algorithm>
34 #include <iomanip>
35 #include <map>
36 #include <sstream>
37 #include <string>
38 #include <utility>
39 #include <vector>
40
41 #include "hwc_display.h"
42 #include "hwc_debugger.h"
43 #include "hwc_tonemapper.h"
44 #include "hwc_session.h"
45
46 #ifdef QTI_BSP
47 #include <hardware/display_defs.h>
48 #endif
49
50 #define __CLASS__ "HWCDisplay"
51
52 namespace sdm {
53
54 uint32_t HWCDisplay::throttling_refresh_rate_ = 60;
55 constexpr auto vsyncPeriodTag = "VsyncPeriod";
56 constexpr uint32_t VSYNC_TIME_DRIFT_NS = 1000000;
57
IsTimeAfterOrEqualVsyncTime(int64_t time,int64_t vsync_time)58 bool IsTimeAfterOrEqualVsyncTime(int64_t time, int64_t vsync_time) {
59 return (vsync_time != INT64_MAX && ((time) - (vsync_time - VSYNC_TIME_DRIFT_NS)) >= 0);
60 }
61
NeedsToneMap(const LayerStack & layer_stack)62 bool NeedsToneMap(const LayerStack &layer_stack) {
63 for (Layer *layer : layer_stack.layers) {
64 if (layer->request.flags.tone_map) {
65 return true;
66 }
67 }
68 return false;
69 }
70
HWCColorMode(DisplayInterface * display_intf)71 HWCColorMode::HWCColorMode(DisplayInterface *display_intf) : display_intf_(display_intf) {}
72
Init()73 HWC2::Error HWCColorMode::Init() {
74 PopulateColorModes();
75 return HWC2::Error::None;
76 }
77
DeInit()78 HWC2::Error HWCColorMode::DeInit() {
79 color_mode_map_.clear();
80 return HWC2::Error::None;
81 }
82
GetColorModeCount()83 uint32_t HWCColorMode::GetColorModeCount() {
84 uint32_t count = UINT32(color_mode_map_.size());
85 DLOGI("Supported color mode count = %d", count);
86 return std::max(1U, count);
87 }
88
GetRenderIntentCount(ColorMode mode)89 uint32_t HWCColorMode::GetRenderIntentCount(ColorMode mode) {
90 uint32_t count = UINT32(color_mode_map_[mode].size());
91 DLOGI("mode: %d supported rendering intent count = %d", mode, count);
92 return std::max(1U, count);
93 }
94
GetColorModes(uint32_t * out_num_modes,ColorMode * out_modes)95 HWC2::Error HWCColorMode::GetColorModes(uint32_t *out_num_modes, ColorMode *out_modes) {
96 auto it = color_mode_map_.begin();
97 *out_num_modes = std::min(*out_num_modes, UINT32(color_mode_map_.size()));
98 for (uint32_t i = 0; i < *out_num_modes; it++, i++) {
99 out_modes[i] = it->first;
100 }
101 return HWC2::Error::None;
102 }
103
GetRenderIntents(ColorMode mode,uint32_t * out_num_intents,RenderIntent * out_intents)104 HWC2::Error HWCColorMode::GetRenderIntents(ColorMode mode, uint32_t *out_num_intents,
105 RenderIntent *out_intents) {
106 if (color_mode_map_.find(mode) == color_mode_map_.end()) {
107 return HWC2::Error::BadParameter;
108 }
109 auto it = color_mode_map_[mode].begin();
110 *out_num_intents = std::min(*out_num_intents, UINT32(color_mode_map_[mode].size()));
111 for (uint32_t i = 0; i < *out_num_intents; it++, i++) {
112 out_intents[i] = it->first;
113 }
114 return HWC2::Error::None;
115 }
116
ValidateColorModeWithRenderIntent(ColorMode mode,RenderIntent intent)117 HWC2::Error HWCColorMode::ValidateColorModeWithRenderIntent(ColorMode mode, RenderIntent intent) {
118 if (mode < ColorMode::NATIVE || mode > ColorMode::BT2100_HLG) {
119 DLOGE("Could not find mode: %d", mode);
120 return HWC2::Error::BadParameter;
121 }
122 if (color_mode_map_.find(mode) == color_mode_map_.end()) {
123 return HWC2::Error::Unsupported;
124 }
125 if (color_mode_map_[mode].find(intent) == color_mode_map_[mode].end()) {
126 return HWC2::Error::Unsupported;
127 }
128
129 return HWC2::Error::None;
130 }
131
SetColorModeWithRenderIntent(ColorMode mode,RenderIntent intent)132 HWC2::Error HWCColorMode::SetColorModeWithRenderIntent(ColorMode mode, RenderIntent intent) {
133 DTRACE_SCOPED();
134 HWC2::Error hwc_error = ValidateColorModeWithRenderIntent(mode, intent);
135 if (hwc_error != HWC2::Error::None) {
136 return hwc_error;
137 }
138
139 if (current_color_mode_ == mode && current_render_intent_ == intent) {
140 return HWC2::Error::None;
141 }
142
143 auto mode_string = color_mode_map_[mode][intent][kSdrType];
144 DisplayError error = display_intf_->SetColorMode(mode_string);
145 if (error != kErrorNone) {
146 DLOGE("failed for mode = %d intent = %d name = %s", mode, intent, mode_string.c_str());
147 return HWC2::Error::Unsupported;
148 }
149 // The mode does not have the PCC configured, restore the transform
150 RestoreColorTransform();
151
152 current_color_mode_ = mode;
153 current_render_intent_ = intent;
154 DLOGV_IF(kTagClient, "Successfully applied mode = %d intent = %d name = %s", mode, intent,
155 mode_string.c_str());
156 return HWC2::Error::None;
157 }
158
CacheColorModeWithRenderIntent(ColorMode mode,RenderIntent intent)159 HWC2::Error HWCColorMode::CacheColorModeWithRenderIntent(ColorMode mode, RenderIntent intent) {
160 HWC2::Error error = ValidateColorModeWithRenderIntent(mode, intent);
161 if (error != HWC2::Error::None) {
162 return error;
163 }
164
165 current_color_mode_ = mode;
166 current_render_intent_ = intent;
167 apply_mode_ = true;
168
169 return HWC2::Error::None;
170 }
171
ApplyCurrentColorModeWithRenderIntent(bool hdr_present)172 HWC2::Error HWCColorMode::ApplyCurrentColorModeWithRenderIntent(bool hdr_present) {
173 // If panel does not support color modes, do not set color mode.
174 if (color_mode_map_.size() <= 1) {
175 return HWC2::Error::None;
176 }
177 if (!apply_mode_) {
178 if ((hdr_present && curr_dynamic_range_ == kHdrType) ||
179 (!hdr_present && curr_dynamic_range_ == kSdrType))
180 return HWC2::Error::None;
181 }
182
183 apply_mode_ = false;
184 curr_dynamic_range_ = (hdr_present)? kHdrType : kSdrType;
185
186 // select mode according to the blend space and dynamic range
187 std::string mode_string = preferred_mode_[current_color_mode_][curr_dynamic_range_];
188 if (mode_string.empty()) {
189 mode_string = color_mode_map_[current_color_mode_][current_render_intent_][curr_dynamic_range_];
190 if (mode_string.empty() && hdr_present) {
191 // Use the colorimetric HDR mode, if an HDR mode with the current render intent is not present
192 mode_string =
193 color_mode_map_[current_color_mode_][RenderIntent::COLORIMETRIC][kHdrType];
194 }
195 if (mode_string.empty() &&
196 current_color_mode_ == ColorMode::DISPLAY_P3 &&
197 curr_dynamic_range_ == kHdrType) {
198 // fall back to display_p3 SDR mode if there is no HDR mode
199 mode_string = color_mode_map_[current_color_mode_][current_render_intent_][kSdrType];
200 }
201 }
202
203 auto error = SetPreferredColorModeInternal(mode_string, false, NULL, NULL);
204 if (error == HWC2::Error::None) {
205 // The mode does not have the PCC configured, restore the transform
206 RestoreColorTransform();
207 DLOGV_IF(kTagClient, "Successfully applied mode = %d intent = %d range = %d name = %s",
208 current_color_mode_, current_render_intent_, curr_dynamic_range_, mode_string.c_str());
209 }
210
211 return error;
212 }
213
SetColorModeById(int32_t color_mode_id)214 HWC2::Error HWCColorMode::SetColorModeById(int32_t color_mode_id) {
215 DLOGI("Applying mode: %d", color_mode_id);
216 DisplayError error = display_intf_->SetColorModeById(color_mode_id);
217 if (error != kErrorNone) {
218 DLOGI_IF(kTagClient, "Failed to apply mode: %d", color_mode_id);
219 return HWC2::Error::BadParameter;
220 }
221 return HWC2::Error::None;
222 }
223
SetPreferredColorModeInternal(const std::string & mode_string,bool from_client,ColorMode * color_mode,DynamicRangeType * dynamic_range)224 HWC2::Error HWCColorMode::SetPreferredColorModeInternal(const std::string &mode_string,
225 bool from_client, ColorMode *color_mode, DynamicRangeType *dynamic_range) {
226 DisplayError error = kErrorNone;
227 ColorMode mode = ColorMode::NATIVE;
228 DynamicRangeType range = kSdrType;
229
230 if (from_client) {
231 // get blend space and dynamic range of the mode
232 AttrVal attr;
233 std::string color_gamut_string, dynamic_range_string;
234 error = display_intf_->GetColorModeAttr(mode_string, &attr);
235 if (error) {
236 DLOGE("Failed to get mode attributes for mode %d", mode_string.c_str());
237 return HWC2::Error::BadParameter;
238 }
239
240 if (!attr.empty()) {
241 for (auto &it : attr) {
242 if (it.first.find(kColorGamutAttribute) != std::string::npos) {
243 color_gamut_string = it.second;
244 } else if (it.first.find(kDynamicRangeAttribute) != std::string::npos) {
245 dynamic_range_string = it.second;
246 }
247 }
248 }
249
250 if (color_gamut_string.empty() || dynamic_range_string.empty()) {
251 DLOGE("Invalid attributes for mode %s: color_gamut = %s, dynamic_range = %s",
252 mode_string.c_str(), color_gamut_string.c_str(), dynamic_range_string.c_str());
253 return HWC2::Error::BadParameter;
254 }
255
256 if (color_gamut_string == kDcip3) {
257 mode = ColorMode::DISPLAY_P3;
258 } else if (color_gamut_string == kSrgb) {
259 mode = ColorMode::SRGB;
260 }
261 if (dynamic_range_string == kHdr) {
262 range = kHdrType;
263 }
264
265 if (color_mode) {
266 *color_mode = mode;
267 }
268 if (dynamic_range) {
269 *dynamic_range = range;
270 }
271 }
272
273 // apply the mode from client if it matches
274 // the current blend space and dynamic range,
275 // skip the check for the mode from SF.
276 if ((!from_client) || (current_color_mode_ == mode && curr_dynamic_range_ == range)) {
277 DLOGI("Applying mode: %s", mode_string.c_str());
278 error = display_intf_->SetColorMode(mode_string);
279 if (error != kErrorNone) {
280 DLOGE("Failed to apply mode: %s", mode_string.c_str());
281 return HWC2::Error::BadParameter;
282 }
283 }
284
285 return HWC2::Error::None;
286 }
287
SetColorModeFromClientApi(std::string mode_string)288 HWC2::Error HWCColorMode::SetColorModeFromClientApi(std::string mode_string) {
289 ColorMode mode = ColorMode::NATIVE;
290 DynamicRangeType range = kSdrType;
291
292 auto error = SetPreferredColorModeInternal(mode_string, true, &mode, &range);
293 if (error == HWC2::Error::None) {
294 preferred_mode_[mode][range] = mode_string;
295 DLOGV_IF(kTagClient, "Put mode %s(mode %d, range %d) into preferred_mode",
296 mode_string.c_str(), mode, range);
297 }
298
299 return error;
300 }
301
RestoreColorTransform()302 HWC2::Error HWCColorMode::RestoreColorTransform() {
303 DisplayError error = display_intf_->SetColorTransform(kColorTransformMatrixCount, color_matrix_);
304 if (error != kErrorNone) {
305 DLOGE("Failed to set Color Transform");
306 return HWC2::Error::BadParameter;
307 }
308
309 return HWC2::Error::None;
310 }
311
SetColorTransform(const float * matrix,android_color_transform_t)312 HWC2::Error HWCColorMode::SetColorTransform(const float *matrix,
313 android_color_transform_t /*hint*/) {
314 DTRACE_SCOPED();
315 auto status = HWC2::Error::None;
316 double color_matrix[kColorTransformMatrixCount] = {0};
317 CopyColorTransformMatrix(matrix, color_matrix);
318
319 DisplayError error = display_intf_->SetColorTransform(kColorTransformMatrixCount, color_matrix);
320 if (error != kErrorNone) {
321 DLOGE("Failed to set Color Transform Matrix");
322 status = HWC2::Error::Unsupported;
323 }
324 CopyColorTransformMatrix(matrix, color_matrix_);
325 return status;
326 }
327
PopulateColorModes()328 void HWCColorMode::PopulateColorModes() {
329 uint32_t color_mode_count = 0;
330 // SDM returns modes which have attributes defining mode and rendering intent
331 DisplayError error = display_intf_->GetColorModeCount(&color_mode_count);
332 if (error != kErrorNone || (color_mode_count == 0)) {
333 DLOGW("GetColorModeCount failed, use native color mode");
334 color_mode_map_[ColorMode::NATIVE][RenderIntent::COLORIMETRIC]
335 [kSdrType] = "hal_native_identity";
336 return;
337 }
338
339 DLOGV_IF(kTagClient, "Color Modes supported count = %d", color_mode_count);
340
341 std::vector<std::string> color_modes(color_mode_count);
342 error = display_intf_->GetColorModes(&color_mode_count, &color_modes);
343 for (uint32_t i = 0; i < color_mode_count; i++) {
344 std::string &mode_string = color_modes.at(i);
345 DLOGV_IF(kTagClient, "Color Mode[%d] = %s", i, mode_string.c_str());
346 AttrVal attr;
347 error = display_intf_->GetColorModeAttr(mode_string, &attr);
348 std::string color_gamut = kNative, dynamic_range = kSdr, pic_quality = kStandard, transfer;
349 if (!attr.empty()) {
350 for (auto &it : attr) {
351 if (it.first.find(kColorGamutAttribute) != std::string::npos) {
352 color_gamut = it.second;
353 } else if (it.first.find(kDynamicRangeAttribute) != std::string::npos) {
354 dynamic_range = it.second;
355 } else if (it.first.find(kPictureQualityAttribute) != std::string::npos) {
356 pic_quality = it.second;
357 } else if (it.first.find(kGammaTransferAttribute) != std::string::npos) {
358 transfer = it.second;
359 }
360 }
361
362 DLOGV_IF(kTagClient, "color_gamut : %s, dynamic_range : %s, pic_quality : %s",
363 color_gamut.c_str(), dynamic_range.c_str(), pic_quality.c_str());
364 if (color_gamut == kNative) {
365 color_mode_map_[ColorMode::NATIVE][RenderIntent::COLORIMETRIC][kSdrType] = mode_string;
366 }
367
368 if (color_gamut == kSrgb && dynamic_range == kSdr) {
369 if (pic_quality == kStandard) {
370 color_mode_map_[ColorMode::SRGB][RenderIntent::COLORIMETRIC][kSdrType] = mode_string;
371 }
372 if (pic_quality == kEnhanced) {
373 color_mode_map_[ColorMode::SRGB][RenderIntent::ENHANCE][kSdrType] = mode_string;
374 }
375 }
376
377 if (color_gamut == kDcip3 && dynamic_range == kSdr) {
378 if (pic_quality == kStandard) {
379 color_mode_map_[ColorMode::DISPLAY_P3][RenderIntent::COLORIMETRIC]
380 [kSdrType] = mode_string;
381 }
382 if (pic_quality == kEnhanced) {
383 color_mode_map_[ColorMode::DISPLAY_P3][RenderIntent::ENHANCE]
384 [kSdrType] = mode_string;
385 }
386 }
387 if (color_gamut == kDcip3 && pic_quality == kStandard && dynamic_range == kHdr) {
388 if (display_intf_->IsSupportSsppTonemap()) {
389 color_mode_map_[ColorMode::DISPLAY_P3][RenderIntent::COLORIMETRIC]
390 [kHdrType] = mode_string;
391 } else {
392 color_mode_map_[ColorMode::BT2100_PQ][RenderIntent::TONE_MAP_COLORIMETRIC]
393 [kHdrType] = mode_string;
394 color_mode_map_[ColorMode::BT2100_HLG][RenderIntent::TONE_MAP_COLORIMETRIC]
395 [kHdrType] = mode_string;
396 }
397 } else if (color_gamut == kBt2020) {
398 if (transfer == kSt2084) {
399 color_mode_map_[ColorMode::BT2100_PQ][RenderIntent::COLORIMETRIC]
400 [kHdrType] = mode_string;
401 } else if (transfer == kHlg) {
402 color_mode_map_[ColorMode::BT2100_HLG][RenderIntent::COLORIMETRIC]
403 [kHdrType] = mode_string;
404 } else if (transfer == kGamma2_2) {
405 color_mode_map_[ColorMode::BT2020][RenderIntent::COLORIMETRIC]
406 [kHdrType] = mode_string;
407 }
408 }
409 } else {
410 // Look at the mode names, if no attributes are found
411 if (mode_string.find("hal_native") != std::string::npos) {
412 color_mode_map_[ColorMode::NATIVE][RenderIntent::COLORIMETRIC]
413 [kSdrType] = mode_string;
414 }
415 }
416 }
417 }
418
Dump(std::ostringstream * os)419 void HWCColorMode::Dump(std::ostringstream* os) {
420 *os << "color modes supported: \n";
421 for (auto it : color_mode_map_) {
422 *os << "mode: " << static_cast<int32_t>(it.first) << " RIs { ";
423 for (auto render_intent_it : color_mode_map_[it.first]) {
424 *os << static_cast<int32_t>(render_intent_it.first) << " dynamic_range [ ";
425 for (auto range_it : color_mode_map_[it.first][render_intent_it.first]) {
426 *os << static_cast<int32_t>(range_it.first) << " ";
427 }
428 *os << "] ";
429 }
430 *os << "} \n";
431 }
432 *os << "current mode: " << static_cast<uint32_t>(current_color_mode_) << std::endl;
433 *os << "current render_intent: " << static_cast<uint32_t>(current_render_intent_) << std::endl;
434 if (curr_dynamic_range_ == kHdrType) {
435 *os << "current dynamic_range: HDR" << std::endl;
436 } else {
437 *os << "current dynamic_range: SDR" << std::endl;
438 }
439 *os << "current transform: ";
440 for (uint32_t i = 0; i < kColorTransformMatrixCount; i++) {
441 if (i % 4 == 0) {
442 *os << std::endl;
443 }
444 *os << std::fixed << std::setprecision(2) << std::setw(6) << std::setfill(' ')
445 << color_matrix_[i] << " ";
446 }
447 *os << std::endl;
448 }
449
HWCDisplay(CoreInterface * core_intf,BufferAllocator * buffer_allocator,HWCCallbacks * callbacks,HWCDisplayEventHandler * event_handler,qService::QService * qservice,DisplayType type,hwc2_display_t id,int32_t sdm_id,bool needs_blit,DisplayClass display_class)450 HWCDisplay::HWCDisplay(CoreInterface *core_intf, BufferAllocator *buffer_allocator,
451 HWCCallbacks *callbacks, HWCDisplayEventHandler* event_handler,
452 qService::QService *qservice, DisplayType type, hwc2_display_t id,
453 int32_t sdm_id, bool needs_blit, DisplayClass display_class)
454 : core_intf_(core_intf),
455 callbacks_(callbacks),
456 event_handler_(event_handler),
457 type_(type),
458 id_(id),
459 sdm_id_(sdm_id),
460 needs_blit_(needs_blit),
461 qservice_(qservice),
462 display_class_(display_class) {
463 buffer_allocator_ = static_cast<HWCBufferAllocator *>(buffer_allocator);
464 }
465
Init()466 int HWCDisplay::Init() {
467 DisplayError error = kErrorNone;
468
469 HWCDebugHandler::Get()->GetProperty(ENABLE_NULL_DISPLAY_PROP, &null_display_mode_);
470 HWCDebugHandler::Get()->GetProperty(ENABLE_ASYNC_POWERMODE, &async_power_mode_);
471
472 if (null_display_mode_) {
473 DisplayNull *disp_null = new DisplayNull();
474 disp_null->Init();
475 use_metadata_refresh_rate_ = false;
476 display_intf_ = disp_null;
477 DLOGI("Enabling null display mode for display type %d", type_);
478 } else {
479 error = core_intf_->CreateDisplay(sdm_id_, this, &display_intf_);
480 if (error != kErrorNone) {
481 if (kErrorDeviceRemoved == error) {
482 DLOGW("Display creation cancelled. Display %d-%d removed.", sdm_id_, type_);
483 return -ENODEV;
484 } else {
485 DLOGE("Display create failed. Error = %d display_id = %d event_handler = %p disp_intf = %p",
486 error, sdm_id_, this, &display_intf_);
487 return -EINVAL;
488 }
489 }
490 }
491
492 validated_ = false;
493 HWCDebugHandler::Get()->GetProperty(DISABLE_HDR, &disable_hdr_handling_);
494 if (disable_hdr_handling_) {
495 DLOGI("HDR Handling disabled");
496 }
497
498 int property_swap_interval = 1;
499 HWCDebugHandler::Get()->GetProperty(ZERO_SWAP_INTERVAL, &property_swap_interval);
500 if (property_swap_interval == 0) {
501 swap_interval_zero_ = true;
502 }
503
504 client_target_ = new HWCLayer(id_, buffer_allocator_);
505
506 int blit_enabled = 0;
507 HWCDebugHandler::Get()->GetProperty(DISABLE_BLIT_COMPOSITION_PROP, &blit_enabled);
508 if (needs_blit_ && blit_enabled) {
509 // TODO(user): Add blit engine when needed
510 }
511
512 error = display_intf_->GetNumVariableInfoConfigs(&num_configs_);
513 if (error != kErrorNone) {
514 DLOGE("Getting config count failed. Error = %d", error);
515 return -EINVAL;
516 }
517
518 UpdateConfigs();
519
520 tone_mapper_ = new HWCToneMapper(buffer_allocator_);
521
522 display_intf_->GetRefreshRateRange(&min_refresh_rate_, &max_refresh_rate_);
523 current_refresh_rate_ = max_refresh_rate_;
524
525 GetUnderScanConfig();
526
527 DisplayConfigFixedInfo fixed_info = {};
528 display_intf_->GetConfig(&fixed_info);
529 is_cmd_mode_ = fixed_info.is_cmdmode;
530 partial_update_enabled_ = fixed_info.partial_update || (!fixed_info.is_cmdmode);
531 client_target_->SetPartialUpdate(partial_update_enabled_);
532
533 int disable_fast_path = 0;
534 HWCDebugHandler::Get()->GetProperty(DISABLE_FAST_PATH, &disable_fast_path);
535 fast_path_enabled_ = !(disable_fast_path == 1);
536
537 DLOGI("Display created with id: %d", id_);
538
539 return 0;
540 }
541
UpdateConfigs()542 void HWCDisplay::UpdateConfigs() {
543 // SF doesnt care about dynamic bit clk support.
544 // Exposing all configs will result in getting/setting of redundant configs.
545
546 // For each config store the corresponding index which client understands.
547 hwc_config_map_.resize(num_configs_);
548
549 for (uint32_t i = 0; i < num_configs_; i++) {
550 DisplayConfigVariableInfo info = {};
551 GetDisplayAttributesForConfig(INT(i), &info);
552 bool config_exists = false;
553 for (auto &config : variable_config_map_) {
554 if (config.second == info) {
555 config_exists = true;
556 hwc_config_map_.at(i) = config.first;
557 break;
558 }
559 }
560
561 if (!config_exists) {
562 variable_config_map_[i] = info;
563 hwc_config_map_.at(i) = i;
564 }
565 }
566
567 // Update num config count.
568 num_configs_ = UINT32(variable_config_map_.size());
569 DLOGI("num_configs = %d", num_configs_);
570 }
571
Deinit()572 int HWCDisplay::Deinit() {
573 if (null_display_mode_) {
574 delete static_cast<DisplayNull *>(display_intf_);
575 display_intf_ = nullptr;
576 } else {
577 DisplayError error = core_intf_->DestroyDisplay(display_intf_);
578 if (error != kErrorNone) {
579 DLOGE("Display destroy failed. Error = %d", error);
580 return -EINVAL;
581 }
582 }
583
584 delete client_target_;
585 for (auto hwc_layer : layer_set_) {
586 delete hwc_layer;
587 }
588
589 // Close fbt release fence.
590 close(fbt_release_fence_);
591
592 if (color_mode_) {
593 color_mode_->DeInit();
594 delete color_mode_;
595 }
596
597 if (tone_mapper_) {
598 delete tone_mapper_;
599 tone_mapper_ = nullptr;
600 }
601
602 return 0;
603 }
604
605 // LayerStack operations
CreateLayer(hwc2_layer_t * out_layer_id)606 HWC2::Error HWCDisplay::CreateLayer(hwc2_layer_t *out_layer_id) {
607 HWCLayer *layer = *layer_set_.emplace(new HWCLayer(id_, buffer_allocator_));
608 layer_map_.emplace(std::make_pair(layer->GetId(), layer));
609 *out_layer_id = layer->GetId();
610 geometry_changes_ |= GeometryChanges::kAdded;
611 validated_ = false;
612 layer_stack_invalid_ = true;
613 layer->SetPartialUpdate(partial_update_enabled_);
614
615 return HWC2::Error::None;
616 }
617
GetHWCLayer(hwc2_layer_t layer_id)618 HWCLayer *HWCDisplay::GetHWCLayer(hwc2_layer_t layer_id) {
619 const auto map_layer = layer_map_.find(layer_id);
620 if (map_layer == layer_map_.end()) {
621 DLOGW("[%" PRIu64 "] GetLayer(%" PRIu64 ") failed: no such layer", id_, layer_id);
622 return nullptr;
623 } else {
624 return map_layer->second;
625 }
626 }
627
DestroyLayer(hwc2_layer_t layer_id)628 HWC2::Error HWCDisplay::DestroyLayer(hwc2_layer_t layer_id) {
629 const auto map_layer = layer_map_.find(layer_id);
630 if (map_layer == layer_map_.end()) {
631 DLOGW("[%" PRIu64 "] destroyLayer(%" PRIu64 ") failed: no such layer", id_, layer_id);
632 return HWC2::Error::BadLayer;
633 }
634 const auto layer = map_layer->second;
635 layer_map_.erase(map_layer);
636 const auto z_range = layer_set_.equal_range(layer);
637 for (auto current = z_range.first; current != z_range.second; ++current) {
638 if (*current == layer) {
639 current = layer_set_.erase(current);
640 delete layer;
641 break;
642 }
643 }
644
645 geometry_changes_ |= GeometryChanges::kRemoved;
646 validated_ = false;
647 layer_stack_invalid_ = true;
648
649 return HWC2::Error::None;
650 }
651
652
BuildLayerStack()653 void HWCDisplay::BuildLayerStack() {
654 layer_stack_ = LayerStack();
655 display_rect_ = LayerRect();
656 metadata_refresh_rate_ = 0;
657 layer_stack_.flags.animating = animating_;
658 hdr_largest_layer_px_ = 0.0f;
659 layer_stack_.flags.fast_path = fast_path_enabled_ && fast_path_composition_;
660
661 DTRACE_SCOPED();
662 // Add one layer for fb target
663 // TODO(user): Add blit target layers
664 for (auto hwc_layer : layer_set_) {
665 // Reset layer data which SDM may change
666 hwc_layer->ResetPerFrameData();
667
668 Layer *layer = hwc_layer->GetSDMLayer();
669 layer->flags = {}; // Reset earlier flags
670 // Mark all layers to skip, when client target handle is NULL
671 if (hwc_layer->GetClientRequestedCompositionType() == HWC2::Composition::Client ||
672 !client_target_->GetSDMLayer()->input_buffer.buffer_id) {
673 layer->flags.skip = true;
674 } else if (hwc_layer->GetClientRequestedCompositionType() == HWC2::Composition::SolidColor) {
675 layer->flags.solid_fill = true;
676 }
677
678 if (!hwc_layer->IsDataSpaceSupported()) {
679 layer->flags.skip = true;
680 }
681
682 if (hwc_layer->IsColorTransformSet()) {
683 layer->flags.skip = true;
684 }
685
686 // set default composition as GPU for SDM
687 layer->composition = kCompositionGPU;
688
689 if (swap_interval_zero_) {
690 if (layer->input_buffer.acquire_fence_fd >= 0) {
691 close(layer->input_buffer.acquire_fence_fd);
692 layer->input_buffer.acquire_fence_fd = -1;
693 }
694 }
695
696 bool is_secure = false;
697 bool is_video = false;
698 const private_handle_t *handle =
699 reinterpret_cast<const private_handle_t *>(layer->input_buffer.buffer_id);
700 if (handle) {
701 if (handle->buffer_type == BUFFER_TYPE_VIDEO) {
702 layer_stack_.flags.video_present = true;
703 is_video = true;
704 }
705 // TZ Protected Buffer - L1
706 // Gralloc Usage Protected Buffer - L3 - which needs to be treated as Secure & avoid fallback
707 if (handle->flags & private_handle_t::PRIV_FLAGS_PROTECTED_BUFFER ||
708 handle->flags & private_handle_t::PRIV_FLAGS_SECURE_BUFFER) {
709 layer_stack_.flags.secure_present = true;
710 is_secure = true;
711 }
712 }
713
714 if (layer->input_buffer.flags.secure_display) {
715 is_secure = true;
716 }
717
718 if (hwc_layer->IsSingleBuffered() &&
719 !(hwc_layer->IsRotationPresent() || hwc_layer->IsScalingPresent())) {
720 layer->flags.single_buffer = true;
721 layer_stack_.flags.single_buffered_layer_present = true;
722 }
723
724 bool hdr_layer = layer->input_buffer.color_metadata.colorPrimaries == ColorPrimaries_BT2020 &&
725 (layer->input_buffer.color_metadata.transfer == Transfer_SMPTE_ST2084 ||
726 layer->input_buffer.color_metadata.transfer == Transfer_HLG);
727 if (hdr_layer && !disable_hdr_handling_) {
728 // Dont honor HDR when its handling is disabled
729 layer->input_buffer.flags.hdr = true;
730 layer_stack_.flags.hdr_present = true;
731
732 // HDR area
733 auto hdr_layer_area = (layer->dst_rect.right - layer->dst_rect.left) *
734 (layer->dst_rect.bottom - layer->dst_rect.top);
735 hdr_largest_layer_px_ = std::max(hdr_largest_layer_px_, hdr_layer_area);
736 }
737
738 if (hwc_layer->IsNonIntegralSourceCrop() && !is_secure && !hdr_layer &&
739 !layer->flags.single_buffer && !layer->flags.solid_fill && !is_video) {
740 layer->flags.skip = true;
741 }
742
743 if (!layer->flags.skip &&
744 (hwc_layer->GetClientRequestedCompositionType() == HWC2::Composition::Cursor)) {
745 // Currently we support only one HWCursor & only at top most z-order
746 if ((*layer_set_.rbegin())->GetId() == hwc_layer->GetId()) {
747 layer->flags.cursor = true;
748 layer_stack_.flags.cursor_present = true;
749 }
750 }
751
752 if (layer->flags.skip) {
753 layer_stack_.flags.skip_present = true;
754 }
755
756 // TODO(user): Move to a getter if this is needed at other places
757 hwc_rect_t scaled_display_frame = {INT(layer->dst_rect.left), INT(layer->dst_rect.top),
758 INT(layer->dst_rect.right), INT(layer->dst_rect.bottom)};
759 if (hwc_layer->GetGeometryChanges() & kDisplayFrame) {
760 ApplyScanAdjustment(&scaled_display_frame);
761 }
762 hwc_layer->SetLayerDisplayFrame(scaled_display_frame);
763 hwc_layer->ResetPerFrameData();
764 // SDM requires these details even for solid fill
765 if (layer->flags.solid_fill) {
766 LayerBuffer *layer_buffer = &layer->input_buffer;
767 layer_buffer->width = UINT32(layer->dst_rect.right - layer->dst_rect.left);
768 layer_buffer->height = UINT32(layer->dst_rect.bottom - layer->dst_rect.top);
769 layer_buffer->unaligned_width = layer_buffer->width;
770 layer_buffer->unaligned_height = layer_buffer->height;
771 layer_buffer->acquire_fence_fd = -1;
772 layer_buffer->release_fence_fd = -1;
773 layer->src_rect.left = 0;
774 layer->src_rect.top = 0;
775 layer->src_rect.right = FLOAT(layer_buffer->width);
776 layer->src_rect.bottom = FLOAT(layer_buffer->height);
777 }
778
779 if (hwc_layer->HasMetaDataRefreshRate() && layer->frame_rate > metadata_refresh_rate_) {
780 metadata_refresh_rate_ = SanitizeRefreshRate(layer->frame_rate);
781 }
782
783 display_rect_ = Union(display_rect_, layer->dst_rect);
784 geometry_changes_ |= hwc_layer->GetGeometryChanges();
785
786 layer->flags.updating = true;
787 if (layer_set_.size() <= kMaxLayerCount) {
788 layer->flags.updating = IsLayerUpdating(hwc_layer);
789 }
790
791 if ((hwc_layer->GetDeviceSelectedCompositionType() != HWC2::Composition::Device) ||
792 (hwc_layer->GetClientRequestedCompositionType() != HWC2::Composition::Device) ||
793 layer->flags.skip) {
794 layer->update_mask.set(kClientCompRequest);
795 }
796
797 layer_stack_.flags.mask_present |= layer->input_buffer.flags.mask_layer;
798
799 layer_stack_.layers.push_back(layer);
800 }
801
802 // If layer stack needs Client composition, HWC display gets into InternalValidate state. If
803 // validation gets reset by any other thread in this state, enforce Geometry change to ensure
804 // that Client target gets composed by SF.
805 bool enforce_geometry_change = (validate_state_ == kInternalValidate) && !validated_;
806
807 // TODO(user): Set correctly when SDM supports geometry_changes as bitmask
808 layer_stack_.flags.geometry_changed = UINT32((geometry_changes_ ||
809 geometry_changes_on_doze_suspend_) > 0) || enforce_geometry_change;
810 layer_stack_.flags.config_changed = !validated_;
811
812 // Append client target to the layer stack
813 Layer *sdm_client_target = client_target_->GetSDMLayer();
814 sdm_client_target->flags.updating = IsLayerUpdating(client_target_);
815 // Derive client target dataspace based on the color mode - bug/115482728
816 int32_t client_target_dataspace = GetDataspaceFromColorMode(GetCurrentColorMode());
817 SetClientTargetDataSpace(client_target_dataspace);
818 layer_stack_.layers.push_back(sdm_client_target);
819
820 // fall back frame composition to GPU when client target is 10bit
821 // TODO(user): clarify the behaviour from Client(SF) and SDM Extn -
822 // when handling 10bit FBT, as it would affect blending
823 if (Is10BitFormat(sdm_client_target->input_buffer.format)) {
824 // Must fall back to client composition
825 MarkLayersForClientComposition();
826 }
827 }
828
BuildSolidFillStack()829 void HWCDisplay::BuildSolidFillStack() {
830 layer_stack_ = LayerStack();
831 display_rect_ = LayerRect();
832
833 layer_stack_.layers.push_back(solid_fill_layer_);
834 layer_stack_.flags.geometry_changed = 1U;
835 // Append client target to the layer stack
836 layer_stack_.layers.push_back(client_target_->GetSDMLayer());
837 }
838
SetLayerZOrder(hwc2_layer_t layer_id,uint32_t z)839 HWC2::Error HWCDisplay::SetLayerZOrder(hwc2_layer_t layer_id, uint32_t z) {
840 const auto map_layer = layer_map_.find(layer_id);
841 if (map_layer == layer_map_.end()) {
842 DLOGE("[%" PRIu64 "] updateLayerZ failed to find layer", id_);
843 return HWC2::Error::BadLayer;
844 }
845
846 const auto layer = map_layer->second;
847 const auto z_range = layer_set_.equal_range(layer);
848 bool layer_on_display = false;
849 for (auto current = z_range.first; current != z_range.second; ++current) {
850 if (*current == layer) {
851 if ((*current)->GetZ() == z) {
852 // Don't change anything if the Z hasn't changed
853 return HWC2::Error::None;
854 }
855 current = layer_set_.erase(current);
856 layer_on_display = true;
857 break;
858 }
859 }
860
861 if (!layer_on_display) {
862 DLOGE("[%" PRIu64 "] updateLayerZ failed to find layer on display", id_);
863 return HWC2::Error::BadLayer;
864 }
865
866 layer->SetLayerZOrder(z);
867 layer_set_.emplace(layer);
868 return HWC2::Error::None;
869 }
870
SetVsyncEnabled(HWC2::Vsync enabled)871 HWC2::Error HWCDisplay::SetVsyncEnabled(HWC2::Vsync enabled) {
872 DLOGV("Display ID: %d enabled: %s", id_, to_string(enabled).c_str());
873 ATRACE_INT("SetVsyncState ", enabled == HWC2::Vsync::Enable ? 1 : 0);
874 DisplayError error = kErrorNone;
875
876 if (shutdown_pending_ ||
877 (!callbacks_->VsyncCallbackRegistered() && !callbacks_->Vsync_2_4CallbackRegistered())) {
878 return HWC2::Error::None;
879 }
880
881 bool state;
882 if (enabled == HWC2::Vsync::Enable)
883 state = true;
884 else if (enabled == HWC2::Vsync::Disable)
885 state = false;
886 else
887 return HWC2::Error::BadParameter;
888
889 error = display_intf_->SetVSyncState(state);
890
891 if (error != kErrorNone) {
892 if (error == kErrorShutDown) {
893 shutdown_pending_ = true;
894 return HWC2::Error::None;
895 }
896 DLOGE("Failed. enabled = %s, error = %d", to_string(enabled).c_str(), error);
897 return HWC2::Error::BadDisplay;
898 }
899
900 if (callbacks_->Vsync_2_4CallbackRegistered()) {
901 ATRACE_INT(vsyncPeriodTag, 0);
902 }
903
904 return HWC2::Error::None;
905 }
906
PostPowerMode()907 void HWCDisplay::PostPowerMode() {
908 if (release_fence_ < 0) {
909 return;
910 }
911
912 for (auto hwc_layer : layer_set_) {
913 auto fence = hwc_layer->PopBackReleaseFence();
914 auto merged_fence = -1;
915 if (fence >= 0) {
916 merged_fence = sync_merge("sync_merge", release_fence_, fence);
917 ::close(fence);
918 } else {
919 merged_fence = ::dup(release_fence_);
920 }
921 hwc_layer->PushBackReleaseFence(merged_fence);
922 }
923
924 // Add this release fence onto fbt_release fence.
925 CloseFd(&fbt_release_fence_);
926 fbt_release_fence_ = release_fence_;
927 release_fence_ = -1;
928 }
929
SetPowerMode(HWC2::PowerMode mode,bool teardown)930 HWC2::Error HWCDisplay::SetPowerMode(HWC2::PowerMode mode, bool teardown) {
931 DLOGV("display = %d, mode = %s", id_, to_string(mode).c_str());
932 DisplayState state = kStateOff;
933 bool flush_on_error = flush_on_error_;
934
935 if (shutdown_pending_) {
936 return HWC2::Error::None;
937 }
938
939 switch (mode) {
940 case HWC2::PowerMode::Off:
941 // During power off, all of the buffers are released.
942 // Do not flush until a buffer is successfully submitted again.
943 flush_on_error = false;
944 state = kStateOff;
945 if (tone_mapper_) {
946 tone_mapper_->Terminate();
947 }
948 break;
949 case HWC2::PowerMode::On:
950 state = kStateOn;
951 break;
952 case HWC2::PowerMode::Doze:
953 state = kStateDoze;
954 break;
955 case HWC2::PowerMode::DozeSuspend:
956 state = kStateDozeSuspend;
957 break;
958 default:
959 return HWC2::Error::BadParameter;
960 }
961 int release_fence = -1;
962
963 ATRACE_INT("SetPowerMode ", state);
964 DisplayError error = display_intf_->SetDisplayState(state, teardown, &release_fence);
965 validated_ = false;
966
967 if (error == kErrorNone) {
968 flush_on_error_ = flush_on_error;
969 } else {
970 if (error == kErrorShutDown) {
971 shutdown_pending_ = true;
972 return HWC2::Error::None;
973 }
974 DLOGE("Set state failed. Error = %d", error);
975 return HWC2::Error::BadParameter;
976 }
977
978 // Update release fence.
979 release_fence_ = release_fence;
980 current_power_mode_ = mode;
981
982 // Close the release fences in synchronous power updates
983 if (!async_power_mode_) {
984 PostPowerMode();
985 }
986 return HWC2::Error::None;
987 }
988
GetClientTargetSupport(uint32_t width,uint32_t height,int32_t format,int32_t dataspace)989 HWC2::Error HWCDisplay::GetClientTargetSupport(uint32_t width, uint32_t height, int32_t format,
990 int32_t dataspace) {
991 ColorMetaData color_metadata = {};
992 if (dataspace != HAL_DATASPACE_UNKNOWN) {
993 dataspace = TranslateFromLegacyDataspace(dataspace);
994 GetColorPrimary(dataspace, &(color_metadata.colorPrimaries));
995 GetTransfer(dataspace, &(color_metadata.transfer));
996 GetRange(dataspace, &(color_metadata.range));
997 }
998
999 LayerBufferFormat sdm_format = HWCLayer::GetSDMFormat(format, 0);
1000 if (display_intf_->GetClientTargetSupport(width, height, sdm_format,
1001 color_metadata) != kErrorNone) {
1002 return HWC2::Error::Unsupported;
1003 }
1004
1005 return HWC2::Error::None;
1006 }
1007
GetColorModes(uint32_t * out_num_modes,ColorMode * out_modes)1008 HWC2::Error HWCDisplay::GetColorModes(uint32_t *out_num_modes, ColorMode *out_modes) {
1009 if (out_modes == nullptr) {
1010 *out_num_modes = 1;
1011 } else if (out_modes && *out_num_modes > 0) {
1012 *out_num_modes = 1;
1013 out_modes[0] = ColorMode::NATIVE;
1014 }
1015 return HWC2::Error::None;
1016 }
1017
GetRenderIntents(ColorMode mode,uint32_t * out_num_intents,RenderIntent * out_intents)1018 HWC2::Error HWCDisplay::GetRenderIntents(ColorMode mode, uint32_t *out_num_intents,
1019 RenderIntent *out_intents) {
1020 if (mode != ColorMode::NATIVE) {
1021 return HWC2::Error::Unsupported;
1022 }
1023 if (out_intents == nullptr) {
1024 *out_num_intents = 1;
1025 } else if (out_intents && *out_num_intents > 0) {
1026 *out_num_intents = 1;
1027 out_intents[0] = RenderIntent::COLORIMETRIC;
1028 }
1029 return HWC2::Error::None;
1030 }
1031
GetDisplayConfigs(uint32_t * out_num_configs,hwc2_config_t * out_configs)1032 HWC2::Error HWCDisplay::GetDisplayConfigs(uint32_t *out_num_configs, hwc2_config_t *out_configs) {
1033 if (out_num_configs == nullptr) {
1034 return HWC2::Error::BadParameter;
1035 }
1036
1037 if (out_configs == nullptr) {
1038 *out_num_configs = num_configs_;
1039 return HWC2::Error::None;
1040 }
1041
1042 *out_num_configs = std::min(*out_num_configs, num_configs_);
1043
1044 // Expose all unique config ids to client.
1045 uint32_t i = 0;
1046 for (auto &info : variable_config_map_) {
1047 if (i == *out_num_configs) {
1048 break;
1049 }
1050 out_configs[i++] = info.first;
1051 }
1052
1053 return HWC2::Error::None;
1054 }
1055
GetDisplayVsyncPeriod(hwc2_vsync_period_t * out_vsync_period)1056 HWC2::Error HWCDisplay::GetDisplayVsyncPeriod(hwc2_vsync_period_t *out_vsync_period) {
1057 if (out_vsync_period == nullptr) {
1058 return HWC2::Error::BadParameter;
1059 }
1060
1061 return GetCurrentVsyncPeriod(out_vsync_period);
1062 }
1063
SetActiveConfigWithConstraints(hwc2_config_t config,hwc_vsync_period_change_constraints_t * vsync_period_change_constraints,hwc_vsync_period_change_timeline_t * out_timeline)1064 HWC2::Error HWCDisplay::SetActiveConfigWithConstraints(
1065 hwc2_config_t config, hwc_vsync_period_change_constraints_t *vsync_period_change_constraints,
1066 hwc_vsync_period_change_timeline_t *out_timeline) {
1067 DTRACE_SCOPED();
1068 if (vsync_period_change_constraints == nullptr || out_timeline == nullptr) {
1069 return HWC2::Error::BadParameter;
1070 }
1071
1072 if (variable_config_map_.find(config) == variable_config_map_.end()) {
1073 DLOGW("Invalid config");
1074 return HWC2::Error::BadConfig;
1075 }
1076
1077 if (vsync_period_change_constraints->seamlessRequired) {
1078 if (!AllowSeamless(config)) {
1079 DLOGW("Not allowed change to config %u seamlessly", config);
1080 return HWC2::Error::SeamlessNotAllowed;
1081 }
1082 }
1083
1084 hwc2_vsync_period_t current_vsync_period;
1085 if (GetCurrentVsyncPeriod(¤t_vsync_period) != HWC2::Error::None) {
1086 return HWC2::Error::BadConfig;
1087 }
1088
1089 std::tie(out_timeline->refreshTimeNanos, out_timeline->newVsyncAppliedTimeNanos) =
1090 RequestActiveConfigChange(config, current_vsync_period,
1091 vsync_period_change_constraints->desiredTimeNanos);
1092 out_timeline->refreshRequired = true;
1093
1094 return HWC2::Error::None;
1095 }
1096
ProcessActiveConfigChange(void)1097 void HWCDisplay::ProcessActiveConfigChange(void) {
1098 if (IsActiveConfigReadyToSubmit(systemTime(SYSTEM_TIME_MONOTONIC))) {
1099 DTRACE_SCOPED();
1100 hwc2_vsync_period_t vsync_period;
1101 if (GetCurrentVsyncPeriodByConfig(&vsync_period) != HWC2::Error::None) {
1102 return;
1103 }
1104 SubmitActiveConfigChange(vsync_period);
1105 }
1106 }
1107
GetCurrentVsyncPeriod(hwc2_vsync_period_t * period)1108 HWC2::Error HWCDisplay::GetCurrentVsyncPeriod(hwc2_vsync_period_t *period) {
1109 if (GetTransientVsyncPeriod(period)) {
1110 return HWC2::Error::None;
1111 }
1112
1113 return GetCurrentVsyncPeriodByConfig(period);
1114 }
1115
GetCurrentVsyncPeriodByConfig(hwc2_vsync_period_t * period)1116 HWC2::Error HWCDisplay::GetCurrentVsyncPeriodByConfig(hwc2_vsync_period_t *period) {
1117 hwc2_config_t current_config;
1118 if (auto error = GetActiveConfig(¤t_config); error != HWC2::Error::None) {
1119 DLOGE("Failed to get active config");
1120 return error;
1121 }
1122
1123 int32_t vsync_period;
1124 if (auto error = GetDisplayAttribute(current_config, HWC2::Attribute::VsyncPeriod, &vsync_period);
1125 error != HWC2::Error::None) {
1126 DLOGE("Failed to get VsyncPeriod from config %d", current_config);
1127 return error;
1128 }
1129 *period = static_cast<hwc2_vsync_period_t>(vsync_period);
1130
1131 return HWC2::Error::None;
1132 }
1133
GetTransientVsyncPeriod(hwc2_vsync_period_t * period)1134 bool HWCDisplay::GetTransientVsyncPeriod(hwc2_vsync_period_t *period) {
1135 std::lock_guard<std::mutex> lock(transient_refresh_rate_lock_);
1136 auto now = systemTime(SYSTEM_TIME_MONOTONIC);
1137 while (!transient_refresh_rate_info_.empty()) {
1138 if (IsActiveConfigApplied(now, transient_refresh_rate_info_.front().vsync_applied_time)) {
1139 transient_refresh_rate_info_.pop_front();
1140 } else {
1141 *period = transient_refresh_rate_info_.front().transient_vsync_period;
1142 return true;
1143 }
1144 }
1145
1146 return false;
1147 }
1148
EstimateVsyncPeriodChangeTimeline(uint32_t current_vsync_period,int64_t desired_time)1149 std::tuple<int64_t, int64_t> HWCDisplay::EstimateVsyncPeriodChangeTimeline(
1150 uint32_t current_vsync_period, int64_t desired_time) {
1151 const auto now = systemTime(SYSTEM_TIME_MONOTONIC);
1152 const auto delta = desired_time - now;
1153 const auto refresh_rate_activate_period = current_vsync_period * vsyncs_to_apply_rate_change_;
1154
1155 nsecs_t refresh_time;
1156 if (delta < 0) {
1157 refresh_time = now + (delta % current_vsync_period);
1158 } else if (delta < refresh_rate_activate_period) {
1159 refresh_time = now + (delta % current_vsync_period) - current_vsync_period;
1160 } else {
1161 refresh_time = desired_time - refresh_rate_activate_period;
1162 }
1163 const auto applied_time = refresh_time + refresh_rate_activate_period;
1164
1165 return std::make_tuple(refresh_time, applied_time);
1166 }
1167
IsActiveConfigReadyToSubmit(int64_t time)1168 bool HWCDisplay::IsActiveConfigReadyToSubmit(int64_t time) {
1169 return (pending_refresh_rate_config_ != UINT_MAX &&
1170 IsTimeAfterOrEqualVsyncTime(time, pending_refresh_rate_refresh_time_));
1171 }
1172
IsActiveConfigApplied(int64_t time,int64_t vsync_applied_time)1173 bool HWCDisplay::IsActiveConfigApplied(int64_t time, int64_t vsync_applied_time) {
1174 return IsTimeAfterOrEqualVsyncTime(time, vsync_applied_time);
1175 }
1176
RequestActiveConfigChange(hwc2_config_t config,uint32_t current_vsync_period,int64_t desired_time)1177 std::tuple<int64_t, int64_t> HWCDisplay::RequestActiveConfigChange(hwc2_config_t config,
1178 uint32_t current_vsync_period,
1179 int64_t desired_time) {
1180 int64_t refresh_time, applied_time;
1181 std::tie(refresh_time, applied_time) =
1182 EstimateVsyncPeriodChangeTimeline(current_vsync_period, desired_time);
1183
1184 pending_refresh_rate_config_ = config;
1185 pending_refresh_rate_refresh_time_ = refresh_time;
1186 pending_refresh_rate_applied_time_ = applied_time;
1187
1188 return std::make_tuple(refresh_time, applied_time);
1189 }
1190
SubmitActiveConfigChange(const uint32_t current_vsync_period)1191 void HWCDisplay::SubmitActiveConfigChange(const uint32_t current_vsync_period) {
1192 if (SetActiveConfig(pending_refresh_rate_config_) == HWC2::Error::None) {
1193 hwc_vsync_period_change_timeline_t timeline;
1194 {
1195 std::lock_guard<std::mutex> lock(transient_refresh_rate_lock_);
1196 std::tie(timeline.refreshTimeNanos, timeline.newVsyncAppliedTimeNanos) =
1197 EstimateVsyncPeriodChangeTimeline(current_vsync_period, pending_refresh_rate_refresh_time_);
1198
1199 transient_refresh_rate_info_.push_back(
1200 {current_vsync_period, timeline.newVsyncAppliedTimeNanos});
1201 }
1202 if (timeline.newVsyncAppliedTimeNanos != pending_refresh_rate_applied_time_) {
1203 timeline.refreshRequired = false;
1204 callbacks_->VsyncPeriodTimingChanged(id_, &timeline);
1205 }
1206 pending_refresh_rate_config_ = UINT_MAX;
1207 pending_refresh_rate_refresh_time_ = INT64_MAX;
1208 pending_refresh_rate_applied_time_ = INT64_MAX;
1209 }
1210 }
1211
GetDisplayGroupConfig(DisplayConfigVariableInfo variable_config)1212 int32_t HWCDisplay::GetDisplayGroupConfig(DisplayConfigVariableInfo variable_config) {
1213 for (auto &config : variable_config_map_) {
1214 if (config.second.SameGroup(variable_config)) {
1215 return INT32(config.first);
1216 }
1217 }
1218
1219 return -1;
1220 }
1221
IsSameGroup(hwc2_config_t configId1,hwc2_config_t configId2)1222 bool HWCDisplay::IsSameGroup(hwc2_config_t configId1, hwc2_config_t configId2) {
1223 const auto &variable_config1 = variable_config_map_.find(configId1);
1224 const auto &variable_config2 = variable_config_map_.find(configId2);
1225
1226 if (variable_config1 == variable_config_map_.end() ||
1227 variable_config2 == variable_config_map_.end()) {
1228 DLOGE("Invalid config %u, %u", configId1, configId2);
1229 return false;
1230 }
1231
1232 const auto &config1 = variable_config1->second;
1233 const auto &config2 = variable_config2->second;
1234 return config1.SameGroup(config2);
1235 }
1236
AllowSeamless(hwc2_config_t request_config)1237 bool HWCDisplay::AllowSeamless(hwc2_config_t request_config) {
1238 hwc2_config_t current_config;
1239 auto error = GetActiveConfig(¤t_config);
1240 if (CC_UNLIKELY(error == HWC2::Error::BadConfig)) {
1241 return true;
1242 }
1243
1244 return (error == HWC2::Error::None && IsSameGroup(current_config, request_config));
1245 }
1246
GetDisplayAttribute(hwc2_config_t config,HWC2::Attribute attribute,int32_t * out_value)1247 HWC2::Error HWCDisplay::GetDisplayAttribute(hwc2_config_t config, HWC2::Attribute attribute,
1248 int32_t *out_value) {
1249 if (variable_config_map_.find(config) == variable_config_map_.end()) {
1250 DLOGE("Get variable config failed");
1251 return HWC2::Error::BadDisplay;
1252 }
1253
1254 DisplayConfigVariableInfo variable_config = variable_config_map_.at(config);
1255 switch (attribute) {
1256 case HWC2::Attribute::VsyncPeriod:
1257 *out_value = INT32(variable_config.vsync_period_ns);
1258 break;
1259 case HWC2::Attribute::Width:
1260 *out_value = INT32(variable_config.x_pixels);
1261 break;
1262 case HWC2::Attribute::Height:
1263 *out_value = INT32(variable_config.y_pixels);
1264 break;
1265 case HWC2::Attribute::DpiX:
1266 *out_value = INT32(variable_config.x_dpi * 1000.0f);
1267 break;
1268 case HWC2::Attribute::DpiY:
1269 *out_value = INT32(variable_config.y_dpi * 1000.0f);
1270 break;
1271 case HWC2::Attribute::ConfigGroup:
1272 *out_value = GetDisplayGroupConfig(variable_config);
1273 break;
1274 default:
1275 DLOGW("Spurious attribute type = %s", to_string(attribute).c_str());
1276 *out_value = -1;
1277 return HWC2::Error::BadConfig;
1278 }
1279
1280 return HWC2::Error::None;
1281 }
1282
GetDisplayName(uint32_t * out_size,char * out_name)1283 HWC2::Error HWCDisplay::GetDisplayName(uint32_t *out_size, char *out_name) {
1284 // TODO(user): Get panel name and EDID name and populate it here
1285 if (out_size == nullptr) {
1286 return HWC2::Error::BadParameter;
1287 }
1288
1289 std::string name;
1290 switch (type_) {
1291 case kBuiltIn:
1292 name = "Built-in Display";
1293 break;
1294 case kPluggable:
1295 name = "Pluggable Display";
1296 break;
1297 case kVirtual:
1298 name = "Virtual Display";
1299 break;
1300 default:
1301 name = "Unknown";
1302 break;
1303 }
1304
1305 if (out_name == nullptr) {
1306 *out_size = UINT32(name.size()) + 1;
1307 } else {
1308 *out_size = std::min((UINT32(name.size()) + 1), *out_size);
1309 if (*out_size > 0) {
1310 strlcpy(out_name, name.c_str(), *out_size);
1311 out_name[*out_size - 1] = '\0';
1312 } else {
1313 DLOGW("Invalid size requested");
1314 }
1315 }
1316
1317 return HWC2::Error::None;
1318 }
1319
GetDisplayType(int32_t * out_type)1320 HWC2::Error HWCDisplay::GetDisplayType(int32_t *out_type) {
1321 if (out_type == nullptr) {
1322 return HWC2::Error::BadParameter;
1323 }
1324
1325 *out_type = HWC2_DISPLAY_TYPE_PHYSICAL;
1326
1327 return HWC2::Error::None;
1328 }
1329
GetPerFrameMetadataKeys(uint32_t * out_num_keys,PerFrameMetadataKey * out_keys)1330 HWC2::Error HWCDisplay::GetPerFrameMetadataKeys(uint32_t *out_num_keys,
1331 PerFrameMetadataKey *out_keys) {
1332 if (out_num_keys == nullptr) {
1333 return HWC2::Error::BadParameter;
1334 }
1335 const uint32_t num_keys = UINT32(PerFrameMetadataKey::HDR10_PLUS_SEI) + 1;
1336 if (out_keys == nullptr) {
1337 *out_num_keys = num_keys;
1338 } else {
1339 uint32_t max_out_key_elements = std::min(*out_num_keys, num_keys);
1340 for (int32_t i = 0; i < max_out_key_elements; i++) {
1341 out_keys[i] = static_cast<PerFrameMetadataKey>(i);
1342 }
1343 }
1344 return HWC2::Error::None;
1345 }
1346
GetActiveConfig(hwc2_config_t * out_config)1347 HWC2::Error HWCDisplay::GetActiveConfig(hwc2_config_t *out_config) {
1348 if (out_config == nullptr) {
1349 return HWC2::Error::BadDisplay;
1350 }
1351
1352 if (pending_config_) {
1353 *out_config = pending_config_index_;
1354 } else {
1355 GetActiveDisplayConfig(out_config);
1356 }
1357
1358 if (*out_config < hwc_config_map_.size()) {
1359 *out_config = hwc_config_map_.at(*out_config);
1360 }
1361 return HWC2::Error::None;
1362 }
1363
SetClientTarget(buffer_handle_t target,int32_t acquire_fence,int32_t dataspace,hwc_region_t damage)1364 HWC2::Error HWCDisplay::SetClientTarget(buffer_handle_t target, int32_t acquire_fence,
1365 int32_t dataspace, hwc_region_t damage) {
1366 // TODO(user): SurfaceFlinger gives us a null pointer here when doing full SDE composition
1367 // The error is problematic for layer caching as it would overwrite our cached client target.
1368 // Reported bug 28569722 to resolve this.
1369 // For now, continue to use the last valid buffer reported to us for layer caching.
1370 if (target == nullptr) {
1371 return HWC2::Error::None;
1372 }
1373
1374 if (acquire_fence == 0) {
1375 DLOGW("acquire_fence is zero");
1376 return HWC2::Error::BadParameter;
1377 }
1378
1379 Layer *sdm_layer = client_target_->GetSDMLayer();
1380 sdm_layer->frame_rate = std::min(current_refresh_rate_, HWCDisplay::GetThrottlingRefreshRate());
1381 client_target_->SetLayerSurfaceDamage(damage);
1382 int translated_dataspace = TranslateFromLegacyDataspace(dataspace);
1383 if (client_target_->GetLayerDataspace() != translated_dataspace) {
1384 DLOGW("New Dataspace = %d not matching Dataspace from color mode = %d",
1385 translated_dataspace, client_target_->GetLayerDataspace());
1386 return HWC2::Error::BadParameter;
1387 }
1388 client_target_->SetLayerBuffer(target, acquire_fence);
1389
1390 return HWC2::Error::None;
1391 }
1392
SetActiveConfig(hwc2_config_t config)1393 HWC2::Error HWCDisplay::SetActiveConfig(hwc2_config_t config) {
1394 DTRACE_SCOPED();
1395 hwc2_config_t current_config = 0;
1396 GetActiveConfig(¤t_config);
1397 if (current_config == config) {
1398 return HWC2::Error::None;
1399 }
1400
1401 // Store config index to be applied upon refresh.
1402 pending_config_ = true;
1403 pending_config_index_ = config;
1404
1405 validated_ = false;
1406 geometry_changes_ |= kConfigChanged;
1407
1408 // Trigger refresh. This config gets applied on next commit.
1409 callbacks_->Refresh(id_);
1410
1411 return HWC2::Error::None;
1412 }
1413
SetMixerResolution(uint32_t width,uint32_t height)1414 DisplayError HWCDisplay::SetMixerResolution(uint32_t width, uint32_t height) {
1415 return kErrorNotSupported;
1416 }
1417
SetFrameDumpConfig(uint32_t count,uint32_t bit_mask_layer_type,int32_t format,bool post_processed)1418 HWC2::Error HWCDisplay::SetFrameDumpConfig(uint32_t count, uint32_t bit_mask_layer_type,
1419 int32_t format, bool post_processed) {
1420 dump_frame_count_ = count;
1421 dump_frame_index_ = 0;
1422 dump_input_layers_ = ((bit_mask_layer_type & (1 << INPUT_LAYER_DUMP)) != 0);
1423
1424 if (tone_mapper_) {
1425 tone_mapper_->SetFrameDumpConfig(count);
1426 }
1427
1428 DLOGI("num_frame_dump %d, input_layer_dump_enable %d", dump_frame_count_, dump_input_layers_);
1429 validated_ = false;
1430 return HWC2::Error::None;
1431 }
1432
GetCurrentPowerMode()1433 HWC2::PowerMode HWCDisplay::GetCurrentPowerMode() {
1434 return current_power_mode_;
1435 }
1436
VSync(const DisplayEventVSync & vsync)1437 DisplayError HWCDisplay::VSync(const DisplayEventVSync &vsync) {
1438 if (callbacks_->Vsync_2_4CallbackRegistered()) {
1439 hwc2_vsync_period_t vsync_period;
1440 if (GetCurrentVsyncPeriod(&vsync_period) != HWC2::Error::None) {
1441 vsync_period = 0;
1442 }
1443 ATRACE_INT(vsyncPeriodTag, INT32(vsync_period));
1444 callbacks_->Vsync_2_4(id_, vsync.timestamp, vsync_period);
1445 } else if (CC_LIKELY(callbacks_->VsyncCallbackRegistered())) {
1446 callbacks_->Vsync(id_, vsync.timestamp);
1447 }
1448
1449 return kErrorNone;
1450 }
1451
Refresh()1452 DisplayError HWCDisplay::Refresh() {
1453 return kErrorNotSupported;
1454 }
1455
CECMessage(char * message)1456 DisplayError HWCDisplay::CECMessage(char *message) {
1457 if (qservice_) {
1458 qservice_->onCECMessageReceived(message, 0);
1459 } else {
1460 DLOGW("Qservice instance not available.");
1461 }
1462
1463 return kErrorNone;
1464 }
1465
HandleEvent(DisplayEvent event)1466 DisplayError HWCDisplay::HandleEvent(DisplayEvent event) {
1467 switch (event) {
1468 case kIdleTimeout: {
1469 SCOPE_LOCK(HWCSession::locker_[id_]);
1470 if (pending_commit_) {
1471 // If idle timeout event comes in between prepare
1472 // and commit, drop it since device is not really
1473 // idle.
1474 return kErrorNotSupported;
1475 }
1476 validated_ = false;
1477 break;
1478 }
1479 case kThermalEvent: {
1480 SEQUENCE_WAIT_SCOPE_LOCK(HWCSession::locker_[id_]);
1481 validated_ = false;
1482 } break;
1483 case kPanelDeadEvent:
1484 case kDisplayPowerResetEvent: {
1485 validated_ = false;
1486 if (event_handler_) {
1487 event_handler_->DisplayPowerReset();
1488 } else {
1489 DLOGW("Cannot execute DisplayPowerReset (client_id = %d), event_handler_ is nullptr",
1490 id_);
1491 }
1492 } break;
1493 case kIdlePowerCollapse: {
1494 // handle idle power collapse but do nothing
1495 } break;
1496 case kInvalidateDisplay:
1497 validated_ = false;
1498 break;
1499 default:
1500 DLOGW("Unknown event: %d", event);
1501 break;
1502 }
1503
1504 return kErrorNone;
1505 }
1506
HistogramEvent(int,uint32_t)1507 DisplayError HWCDisplay::HistogramEvent(int /* fd */, uint32_t /* blob_fd */) {
1508 return kErrorNone;
1509 }
1510
PrepareLayerStack(uint32_t * out_num_types,uint32_t * out_num_requests)1511 HWC2::Error HWCDisplay::PrepareLayerStack(uint32_t *out_num_types, uint32_t *out_num_requests) {
1512 layer_changes_.clear();
1513 layer_requests_.clear();
1514 has_client_composition_ = false;
1515 has_force_client_composition_ = false;
1516
1517 DTRACE_SCOPED();
1518 if (shutdown_pending_) {
1519 validated_ = false;
1520 return HWC2::Error::BadDisplay;
1521 }
1522
1523 if (CanSkipSdmPrepare(out_num_types, out_num_requests)) {
1524 return ((*out_num_types > 0) ? HWC2::Error::HasChanges : HWC2::Error::None);
1525 }
1526
1527 UpdateRefreshRate();
1528 UpdateActiveConfig();
1529 DisplayError error = display_intf_->Prepare(&layer_stack_);
1530 if (error != kErrorNone) {
1531 if (error == kErrorShutDown) {
1532 shutdown_pending_ = true;
1533 } else if (error == kErrorPermission) {
1534 WaitOnPreviousFence();
1535 MarkLayersForGPUBypass();
1536 geometry_changes_on_doze_suspend_ |= geometry_changes_;
1537 } else {
1538 DLOGE("Prepare failed. Error = %d", error);
1539 // To prevent surfaceflinger infinite wait, flush the previous frame during Commit()
1540 // so that previous buffer and fences are released, and override the error.
1541 flush_ = true;
1542 validated_ = false;
1543 // Prepare cycle can fail on a newly connected display if insufficient pipes
1544 // are available at this moment. Trigger refresh so that the other displays
1545 // can free up pipes and a valid content can be attached to virtual display.
1546 callbacks_->Refresh(id_);
1547 return HWC2::Error::BadDisplay;
1548 }
1549 } else {
1550 // clear geometry_changes_on_doze_suspend_ on successful prepare.
1551 geometry_changes_on_doze_suspend_ = GeometryChanges::kNone;
1552 }
1553
1554 for (auto hwc_layer : layer_set_) {
1555 Layer *layer = hwc_layer->GetSDMLayer();
1556 LayerComposition &composition = layer->composition;
1557
1558 if ((composition == kCompositionSDE) || (composition == kCompositionHybrid) ||
1559 (composition == kCompositionBlit)) {
1560 layer_requests_[hwc_layer->GetId()] = HWC2::LayerRequest::ClearClientTarget;
1561 }
1562
1563 HWC2::Composition requested_composition = hwc_layer->GetClientRequestedCompositionType();
1564 // Set SDM composition to HWC2 type in HWCLayer
1565 hwc_layer->SetComposition(composition);
1566 HWC2::Composition device_composition = hwc_layer->GetDeviceSelectedCompositionType();
1567 if (device_composition == HWC2::Composition::Client) {
1568 has_client_composition_ = true;
1569 }
1570
1571 if (requested_composition == HWC2::Composition::Client) {
1572 has_force_client_composition_ = true;
1573 }
1574
1575 // Update the changes list only if the requested composition is different from SDM comp type
1576 // TODO(user): Take Care of other comptypes(BLIT)
1577 if (requested_composition != device_composition) {
1578 layer_changes_[hwc_layer->GetId()] = device_composition;
1579 }
1580 hwc_layer->ResetValidation();
1581 }
1582
1583 if ((has_client_composition_) && (!has_force_client_composition_)) {
1584 DLOGI_IF(kTagDisplay, "HWC marked skip layer present");
1585 }
1586
1587 client_target_->ResetValidation();
1588 *out_num_types = UINT32(layer_changes_.size());
1589 *out_num_requests = UINT32(layer_requests_.size());
1590 validate_state_ = kNormalValidate;
1591 validated_ = true;
1592 layer_stack_invalid_ = false;
1593
1594 return ((*out_num_types > 0) ? HWC2::Error::HasChanges : HWC2::Error::None);
1595 }
1596
AcceptDisplayChanges()1597 HWC2::Error HWCDisplay::AcceptDisplayChanges() {
1598 if (layer_set_.empty()) {
1599 return HWC2::Error::None;
1600 }
1601
1602 if (!validated_) {
1603 return HWC2::Error::NotValidated;
1604 }
1605
1606 for (const auto& change : layer_changes_) {
1607 auto hwc_layer = layer_map_[change.first];
1608 auto composition = change.second;
1609 if (hwc_layer != nullptr) {
1610 hwc_layer->UpdateClientCompositionType(composition);
1611 } else {
1612 DLOGW("Invalid layer: %" PRIu64, change.first);
1613 }
1614 }
1615 return HWC2::Error::None;
1616 }
1617
GetChangedCompositionTypes(uint32_t * out_num_elements,hwc2_layer_t * out_layers,int32_t * out_types)1618 HWC2::Error HWCDisplay::GetChangedCompositionTypes(uint32_t *out_num_elements,
1619 hwc2_layer_t *out_layers, int32_t *out_types) {
1620 if (layer_set_.empty()) {
1621 return HWC2::Error::None;
1622 }
1623
1624 if (!validated_) {
1625 DLOGW("Display is not validated");
1626 return HWC2::Error::NotValidated;
1627 }
1628
1629 *out_num_elements = UINT32(layer_changes_.size());
1630 if (out_layers != nullptr && out_types != nullptr) {
1631 int i = 0;
1632 for (auto change : layer_changes_) {
1633 out_layers[i] = change.first;
1634 out_types[i] = INT32(change.second);
1635 i++;
1636 }
1637 }
1638 return HWC2::Error::None;
1639 }
1640
GetReleaseFences(uint32_t * out_num_elements,hwc2_layer_t * out_layers,int32_t * out_fences)1641 HWC2::Error HWCDisplay::GetReleaseFences(uint32_t *out_num_elements, hwc2_layer_t *out_layers,
1642 int32_t *out_fences) {
1643 if (out_num_elements == nullptr) {
1644 return HWC2::Error::BadParameter;
1645 }
1646
1647 if (out_layers != nullptr && out_fences != nullptr) {
1648 *out_num_elements = std::min(*out_num_elements, UINT32(layer_set_.size()));
1649 auto it = layer_set_.begin();
1650 for (uint32_t i = 0; i < *out_num_elements; i++, it++) {
1651 auto hwc_layer = *it;
1652 out_layers[i] = hwc_layer->GetId();
1653 out_fences[i] = hwc_layer->PopFrontReleaseFence();
1654 }
1655 } else {
1656 *out_num_elements = UINT32(layer_set_.size());
1657 }
1658
1659 return HWC2::Error::None;
1660 }
1661
GetDisplayRequests(int32_t * out_display_requests,uint32_t * out_num_elements,hwc2_layer_t * out_layers,int32_t * out_layer_requests)1662 HWC2::Error HWCDisplay::GetDisplayRequests(int32_t *out_display_requests,
1663 uint32_t *out_num_elements, hwc2_layer_t *out_layers,
1664 int32_t *out_layer_requests) {
1665 if (layer_set_.empty()) {
1666 return HWC2::Error::None;
1667 }
1668
1669 if (out_display_requests == nullptr || out_num_elements == nullptr) {
1670 return HWC2::Error::BadParameter;
1671 }
1672
1673 // No display requests for now
1674 // Use for sharing blit buffers and
1675 // writing wfd buffer directly to output if there is full GPU composition
1676 // and no color conversion needed
1677 if (!validated_) {
1678 DLOGW("Display is not validated");
1679 return HWC2::Error::NotValidated;
1680 }
1681
1682 *out_display_requests = 0;
1683 if (out_layers != nullptr && out_layer_requests != nullptr) {
1684 *out_num_elements = std::min(*out_num_elements, UINT32(layer_requests_.size()));
1685 auto it = layer_requests_.begin();
1686 for (uint32_t i = 0; i < *out_num_elements; i++, it++) {
1687 out_layers[i] = it->first;
1688 out_layer_requests[i] = INT32(it->second);
1689 }
1690 } else {
1691 *out_num_elements = UINT32(layer_requests_.size());
1692 }
1693
1694 auto client_target_layer = client_target_->GetSDMLayer();
1695 if (client_target_layer->request.flags.flip_buffer) {
1696 *out_display_requests = INT32(HWC2::DisplayRequest::FlipClientTarget);
1697 }
1698
1699 return HWC2::Error::None;
1700 }
1701
GetHdrCapabilities(uint32_t * out_num_types,int32_t * out_types,float * out_max_luminance,float * out_max_average_luminance,float * out_min_luminance)1702 HWC2::Error HWCDisplay::GetHdrCapabilities(uint32_t *out_num_types, int32_t *out_types,
1703 float *out_max_luminance,
1704 float *out_max_average_luminance,
1705 float *out_min_luminance) {
1706 if (out_num_types == nullptr || out_max_luminance == nullptr ||
1707 out_max_average_luminance == nullptr || out_min_luminance == nullptr) {
1708 return HWC2::Error::BadParameter;
1709 }
1710
1711 DisplayConfigFixedInfo fixed_info = {};
1712 display_intf_->GetConfig(&fixed_info);
1713
1714 if (!fixed_info.hdr_supported) {
1715 *out_num_types = 0;
1716 DLOGI("HDR is not supported");
1717 return HWC2::Error::None;
1718 }
1719
1720 if (out_types == nullptr) {
1721 // We support HDR10, HLG and HDR10_PLUS.
1722 *out_num_types = 3;
1723 } else {
1724 // HDR10, HLG and HDR10_PLUS are supported.
1725 out_types[0] = HAL_HDR_HDR10;
1726 out_types[1] = HAL_HDR_HLG;
1727 out_types[2] = HAL_HDR_HDR10_PLUS;
1728 *out_max_luminance = fixed_info.max_luminance;
1729 *out_max_average_luminance = fixed_info.average_luminance;
1730 *out_min_luminance = fixed_info.min_luminance;
1731 }
1732
1733 return HWC2::Error::None;
1734 }
1735
1736
CommitLayerStack(void)1737 HWC2::Error HWCDisplay::CommitLayerStack(void) {
1738 if (flush_) {
1739 return HWC2::Error::None;
1740 }
1741
1742 DTRACE_SCOPED();
1743
1744 if (!validated_) {
1745 DLOGV_IF(kTagClient, "Display %d is not validated", id_);
1746 return HWC2::Error::NotValidated;
1747 }
1748
1749 if (shutdown_pending_ || layer_set_.empty()) {
1750 return HWC2::Error::None;
1751 }
1752
1753 if (skip_commit_) {
1754 DLOGV_IF(kTagClient, "Skipping Refresh on display %d", id_);
1755 return HWC2::Error::None;
1756 }
1757
1758 DumpInputBuffers();
1759
1760 DisplayError error = kErrorUndefined;
1761 int status = 0;
1762 if (tone_mapper_) {
1763 if (NeedsToneMap(layer_stack_)) {
1764 status = tone_mapper_->HandleToneMap(&layer_stack_);
1765 if (status != 0) {
1766 DLOGE("Error handling HDR in ToneMapper");
1767 }
1768 } else {
1769 tone_mapper_->Terminate();
1770 }
1771 }
1772 error = display_intf_->Commit(&layer_stack_);
1773
1774 if (error == kErrorNone) {
1775 // A commit is successfully submitted, start flushing on failure now onwards.
1776 flush_on_error_ = true;
1777 first_cycle_ = false;
1778 } else {
1779 if (error == kErrorShutDown) {
1780 shutdown_pending_ = true;
1781 return HWC2::Error::Unsupported;
1782 } else if (error == kErrorNotValidated) {
1783 validated_ = false;
1784 return HWC2::Error::NotValidated;
1785 } else if (error != kErrorPermission) {
1786 DLOGE("Commit failed. Error = %d", error);
1787 // To prevent surfaceflinger infinite wait, flush the previous frame during Commit()
1788 // so that previous buffer and fences are released, and override the error.
1789 flush_ = true;
1790 }
1791 }
1792
1793 validate_state_ = kSkipValidate;
1794 return HWC2::Error::None;
1795 }
1796
PostCommitLayerStack(int32_t * out_retire_fence)1797 HWC2::Error HWCDisplay::PostCommitLayerStack(int32_t *out_retire_fence) {
1798 auto status = HWC2::Error::None;
1799
1800 // Do no call flush on errors, if a successful buffer is never submitted.
1801 if (flush_ && flush_on_error_) {
1802 display_intf_->Flush(&layer_stack_);
1803 validated_ = false;
1804 }
1805
1806 if (tone_mapper_ && tone_mapper_->IsActive()) {
1807 tone_mapper_->PostCommit(&layer_stack_);
1808 }
1809
1810 // TODO(user): No way to set the client target release fence on SF
1811 int32_t &client_target_release_fence =
1812 client_target_->GetSDMLayer()->input_buffer.release_fence_fd;
1813 if (client_target_release_fence >= 0) {
1814 // Close cached release fence.
1815 close(fbt_release_fence_);
1816 fbt_release_fence_ = dup(client_target_release_fence);
1817 // Close fence returned by driver.
1818 close(client_target_release_fence);
1819 client_target_release_fence = -1;
1820 }
1821 client_target_->ResetGeometryChanges();
1822
1823 for (auto hwc_layer : layer_set_) {
1824 hwc_layer->ResetGeometryChanges();
1825 Layer *layer = hwc_layer->GetSDMLayer();
1826 LayerBuffer *layer_buffer = &layer->input_buffer;
1827
1828 if (!flush_) {
1829 // If swapinterval property is set to 0 or for single buffer layers, do not update f/w
1830 // release fences and discard fences from driver
1831 if (swap_interval_zero_ || layer->flags.single_buffer) {
1832 close(layer_buffer->release_fence_fd);
1833 } else {
1834 // It may so happen that layer gets marked to GPU & app layer gets queued
1835 // to MDP for composition. In those scenarios, release fence of buffer should
1836 // have mdp and gpu sync points merged.
1837 hwc_layer->PushBackReleaseFence(layer_buffer->release_fence_fd);
1838 }
1839 } else {
1840 // In case of flush or display paused, we don't return an error to f/w, so it will
1841 // get a release fence out of the hwc_layer's release fence queue
1842 // We should push a -1 to preserve release fence circulation semantics.
1843 hwc_layer->PushBackReleaseFence(-1);
1844 }
1845
1846 layer_buffer->release_fence_fd = -1;
1847 if (layer_buffer->acquire_fence_fd >= 0) {
1848 close(layer_buffer->acquire_fence_fd);
1849 layer_buffer->acquire_fence_fd = -1;
1850 }
1851
1852 layer->request.flags = {};
1853 }
1854
1855 client_target_->GetSDMLayer()->request.flags = {};
1856 *out_retire_fence = -1;
1857 // if swapinterval property is set to 0 then close and reset the list retire fence
1858 if (swap_interval_zero_) {
1859 close(layer_stack_.retire_fence_fd);
1860 layer_stack_.retire_fence_fd = -1;
1861 }
1862 *out_retire_fence = layer_stack_.retire_fence_fd;
1863 layer_stack_.retire_fence_fd = -1;
1864
1865 if (dump_frame_count_) {
1866 dump_frame_count_--;
1867 dump_frame_index_++;
1868 }
1869
1870 layer_stack_.flags.geometry_changed = false;
1871 geometry_changes_ = GeometryChanges::kNone;
1872 flush_ = false;
1873 skip_commit_ = false;
1874
1875 return status;
1876 }
1877
SetIdleTimeoutMs(uint32_t timeout_ms)1878 void HWCDisplay::SetIdleTimeoutMs(uint32_t timeout_ms) {
1879 return;
1880 }
1881
SetMaxMixerStages(uint32_t max_mixer_stages)1882 DisplayError HWCDisplay::SetMaxMixerStages(uint32_t max_mixer_stages) {
1883 DisplayError error = kErrorNone;
1884
1885 if (display_intf_) {
1886 error = display_intf_->SetMaxMixerStages(max_mixer_stages);
1887 validated_ = false;
1888 }
1889
1890 return error;
1891 }
1892
DumpInputBuffers()1893 void HWCDisplay::DumpInputBuffers() {
1894 char dir_path[PATH_MAX];
1895 int status;
1896
1897 if (!dump_frame_count_ || flush_ || !dump_input_layers_) {
1898 return;
1899 }
1900
1901 DLOGI("dump_frame_count %d dump_input_layers %d", dump_frame_count_, dump_input_layers_);
1902 snprintf(dir_path, sizeof(dir_path), "%s/frame_dump_disp_id_%02u_%s", HWCDebugHandler::DumpDir(),
1903 UINT32(id_), GetDisplayString());
1904
1905 status = mkdir(dir_path, 777);
1906 if ((status != 0) && errno != EEXIST) {
1907 DLOGW("Failed to create %s directory errno = %d, desc = %s", dir_path, errno, strerror(errno));
1908 return;
1909 }
1910
1911 // Even if directory exists already, need to explicitly change the permission.
1912 if (chmod(dir_path, 0777) != 0) {
1913 DLOGW("Failed to change permissions on %s directory", dir_path);
1914 return;
1915 }
1916
1917 for (uint32_t i = 0; i < layer_stack_.layers.size(); i++) {
1918 auto layer = layer_stack_.layers.at(i);
1919 const private_handle_t *pvt_handle =
1920 reinterpret_cast<const private_handle_t *>(layer->input_buffer.buffer_id);
1921 auto acquire_fence_fd = layer->input_buffer.acquire_fence_fd;
1922
1923 if (acquire_fence_fd >= 0) {
1924 int error = sync_wait(acquire_fence_fd, 1000);
1925 if (error < 0) {
1926 DLOGW("sync_wait error errno = %d, desc = %s", errno, strerror(errno));
1927 continue;
1928 }
1929 }
1930
1931 DLOGI("Dump layer[%d] of %d pvt_handle %x pvt_handle->base %x", i, layer_stack_.layers.size(),
1932 pvt_handle, pvt_handle? pvt_handle->base : 0);
1933
1934 if (!pvt_handle) {
1935 DLOGE("Buffer handle is null");
1936 continue;
1937 }
1938
1939 if (!pvt_handle->base) {
1940 DisplayError error = buffer_allocator_->MapBuffer(pvt_handle, -1);
1941 if (error != kErrorNone) {
1942 DLOGE("Failed to map buffer, error = %d", error);
1943 continue;
1944 }
1945 }
1946
1947 char dump_file_name[PATH_MAX];
1948 size_t result = 0;
1949
1950 snprintf(dump_file_name, sizeof(dump_file_name), "%s/input_layer%d_%dx%d_%s_frame%d.raw",
1951 dir_path, i, pvt_handle->width, pvt_handle->height,
1952 qdutils::GetHALPixelFormatString(pvt_handle->format), dump_frame_index_);
1953
1954 FILE *fp = fopen(dump_file_name, "w+");
1955 if (fp) {
1956 result = fwrite(reinterpret_cast<void *>(pvt_handle->base), pvt_handle->size, 1, fp);
1957 fclose(fp);
1958 }
1959
1960 int release_fence = -1;
1961 DisplayError error = buffer_allocator_->UnmapBuffer(pvt_handle, &release_fence);
1962 if (error != kErrorNone) {
1963 DLOGE("Failed to unmap buffer, error = %d", error);
1964 continue;
1965 }
1966
1967 DLOGI("Frame Dump %s: is %s", dump_file_name, result ? "Successful" : "Failed");
1968 }
1969 }
1970
DumpOutputBuffer(const BufferInfo & buffer_info,void * base,int fence)1971 void HWCDisplay::DumpOutputBuffer(const BufferInfo &buffer_info, void *base, int fence) {
1972 char dir_path[PATH_MAX];
1973 int status;
1974
1975 snprintf(dir_path, sizeof(dir_path), "%s/frame_dump_disp_id_%02u_%s", HWCDebugHandler::DumpDir(),
1976 UINT32(id_), GetDisplayString());
1977
1978 status = mkdir(dir_path, 777);
1979 if ((status != 0) && errno != EEXIST) {
1980 DLOGW("Failed to create %s directory errno = %d, desc = %s", dir_path, errno, strerror(errno));
1981 return;
1982 }
1983
1984 // Even if directory exists already, need to explicitly change the permission.
1985 if (chmod(dir_path, 0777) != 0) {
1986 DLOGW("Failed to change permissions on %s directory", dir_path);
1987 return;
1988 }
1989
1990 if (base) {
1991 char dump_file_name[PATH_MAX];
1992 size_t result = 0;
1993
1994 if (fence >= 0) {
1995 int error = sync_wait(fence, 1000);
1996 if (error < 0) {
1997 DLOGW("sync_wait error errno = %d, desc = %s", errno, strerror(errno));
1998 return;
1999 }
2000 }
2001
2002 snprintf(dump_file_name, sizeof(dump_file_name), "%s/output_layer_%dx%d_%s_frame%d.raw",
2003 dir_path, buffer_info.alloc_buffer_info.aligned_width,
2004 buffer_info.alloc_buffer_info.aligned_height,
2005 GetFormatString(buffer_info.buffer_config.format), dump_frame_index_);
2006
2007 FILE *fp = fopen(dump_file_name, "w+");
2008 if (fp) {
2009 result = fwrite(base, buffer_info.alloc_buffer_info.size, 1, fp);
2010 fclose(fp);
2011 }
2012
2013 DLOGI("Frame Dump of %s is %s", dump_file_name, result ? "Successful" : "Failed");
2014 }
2015 }
2016
GetDisplayString()2017 const char *HWCDisplay::GetDisplayString() {
2018 switch (type_) {
2019 case kBuiltIn:
2020 return "builtin";
2021 case kPluggable:
2022 return "pluggable";
2023 case kVirtual:
2024 return "virtual";
2025 default:
2026 return "invalid";
2027 }
2028 }
2029
SetFrameBufferResolution(uint32_t x_pixels,uint32_t y_pixels)2030 int HWCDisplay::SetFrameBufferResolution(uint32_t x_pixels, uint32_t y_pixels) {
2031 if (x_pixels <= 0 || y_pixels <= 0) {
2032 DLOGW("Unsupported config: x_pixels=%d, y_pixels=%d", x_pixels, y_pixels);
2033 return -EINVAL;
2034 }
2035
2036 DisplayConfigVariableInfo fb_config;
2037 DisplayError error = display_intf_->GetFrameBufferConfig(&fb_config);
2038 if (error != kErrorNone) {
2039 DLOGV("Get frame buffer config failed. Error = %d", error);
2040 return -EINVAL;
2041 }
2042
2043 fb_config.x_pixels = x_pixels;
2044 fb_config.y_pixels = y_pixels;
2045
2046 error = display_intf_->SetFrameBufferConfig(fb_config);
2047 if (error != kErrorNone) {
2048 DLOGV("Set frame buffer config failed. Error = %d", error);
2049 return -EINVAL;
2050 }
2051
2052 // Create rects to represent the new source and destination crops
2053 LayerRect crop = LayerRect(0, 0, FLOAT(x_pixels), FLOAT(y_pixels));
2054 hwc_rect_t scaled_display_frame = {0, 0, INT(x_pixels), INT(y_pixels)};
2055 ApplyScanAdjustment(&scaled_display_frame);
2056 client_target_->SetLayerDisplayFrame(scaled_display_frame);
2057 client_target_->ResetPerFrameData();
2058
2059 auto client_target_layer = client_target_->GetSDMLayer();
2060 client_target_layer->src_rect = crop;
2061
2062 int aligned_width;
2063 int aligned_height;
2064 uint32_t usage = GRALLOC_USAGE_HW_FB;
2065 int format = HAL_PIXEL_FORMAT_RGBA_8888;
2066 int ubwc_disabled = 0;
2067 int flags = 0;
2068
2069 // By default UBWC is enabled and below property is global enable/disable for all
2070 // buffers allocated through gralloc , including framebuffer targets.
2071 HWCDebugHandler::Get()->GetProperty(DISABLE_UBWC_PROP, &ubwc_disabled);
2072 if (!ubwc_disabled) {
2073 usage |= GRALLOC_USAGE_PRIVATE_ALLOC_UBWC;
2074 flags |= private_handle_t::PRIV_FLAGS_UBWC_ALIGNED;
2075 }
2076
2077 buffer_allocator_->GetAlignedWidthAndHeight(INT(x_pixels), INT(y_pixels), format, usage,
2078 &aligned_width, &aligned_height);
2079
2080 // TODO(user): How does the dirty region get set on the client target? File bug on Google
2081 client_target_layer->composition = kCompositionGPUTarget;
2082 client_target_layer->input_buffer.format = HWCLayer::GetSDMFormat(format, flags);
2083 client_target_layer->input_buffer.width = UINT32(aligned_width);
2084 client_target_layer->input_buffer.height = UINT32(aligned_height);
2085 client_target_layer->input_buffer.unaligned_width = x_pixels;
2086 client_target_layer->input_buffer.unaligned_height = y_pixels;
2087 client_target_layer->plane_alpha = 255;
2088
2089 DLOGI("New framebuffer resolution (%dx%d)", fb_config.x_pixels, fb_config.y_pixels);
2090
2091 return 0;
2092 }
2093
GetFrameBufferResolution(uint32_t * x_pixels,uint32_t * y_pixels)2094 void HWCDisplay::GetFrameBufferResolution(uint32_t *x_pixels, uint32_t *y_pixels) {
2095 DisplayConfigVariableInfo fb_config;
2096 display_intf_->GetFrameBufferConfig(&fb_config);
2097
2098 *x_pixels = fb_config.x_pixels;
2099 *y_pixels = fb_config.y_pixels;
2100 }
2101
GetMixerResolution(uint32_t * x_pixels,uint32_t * y_pixels)2102 DisplayError HWCDisplay::GetMixerResolution(uint32_t *x_pixels, uint32_t *y_pixels) {
2103 return display_intf_->GetMixerResolution(x_pixels, y_pixels);
2104 }
2105
GetPanelResolution(uint32_t * x_pixels,uint32_t * y_pixels)2106 void HWCDisplay::GetPanelResolution(uint32_t *x_pixels, uint32_t *y_pixels) {
2107 DisplayConfigVariableInfo display_config;
2108 uint32_t active_index = 0;
2109
2110 display_intf_->GetActiveConfig(&active_index);
2111 display_intf_->GetConfig(active_index, &display_config);
2112
2113 *x_pixels = display_config.x_pixels;
2114 *y_pixels = display_config.y_pixels;
2115 }
2116
SetDisplayStatus(DisplayStatus display_status)2117 int HWCDisplay::SetDisplayStatus(DisplayStatus display_status) {
2118 int status = 0;
2119
2120 switch (display_status) {
2121 case kDisplayStatusResume:
2122 display_paused_ = false;
2123 status = INT32(SetPowerMode(HWC2::PowerMode::On, false /* teardown */));
2124 break;
2125 case kDisplayStatusOnline:
2126 status = INT32(SetPowerMode(HWC2::PowerMode::On, false /* teardown */));
2127 break;
2128 case kDisplayStatusPause:
2129 display_paused_ = true;
2130 status = INT32(SetPowerMode(HWC2::PowerMode::Off, false /* teardown */));
2131 break;
2132 case kDisplayStatusOffline:
2133 status = INT32(SetPowerMode(HWC2::PowerMode::Off, false /* teardown */));
2134 break;
2135 default:
2136 DLOGW("Invalid display status %d", display_status);
2137 return -EINVAL;
2138 }
2139
2140 return status;
2141 }
2142
SetCursorPosition(hwc2_layer_t layer,int x,int y)2143 HWC2::Error HWCDisplay::SetCursorPosition(hwc2_layer_t layer, int x, int y) {
2144 if (shutdown_pending_) {
2145 return HWC2::Error::None;
2146 }
2147
2148 if (!layer_stack_.flags.cursor_present) {
2149 DLOGW("Cursor layer not present");
2150 return HWC2::Error::BadLayer;
2151 }
2152
2153 HWCLayer *hwc_layer = GetHWCLayer(layer);
2154 if (hwc_layer == nullptr) {
2155 return HWC2::Error::BadLayer;
2156 }
2157 if (hwc_layer->GetDeviceSelectedCompositionType() != HWC2::Composition::Cursor) {
2158 return HWC2::Error::None;
2159 }
2160 if ((validate_state_ != kSkipValidate) && validated_) {
2161 // the device is currently in the middle of the validate/present sequence,
2162 // cannot set the Position(as per HWC2 spec)
2163 return HWC2::Error::NotValidated;
2164 }
2165
2166 DisplayState state;
2167 if (display_intf_->GetDisplayState(&state) == kErrorNone) {
2168 if (state != kStateOn) {
2169 return HWC2::Error::None;
2170 }
2171 }
2172
2173 // TODO(user): HWC1.5 was not letting SetCursorPosition before validateDisplay,
2174 // but HWC2.0 doesn't let setting cursor position after validate before present.
2175 // Need to revisit.
2176
2177 auto error = display_intf_->SetCursorPosition(x, y);
2178 if (error != kErrorNone) {
2179 if (error == kErrorShutDown) {
2180 shutdown_pending_ = true;
2181 return HWC2::Error::None;
2182 }
2183
2184 DLOGE("Failed for x = %d y = %d, Error = %d", x, y, error);
2185 return HWC2::Error::BadDisplay;
2186 }
2187
2188 return HWC2::Error::None;
2189 }
2190
OnMinHdcpEncryptionLevelChange(uint32_t min_enc_level)2191 int HWCDisplay::OnMinHdcpEncryptionLevelChange(uint32_t min_enc_level) {
2192 DisplayError error = display_intf_->OnMinHdcpEncryptionLevelChange(min_enc_level);
2193 if (error != kErrorNone) {
2194 DLOGE("Failed. Error = %d", error);
2195 return -1;
2196 }
2197
2198 validated_ = false;
2199 return 0;
2200 }
2201
MarkLayersForGPUBypass()2202 void HWCDisplay::MarkLayersForGPUBypass() {
2203 for (auto hwc_layer : layer_set_) {
2204 auto layer = hwc_layer->GetSDMLayer();
2205 layer->composition = kCompositionSDE;
2206 }
2207 validated_ = true;
2208 }
2209
MarkLayersForClientComposition()2210 void HWCDisplay::MarkLayersForClientComposition() {
2211 // ClientComposition - GPU comp, to acheive this, set skip flag so that
2212 // SDM does not handle this layer and hwc_layer composition will be
2213 // set correctly at the end of Prepare.
2214 DLOGV_IF(kTagClient, "HWC Layers marked for GPU comp");
2215 for (auto hwc_layer : layer_set_) {
2216 Layer *layer = hwc_layer->GetSDMLayer();
2217 layer->flags.skip = true;
2218 }
2219 layer_stack_.flags.skip_present = true;
2220 }
2221
ApplyScanAdjustment(hwc_rect_t * display_frame)2222 void HWCDisplay::ApplyScanAdjustment(hwc_rect_t *display_frame) {
2223 }
2224
ToggleScreenUpdates(bool enable)2225 int HWCDisplay::ToggleScreenUpdates(bool enable) {
2226 display_paused_ = enable ? false : true;
2227 callbacks_->Refresh(id_);
2228 validated_ = false;
2229 return 0;
2230 }
2231
ColorSVCRequestRoute(const PPDisplayAPIPayload & in_payload,PPDisplayAPIPayload * out_payload,PPPendingParams * pending_action)2232 int HWCDisplay::ColorSVCRequestRoute(const PPDisplayAPIPayload &in_payload,
2233 PPDisplayAPIPayload *out_payload,
2234 PPPendingParams *pending_action) {
2235 int ret = 0;
2236
2237 if (display_intf_)
2238 ret = display_intf_->ColorSVCRequestRoute(in_payload, out_payload, pending_action);
2239 else
2240 ret = -EINVAL;
2241
2242 return ret;
2243 }
2244
SolidFillPrepare()2245 void HWCDisplay::SolidFillPrepare() {
2246 if (solid_fill_enable_) {
2247 if (solid_fill_layer_ == NULL) {
2248 // Create a dummy layer here
2249 solid_fill_layer_ = new Layer();
2250 }
2251 uint32_t primary_width = 0, primary_height = 0;
2252 GetMixerResolution(&primary_width, &primary_height);
2253
2254 LayerBuffer *layer_buffer = &solid_fill_layer_->input_buffer;
2255 layer_buffer->width = primary_width;
2256 layer_buffer->height = primary_height;
2257 layer_buffer->unaligned_width = primary_width;
2258 layer_buffer->unaligned_height = primary_height;
2259 layer_buffer->acquire_fence_fd = -1;
2260 layer_buffer->release_fence_fd = -1;
2261
2262 solid_fill_layer_->composition = kCompositionGPU;
2263 solid_fill_layer_->src_rect = solid_fill_rect_;
2264 solid_fill_layer_->dst_rect = solid_fill_rect_;
2265
2266 solid_fill_layer_->blending = kBlendingPremultiplied;
2267 solid_fill_layer_->solid_fill_color = 0;
2268 solid_fill_layer_->solid_fill_info.bit_depth = solid_fill_color_.bit_depth;
2269 solid_fill_layer_->solid_fill_info.red = solid_fill_color_.red;
2270 solid_fill_layer_->solid_fill_info.blue = solid_fill_color_.blue;
2271 solid_fill_layer_->solid_fill_info.green = solid_fill_color_.green;
2272 solid_fill_layer_->solid_fill_info.alpha = solid_fill_color_.alpha;
2273 solid_fill_layer_->frame_rate = 60;
2274 solid_fill_layer_->visible_regions.push_back(solid_fill_layer_->dst_rect);
2275 solid_fill_layer_->flags.updating = 1;
2276 solid_fill_layer_->flags.solid_fill = true;
2277 } else {
2278 // delete the dummy layer
2279 delete solid_fill_layer_;
2280 solid_fill_layer_ = NULL;
2281 }
2282
2283 if (solid_fill_enable_ && solid_fill_layer_) {
2284 BuildSolidFillStack();
2285 MarkLayersForGPUBypass();
2286 }
2287
2288 return;
2289 }
2290
SolidFillCommit()2291 void HWCDisplay::SolidFillCommit() {
2292 if (solid_fill_enable_ && solid_fill_layer_) {
2293 LayerBuffer *layer_buffer = &solid_fill_layer_->input_buffer;
2294 if (layer_buffer->release_fence_fd > 0) {
2295 close(layer_buffer->release_fence_fd);
2296 layer_buffer->release_fence_fd = -1;
2297 }
2298 if (layer_stack_.retire_fence_fd > 0) {
2299 close(layer_stack_.retire_fence_fd);
2300 layer_stack_.retire_fence_fd = -1;
2301 }
2302 }
2303 }
2304
GetVisibleDisplayRect(hwc_rect_t * visible_rect)2305 int HWCDisplay::GetVisibleDisplayRect(hwc_rect_t *visible_rect) {
2306 if (!IsValid(display_rect_)) {
2307 return -EINVAL;
2308 }
2309
2310 visible_rect->left = INT(display_rect_.left);
2311 visible_rect->top = INT(display_rect_.top);
2312 visible_rect->right = INT(display_rect_.right);
2313 visible_rect->bottom = INT(display_rect_.bottom);
2314 DLOGI("Dpy = %d Visible Display Rect(%d %d %d %d)", visible_rect->left, visible_rect->top,
2315 visible_rect->right, visible_rect->bottom);
2316
2317 return 0;
2318 }
2319
HandleSecureSession(const std::bitset<kSecureMax> & secure_sessions,bool * power_on_pending)2320 int HWCDisplay::HandleSecureSession(const std::bitset<kSecureMax> &secure_sessions,
2321 bool *power_on_pending) {
2322 if (!power_on_pending) {
2323 return -EINVAL;
2324 }
2325
2326 if (active_secure_sessions_[kSecureDisplay] != secure_sessions[kSecureDisplay]) {
2327 if (secure_sessions[kSecureDisplay]) {
2328 HWC2::Error error = SetPowerMode(HWC2::PowerMode::Off, true /* teardown */);
2329 if (error != HWC2::Error::None) {
2330 DLOGE("SetPowerMode failed. Error = %d", error);
2331 }
2332 } else {
2333 *power_on_pending = true;
2334 }
2335
2336 DLOGI("SecureDisplay state changed from %d to %d for display %d",
2337 active_secure_sessions_.test(kSecureDisplay), secure_sessions.test(kSecureDisplay),
2338 type_);
2339 }
2340 active_secure_sessions_ = secure_sessions;
2341 return 0;
2342 }
2343
GetActiveSecureSession(std::bitset<kSecureMax> * secure_sessions)2344 int HWCDisplay::GetActiveSecureSession(std::bitset<kSecureMax> *secure_sessions) {
2345 if (!secure_sessions) {
2346 return -1;
2347 }
2348 secure_sessions->reset();
2349 for (auto hwc_layer : layer_set_) {
2350 Layer *layer = hwc_layer->GetSDMLayer();
2351 if (layer->input_buffer.flags.secure_camera) {
2352 secure_sessions->set(kSecureCamera);
2353 }
2354 if (layer->input_buffer.flags.secure_display) {
2355 secure_sessions->set(kSecureDisplay);
2356 }
2357 }
2358 return 0;
2359 }
2360
SetActiveDisplayConfig(uint32_t config)2361 int HWCDisplay::SetActiveDisplayConfig(uint32_t config) {
2362 uint32_t current_config = 0;
2363 display_intf_->GetActiveConfig(¤t_config);
2364 if (config == current_config) {
2365 return 0;
2366 }
2367
2368 validated_ = false;
2369 display_intf_->SetActiveConfig(config);
2370
2371 return 0;
2372 }
2373
GetActiveDisplayConfig(uint32_t * config)2374 int HWCDisplay::GetActiveDisplayConfig(uint32_t *config) {
2375 return display_intf_->GetActiveConfig(config) == kErrorNone ? 0 : -1;
2376 }
2377
GetDisplayConfigCount(uint32_t * count)2378 int HWCDisplay::GetDisplayConfigCount(uint32_t *count) {
2379 return display_intf_->GetNumVariableInfoConfigs(count) == kErrorNone ? 0 : -1;
2380 }
2381
GetDisplayAttributesForConfig(int config,DisplayConfigVariableInfo * display_attributes)2382 int HWCDisplay::GetDisplayAttributesForConfig(int config,
2383 DisplayConfigVariableInfo *display_attributes) {
2384 return display_intf_->GetConfig(UINT32(config), display_attributes) == kErrorNone ? 0 : -1;
2385 }
2386
GetUpdatingLayersCount(void)2387 uint32_t HWCDisplay::GetUpdatingLayersCount(void) {
2388 uint32_t updating_count = 0;
2389
2390 for (uint i = 0; i < layer_stack_.layers.size(); i++) {
2391 auto layer = layer_stack_.layers.at(i);
2392 if (layer->flags.updating) {
2393 updating_count++;
2394 }
2395 }
2396
2397 return updating_count;
2398 }
2399
IsLayerUpdating(HWCLayer * hwc_layer)2400 bool HWCDisplay::IsLayerUpdating(HWCLayer *hwc_layer) {
2401 auto layer = hwc_layer->GetSDMLayer();
2402 // Layer should be considered updating if
2403 // a) layer is in single buffer mode, or
2404 // b) valid dirty_regions(android specific hint for updating status), or
2405 // c) layer stack geometry has changed (TODO(user): Remove when SDM accepts
2406 // geometry_changed as bit fields).
2407 return (layer->flags.single_buffer || hwc_layer->IsSurfaceUpdated() ||
2408 geometry_changes_);
2409 }
2410
SanitizeRefreshRate(uint32_t req_refresh_rate)2411 uint32_t HWCDisplay::SanitizeRefreshRate(uint32_t req_refresh_rate) {
2412 uint32_t refresh_rate = req_refresh_rate;
2413
2414 if (refresh_rate < min_refresh_rate_) {
2415 // Pick the next multiple of request which is within the range
2416 refresh_rate =
2417 (((min_refresh_rate_ / refresh_rate) + ((min_refresh_rate_ % refresh_rate) ? 1 : 0)) *
2418 refresh_rate);
2419 }
2420
2421 if (refresh_rate > max_refresh_rate_) {
2422 refresh_rate = max_refresh_rate_;
2423 }
2424
2425 return refresh_rate;
2426 }
2427
GetDisplayClass()2428 DisplayClass HWCDisplay::GetDisplayClass() {
2429 return display_class_;
2430 }
2431
Dump()2432 std::string HWCDisplay::Dump() {
2433 std::ostringstream os;
2434 os << "\n------------HWC----------------\n";
2435 os << "HWC2 display_id: " << id_ << std::endl;
2436 for (auto layer : layer_set_) {
2437 auto sdm_layer = layer->GetSDMLayer();
2438 auto transform = sdm_layer->transform;
2439 os << "layer: " << std::setw(4) << layer->GetId();
2440 os << " z: " << layer->GetZ();
2441 os << " composition: " <<
2442 to_string(layer->GetOrigClientRequestedCompositionType()).c_str();
2443 os << "/" <<
2444 to_string(layer->GetDeviceSelectedCompositionType()).c_str();
2445 os << " alpha: " << std::to_string(sdm_layer->plane_alpha).c_str();
2446 os << " format: " << std::setw(22) << GetFormatString(sdm_layer->input_buffer.format);
2447 os << " dataspace:" << std::hex << "0x" << std::setw(8) << std::setfill('0')
2448 << layer->GetLayerDataspace() << std::dec << std::setfill(' ');
2449 os << " transform: " << transform.rotation << "/" << transform.flip_horizontal <<
2450 "/"<< transform.flip_vertical;
2451 os << " buffer_id: " << std::hex << "0x" << sdm_layer->input_buffer.buffer_id << std::dec
2452 << std::endl;
2453 }
2454
2455 if (has_client_composition_) {
2456 os << "\n---------client target---------\n";
2457 auto sdm_layer = client_target_->GetSDMLayer();
2458 os << "format: " << std::setw(14) << GetFormatString(sdm_layer->input_buffer.format);
2459 os << " dataspace:" << std::hex << "0x" << std::setw(8) << std::setfill('0')
2460 << client_target_->GetLayerDataspace() << std::dec << std::setfill(' ');
2461 os << " buffer_id: " << std::hex << "0x" << sdm_layer->input_buffer.buffer_id << std::dec
2462 << std::endl;
2463 }
2464
2465 if (layer_stack_invalid_) {
2466 os << "\n Layers added or removed but not reflected to SDM's layer stack yet\n";
2467 return os.str();
2468 }
2469
2470 if (color_mode_) {
2471 os << "\n----------Color Modes---------\n";
2472 color_mode_->Dump(&os);
2473 }
2474
2475 if (display_intf_) {
2476 os << "\n------------SDM----------------\n";
2477 os << display_intf_->Dump();
2478 }
2479
2480 os << "\n";
2481
2482 return os.str();
2483 }
2484
CanSkipValidate()2485 bool HWCDisplay::CanSkipValidate() {
2486 if (!validated_ || solid_fill_enable_) {
2487 return false;
2488 }
2489
2490 if ((tone_mapper_ && tone_mapper_->IsActive()) ||
2491 layer_stack_.flags.single_buffered_layer_present) {
2492 DLOGV_IF(kTagClient, "Tonemapping enabled or single buffer layer present = %d"
2493 " Returning false.", layer_stack_.flags.single_buffered_layer_present);
2494 return false;
2495 }
2496
2497 if (client_target_->NeedsValidation()) {
2498 DLOGV_IF(kTagClient, "Framebuffer target needs validation. Returning false.");
2499 return false;
2500 }
2501
2502 for (auto hwc_layer : layer_set_) {
2503 Layer *layer = hwc_layer->GetSDMLayer();
2504 if (hwc_layer->NeedsValidation()) {
2505 DLOGV_IF(kTagClient, "hwc_layer[%d] needs validation. Returning false.",
2506 hwc_layer->GetId());
2507 return false;
2508 }
2509
2510 // Do not allow Skip Validate, if any layer needs GPU Composition.
2511 if (layer->composition == kCompositionGPU || layer->composition == kCompositionNone) {
2512 DLOGV_IF(kTagClient, "hwc_layer[%d] is %s. Returning false.", hwc_layer->GetId(),
2513 (layer->composition == kCompositionGPU) ? "GPU composed": "Dropped");
2514 return false;
2515 }
2516 }
2517
2518 if (!layer_set_.empty() && !display_intf_->CanSkipValidate()) {
2519 DLOGV_IF(kTagClient, "Display needs validation %d", id_);
2520 return false;
2521 }
2522
2523 return true;
2524 }
2525
GetValidateDisplayOutput(uint32_t * out_num_types,uint32_t * out_num_requests)2526 HWC2::Error HWCDisplay::GetValidateDisplayOutput(uint32_t *out_num_types,
2527 uint32_t *out_num_requests) {
2528 *out_num_types = UINT32(layer_changes_.size());
2529 *out_num_requests = UINT32(layer_requests_.size());
2530
2531 return ((*out_num_types > 0) ? HWC2::Error::HasChanges : HWC2::Error::None);
2532 }
2533
GetDisplayIdentificationData(uint8_t * out_port,uint32_t * out_data_size,uint8_t * out_data)2534 HWC2::Error HWCDisplay::GetDisplayIdentificationData(uint8_t *out_port, uint32_t *out_data_size,
2535 uint8_t *out_data) {
2536 DisplayError ret = display_intf_->GetDisplayIdentificationData(out_port, out_data_size, out_data);
2537 if (ret != kErrorNone) {
2538 DLOGE("Failed due to SDM/Driver (err = %d, disp id = %" PRIu64
2539 " %d-%d", ret, id_, sdm_id_, type_);
2540 }
2541
2542 return HWC2::Error::None;
2543 }
2544
IsDisplayCommandMode()2545 bool HWCDisplay::IsDisplayCommandMode() {
2546 return is_cmd_mode_;
2547 }
2548
SetDisplayedContentSamplingEnabledVndService(bool enabled)2549 HWC2::Error HWCDisplay::SetDisplayedContentSamplingEnabledVndService(bool enabled) {
2550 return HWC2::Error::Unsupported;
2551 }
2552
SetDisplayedContentSamplingEnabled(int32_t enabled,uint8_t component_mask,uint64_t max_frames)2553 HWC2::Error HWCDisplay::SetDisplayedContentSamplingEnabled(int32_t enabled,
2554 uint8_t component_mask, uint64_t max_frames) {
2555
2556 DLOGV("Request to start/stop histogram thread not supported on this display");
2557 return HWC2::Error::Unsupported;
2558 }
2559
GetDisplayedContentSamplingAttributes(int32_t * format,int32_t * dataspace,uint8_t * supported_components)2560 HWC2::Error HWCDisplay::GetDisplayedContentSamplingAttributes(int32_t* format,
2561 int32_t* dataspace,
2562 uint8_t* supported_components) {
2563 return HWC2::Error::Unsupported;
2564 }
2565
GetDisplayedContentSample(uint64_t max_frames,uint64_t timestamp,uint64_t * numFrames,int32_t samples_size[NUM_HISTOGRAM_COLOR_COMPONENTS],uint64_t * samples[NUM_HISTOGRAM_COLOR_COMPONENTS])2566 HWC2::Error HWCDisplay::GetDisplayedContentSample(uint64_t max_frames,
2567 uint64_t timestamp,
2568 uint64_t* numFrames,
2569 int32_t samples_size[NUM_HISTOGRAM_COLOR_COMPONENTS],
2570 uint64_t* samples[NUM_HISTOGRAM_COLOR_COMPONENTS]) {
2571 return HWC2::Error::Unsupported;
2572 }
2573
GetDisplayConnectionType(uint32_t * out_type)2574 HWC2::Error HWCDisplay::GetDisplayConnectionType(uint32_t *out_type) {
2575 switch (GetDisplayClass()) {
2576 case DISPLAY_CLASS_BUILTIN:
2577 *out_type = HWC2_DISPLAY_CONNECTION_TYPE_INTERNAL;
2578 return HWC2::Error::None;
2579 case DISPLAY_CLASS_PLUGGABLE:
2580 *out_type = HWC2_DISPLAY_CONNECTION_TYPE_EXTERNAL;
2581 return HWC2::Error::None;
2582 default:
2583 return HWC2::Error::BadDisplay;
2584 }
2585 }
2586
GetDisplayBrightnessSupport(bool * out_support)2587 HWC2::Error HWCDisplay::GetDisplayBrightnessSupport(bool *out_support) {
2588 *out_support = false;
2589 return HWC2::Error::None;
2590 }
2591
GetProtectedContentsSupport(bool * out_support)2592 HWC2::Error HWCDisplay::GetProtectedContentsSupport(bool *out_support) {
2593 *out_support = false;
2594 return HWC2::Error::None;
2595 }
2596
GetAutoLowLatencyModeSupport(bool * out_support)2597 HWC2::Error HWCDisplay::GetAutoLowLatencyModeSupport(bool *out_support) {
2598 *out_support = false;
2599 return HWC2::Error::None;
2600 }
2601
GetSupportedContentTypes(uint32_t * out_num_types,uint32_t * out_types)2602 HWC2::Error HWCDisplay::GetSupportedContentTypes(uint32_t *out_num_types, uint32_t *out_types) {
2603 *out_num_types = 0;
2604 return HWC2::Error::None;
2605 }
2606
SetContentType(int32_t content_type)2607 HWC2::Error HWCDisplay::SetContentType(int32_t content_type) {
2608 if (content_type == HWC2_CONTENT_TYPE_NONE) {
2609 return HWC2::Error::None;
2610 }
2611
2612 return HWC2::Error::Unsupported;
2613 }
2614
2615 // Skip SDM prepare if all the layers in the current draw cycle are marked as Skip and
2616 // previous draw cycle had GPU Composition, as the resources for GPU Target layer have
2617 // already been validated and configured to the driver.
CanSkipSdmPrepare(uint32_t * num_types,uint32_t * num_requests)2618 bool HWCDisplay::CanSkipSdmPrepare(uint32_t *num_types, uint32_t *num_requests) {
2619 if (!validated_ || layer_set_.empty()) {
2620 return false;
2621 }
2622
2623 bool skip_prepare = true;
2624 for (auto hwc_layer : layer_set_) {
2625 if (!hwc_layer->GetSDMLayer()->flags.skip ||
2626 (hwc_layer->GetDeviceSelectedCompositionType() != HWC2::Composition::Client)) {
2627 skip_prepare = false;
2628 layer_changes_.clear();
2629 break;
2630 }
2631 if (hwc_layer->GetClientRequestedCompositionType() != HWC2::Composition::Client) {
2632 layer_changes_[hwc_layer->GetId()] = HWC2::Composition::Client;
2633 }
2634 }
2635
2636 if (skip_prepare) {
2637 *num_types = UINT32(layer_changes_.size());
2638 *num_requests = 0;
2639 layer_stack_invalid_ = false;
2640 has_client_composition_ = true;
2641 client_target_->ResetValidation();
2642 validate_state_ = kNormalValidate;
2643 }
2644
2645 return skip_prepare;
2646 }
2647
UpdateRefreshRate()2648 void HWCDisplay::UpdateRefreshRate() {
2649 for (auto hwc_layer : layer_set_) {
2650 if (hwc_layer->HasMetaDataRefreshRate()) {
2651 continue;
2652 }
2653 auto layer = hwc_layer->GetSDMLayer();
2654 layer->frame_rate = std::min(current_refresh_rate_, HWCDisplay::GetThrottlingRefreshRate());
2655 }
2656 }
2657
SetClientTargetDataSpace(int32_t dataspace)2658 int32_t HWCDisplay::SetClientTargetDataSpace(int32_t dataspace) {
2659 if (client_target_->GetLayerDataspace() != dataspace) {
2660 client_target_->SetLayerDataspace(dataspace);
2661 Layer *sdm_layer = client_target_->GetSDMLayer();
2662 // Data space would be validated at GetClientTargetSupport, so just use here.
2663 sdm::GetSDMColorSpace(client_target_->GetLayerDataspace(),
2664 &sdm_layer->input_buffer.color_metadata);
2665 }
2666
2667 return 0;
2668 }
2669
WaitOnPreviousFence()2670 void HWCDisplay::WaitOnPreviousFence() {
2671 DisplayConfigFixedInfo display_config;
2672 display_intf_->GetConfig(&display_config);
2673 if (!display_config.is_cmdmode) {
2674 return;
2675 }
2676
2677 // Since prepare failed commit would follow the same.
2678 // Wait for previous rel fence.
2679 for (auto hwc_layer : layer_set_) {
2680 auto fence = hwc_layer->PopBackReleaseFence();
2681 if (fence >= 0) {
2682 int error = sync_wait(fence, 1000);
2683 if (error < 0) {
2684 DLOGW("sync_wait error errno = %d, desc = %s", errno, strerror(errno));
2685 return;
2686 }
2687 }
2688 hwc_layer->PushBackReleaseFence(fence);
2689 }
2690
2691 if (fbt_release_fence_ >= 0) {
2692 int error = sync_wait(fbt_release_fence_, 1000);
2693 if (error < 0) {
2694 DLOGW("sync_wait error errno = %d, desc = %s", errno, strerror(errno));
2695 return;
2696 }
2697 }
2698 }
2699
GetLayerStack(HWCLayerStack * stack)2700 void HWCDisplay::GetLayerStack(HWCLayerStack *stack) {
2701 stack->client_target = client_target_;
2702 stack->layer_map = layer_map_;
2703 stack->layer_set = layer_set_;
2704 }
2705
SetLayerStack(HWCLayerStack * stack)2706 void HWCDisplay::SetLayerStack(HWCLayerStack *stack) {
2707 client_target_ = stack->client_target;
2708 layer_map_ = stack->layer_map;
2709 layer_set_ = stack->layer_set;
2710 }
UpdateActiveConfig()2711 void HWCDisplay::UpdateActiveConfig() {
2712 if (!pending_config_) {
2713 return;
2714 }
2715
2716 DisplayError error = display_intf_->SetActiveConfig(pending_config_index_);
2717 if (error != kErrorNone) {
2718 DLOGI("Failed to set %d config", INT(pending_config_index_));
2719 }
2720
2721 // Reset pending config.
2722 pending_config_ = false;
2723 }
2724
2725 } // namespace sdm
2726