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