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