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