1 /*
2  * Copyright (C) 2012 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef _EXYNOSDISPLAY_H
18 #define _EXYNOSDISPLAY_H
19 
20 #include <aidl/android/hardware/drm/HdcpLevels.h>
21 #include <android/hardware/graphics/composer/2.4/types.h>
22 #include <hardware/hwcomposer2.h>
23 #include <system/graphics.h>
24 #include <utils/KeyedVector.h>
25 #include <utils/Vector.h>
26 
27 #include <atomic>
28 #include <chrono>
29 #include <set>
30 
31 #include "DeconHeader.h"
32 #include "ExynosDisplayInterface.h"
33 #include "ExynosHWC.h"
34 #include "ExynosHWCDebug.h"
35 #include "ExynosHWCHelper.h"
36 #include "ExynosHwc3Types.h"
37 #include "ExynosMPP.h"
38 #include "ExynosResourceManager.h"
39 #include "drmeventlistener.h"
40 #include "worker.h"
41 
42 #include "../libvrr/interface/VariableRefreshRateInterface.h"
43 
44 #define HWC_CLEARDISPLAY_WITH_COLORMAP
45 #define HWC_PRINT_FRAME_NUM     10
46 
47 #define LOW_FPS_THRESHOLD     5
48 
49 using ::aidl::android::hardware::drm::HdcpLevels;
50 using ::android::hardware::graphics::composer::RefreshRateChangeListener;
51 using ::android::hardware::graphics::composer::V2_4::VsyncPeriodNanos;
52 using namespace std::chrono_literals;
53 
54 #ifndef SECOND_DISPLAY_START_BIT
55 #define SECOND_DISPLAY_START_BIT   4
56 #endif
57 
58 typedef hwc2_composition_t exynos_composition;
59 
60 class BrightnessController;
61 class ExynosLayer;
62 class ExynosDevice;
63 class ExynosMPP;
64 class ExynosMPPSource;
65 class HistogramController;
66 class DisplayTe2Manager;
67 
68 namespace aidl {
69 namespace google {
70 namespace hardware {
71 namespace power {
72 namespace extension {
73 namespace pixel {
74 
75 class IPowerExt;
76 
77 } // namespace pixel
78 } // namespace extension
79 } // namespace power
80 } // namespace hardware
81 } // namespace google
82 } // namespace aidl
83 namespace aidl {
84 namespace android {
85 namespace hardware {
86 namespace power {
87 
88 class IPower;
89 class IPowerHintSession;
90 class WorkDuration;
91 
92 } // namespace power
93 } // namespace hardware
94 } // namespace android
95 } // namespace aidl
96 
97 namespace aidl {
98 namespace com {
99 namespace google {
100 namespace hardware {
101 namespace pixel {
102 namespace display {
103 
104 class IDisplayProximitySensorCallback;
105 
106 } // namespace display
107 } // namespace pixel
108 } // namespace hardware
109 } // namespace google
110 } // namespace com
111 } // namespace aidl
112 
113 using WorkDuration = aidl::android::hardware::power::WorkDuration;
114 
115 enum dynamic_recomp_mode {
116     NO_MODE_SWITCH,
117     DEVICE_2_CLIENT,
118     CLIENT_2_DEVICE
119 };
120 
121 enum rendering_state {
122     RENDERING_STATE_NONE = 0,
123     RENDERING_STATE_VALIDATED,
124     RENDERING_STATE_ACCEPTED_CHANGE,
125     RENDERING_STATE_PRESENTED,
126     RENDERING_STATE_MAX
127 };
128 
129 enum composition_type {
130     COMPOSITION_NONE = 0,
131     COMPOSITION_CLIENT,
132     COMPOSITION_EXYNOS,
133     COMPOSITION_MAX
134 };
135 
136 enum {
137     PSR_NONE = 0,
138     PSR_DP,
139     PSR_MIPI,
140     PSR_MAX,
141 };
142 
143 enum {
144     PANEL_LEGACY = 0,
145     PANEL_DSC,
146     PANEL_MIC,
147 };
148 
149 enum {
150     eDisplayNone     = 0x0,
151     ePrimaryDisplay  = 0x00000001,
152     eExternalDisplay = 0x00000002,
153     eVirtualDisplay  = 0x00000004,
154 };
155 
156 // served as extension of hwc2_power_mode_t for use with setPowerMode
157 enum class ext_hwc2_power_mode_t{
158     PAUSE = 10,
159     RESUME,
160 };
161 
162 enum class PanelGammaSource {
163     GAMMA_DEFAULT,     // Resotre gamma table to default
164     GAMMA_CALIBRATION, // Update gamma table from calibration file
165     GAMMA_TYPES,
166 };
167 
168 enum class hwc_request_state_t {
169     SET_CONFIG_STATE_DONE = 0,
170     SET_CONFIG_STATE_PENDING,
171     SET_CONFIG_STATE_REQUESTED,
172 };
173 
174 enum class RrThrottleRequester : uint32_t {
175     PIXEL_DISP = 0,
176     TEST,
177     LHBM,
178     BRIGHTNESS,
179     MAX,
180 };
181 
182 enum class DispIdleTimerRequester : uint32_t {
183     SF = 0,
184     RR_THROTTLE,
185     MAX,
186 };
187 
188 #define NUM_SKIP_STATIC_LAYER  5
189 struct ExynosFrameInfo
190 {
191     uint32_t srcNum;
192     exynos_image srcInfo[NUM_SKIP_STATIC_LAYER];
193     exynos_image dstInfo[NUM_SKIP_STATIC_LAYER];
194 };
195 
196 struct exynos_readback_info
197 {
198     buffer_handle_t handle = NULL;
199     /* release sync fence file descriptor,
200      * which will be signaled when it is safe to write to the output buffer.
201      */
202     int rel_fence = -1;
203     /* acquire sync fence file descriptor which will signal when the
204      * buffer provided to setReadbackBuffer has been filled by the device and is
205      * safe for the client to read.
206      */
207     int acq_fence = -1;
208     /* Requested from HWCService */
209     bool requested_from_service = false;
210 };
211 
212 struct exynos_win_config_data
213 {
214     enum {
215         WIN_STATE_DISABLED = 0,
216         WIN_STATE_COLOR,
217         WIN_STATE_BUFFER,
218         WIN_STATE_UPDATE,
219         WIN_STATE_CURSOR,
220         WIN_STATE_RCD,
221     } state = WIN_STATE_DISABLED;
222 
223     uint32_t color = 0;
224     const ExynosLayer* layer = nullptr;
225     uint64_t buffer_id = 0;
226     int fd_idma[3] = {-1, -1, -1};
227     int acq_fence = -1;
228     int rel_fence = -1;
229     float plane_alpha = 1;
230     int32_t blending = HWC2_BLEND_MODE_NONE;
231     ExynosMPP* assignedMPP = NULL;
232     int format = 0;
233     uint32_t transform = 0;
234     android_dataspace dataspace = HAL_DATASPACE_UNKNOWN;
235     bool hdr_enable = false;
236     enum dpp_comp_src comp_src = DPP_COMP_SRC_NONE;
237     uint32_t min_luminance = 0;
238     uint32_t max_luminance = 0;
239     struct decon_win_rect block_area = { 0, 0, 0, 0};
240     struct decon_win_rect transparent_area = {0, 0, 0, 0};
241     struct decon_win_rect opaque_area = {0, 0, 0, 0};
242     struct decon_frame src = {0, 0, 0, 0, 0, 0};
243     struct decon_frame dst = {0, 0, 0, 0, 0, 0};
244     bool protection = false;
245     CompressionInfo compressionInfo;
246     bool needColorTransform = false;
247 
resetexynos_win_config_data248     void reset(){
249         *this = {};
250     };
251 };
252 struct exynos_dpu_data
253 {
254     int retire_fence = -1;
255     std::vector<exynos_win_config_data> configs;
256     std::vector<exynos_win_config_data> rcdConfigs;
257 
258     bool enable_win_update = false;
259     std::atomic<bool> enable_readback = false;
260     struct decon_frame win_update_region = {0, 0, 0, 0, 0, 0};
261     struct exynos_readback_info readback_info;
262 
initexynos_dpu_data263     void init(size_t configNum, size_t rcdConfigNum) {
264         configs.resize(configNum);
265         rcdConfigs.resize(rcdConfigNum);
266     };
267 
resetexynos_dpu_data268     void reset() {
269         retire_fence = -1;
270         for (auto& config : configs) config.reset();
271         for (auto& config : rcdConfigs) config.reset();
272 
273         /*
274          * Should not initialize readback_info
275          * readback_info should be initialized after present
276          */
277     };
278     exynos_dpu_data& operator =(const exynos_dpu_data &configs_data){
279         retire_fence = configs_data.retire_fence;
280         if (configs.size() != configs_data.configs.size()) {
281             HWC_LOGE(NULL, "invalid config, it has different configs size");
282             return *this;
283         }
284         configs = configs_data.configs;
285         if (rcdConfigs.size() != configs_data.rcdConfigs.size()) {
286             HWC_LOGE(NULL, "invalid config, it has different rcdConfigs size");
287             return *this;
288         }
289         rcdConfigs = configs_data.rcdConfigs;
290         return *this;
291     };
292 };
293 
294 class ExynosLowFpsLayerInfo
295 {
296     public:
297         ExynosLowFpsLayerInfo();
298         bool mHasLowFpsLayer;
299         int32_t mFirstIndex;
300         int32_t mLastIndex;
301 
302         void initializeInfos();
303         int32_t addLowFpsLayer(uint32_t layerIndex);
304 };
305 
306 class ExynosSortedLayer : public Vector <ExynosLayer*>
307 {
308     public:
309         ssize_t remove(const ExynosLayer *item);
310         status_t vector_sort();
311         static int compare(void const *lhs, void const *rhs);
312 };
313 
314 class DisplayTDMInfo {
315     public:
316         /* Could be extended */
317         typedef struct ResourceAmount {
318             uint32_t totalAmount;
319         } ResourceAmount_t;
320         std::map<tdm_attr_t, ResourceAmount_t> mAmount;
321 
initTDMInfo(ResourceAmount_t amount,tdm_attr_t attr)322         uint32_t initTDMInfo(ResourceAmount_t amount, tdm_attr_t attr) {
323             mAmount[attr] = amount;
324             return 0;
325         }
326 
getAvailableAmount(tdm_attr_t attr)327         ResourceAmount_t getAvailableAmount(tdm_attr_t attr) { return mAmount[attr]; }
328 };
329 
330 class ExynosCompositionInfo : public ExynosMPPSource {
331     public:
ExynosCompositionInfo()332         ExynosCompositionInfo():ExynosCompositionInfo(COMPOSITION_NONE){};
333         ExynosCompositionInfo(uint32_t type);
334         uint32_t mType;
335         bool mHasCompositionLayer;
336         bool mPrevHasCompositionLayer = false;
337         int32_t mFirstIndex;
338         int32_t mLastIndex;
339         buffer_handle_t mTargetBuffer;
340         android_dataspace mDataSpace;
341         int32_t mAcquireFence;
342         int32_t mReleaseFence;
343         bool mEnableSkipStatic;
344         bool mSkipStaticInitFlag;
345         bool mSkipFlag;
346         ExynosFrameInfo mSkipSrcInfo;
347         exynos_win_config_data mLastWinConfigData;
348 
349         int32_t mWindowIndex;
350         CompressionInfo mCompressionInfo;
351 
352         void initializeInfos(ExynosDisplay *display);
353         void initializeInfosComplete(ExynosDisplay *display);
354         void setTargetBuffer(ExynosDisplay *display, buffer_handle_t handle,
355                 int32_t acquireFence, android_dataspace dataspace);
356         void setCompressionType(uint32_t compressionType);
357         void dump(String8& result) const;
358         String8 getTypeStr();
359 };
360 
361 // Prepare multi-resolution
362 struct ResolutionSize {
363     uint32_t w;
364     uint32_t h;
365 };
366 
367 struct ResolutionInfo {
368     uint32_t nNum;
369     ResolutionSize nResolution[3];
370     uint32_t nDSCYSliceSize[3];
371     uint32_t nDSCXSliceSize[3];
372     int      nPanelType[3];
373 };
374 
375 typedef struct FrameIntervalPowerHint {
376     int frameIntervalNs = 0;
377     int averageRefreshPeriodNs = 0;
378 } FrameIntervalPowerHint_t;
379 
380 typedef struct NotifyExpectedPresentConfig {
381     int HeadsUpNs = 0;
382     int TimeoutNs = 0;
383 } NotifyExpectedPresentConfig_t;
384 
385 typedef struct VrrConfig {
386     bool isFullySupported = false;
387     int vsyncPeriodNs = 0;
388     int minFrameIntervalNs = 0;
389     std::optional<std::vector<FrameIntervalPowerHint_t>> frameIntervalPowerHint;
390     std::optional<NotifyExpectedPresentConfig_t> notifyExpectedPresentConfig;
391 } VrrConfig_t;
392 
393 typedef struct XrrSettings {
394     android::hardware::graphics::composer::XrrVersionInfo_t versionInfo;
395     NotifyExpectedPresentConfig_t notifyExpectedPresentConfig;
396     std::function<void(int)> configChangeCallback;
397 } XrrSettings_t;
398 
399 typedef struct displayConfigs {
toStringdisplayConfigs400     std::string toString() const {
401         std::ostringstream os;
402         os << "vsyncPeriod = " << vsyncPeriod;
403         os << ", w = " << width;
404         os << ", h = " << height;
405         os << ", Xdpi = " << Xdpi;
406         os << ", Ydpi = " << Ydpi;
407         os << ", groupId = " << groupId;
408         os << (isNsMode ? ", NS " : ", HS ");
409         os << ", refreshRate = " << refreshRate;
410         return os.str();
411     }
412 
413     // HWC2_ATTRIBUTE_VSYNC_PERIOD
414     VsyncPeriodNanos vsyncPeriod;
415     // HWC2_ATTRIBUTE_WIDTH
416     uint32_t width;
417     // case HWC2_ATTRIBUTE_HEIGHT
418     uint32_t height;
419     // HWC2_ATTRIBUTE_DPI_X
420     uint32_t Xdpi;
421     // HWC2_ATTRIBUTE_DPI_Y
422     uint32_t Ydpi;
423     // HWC2_ATTRIBUTE_CONFIG_GROUP
424     uint32_t groupId;
425 
426     std::optional<VrrConfig_t> vrrConfig;
427 
428     /* internal use */
429     bool isNsMode = false;
430     bool isOperationRateToBts;
431     bool isBoost2xBts;
432     int32_t refreshRate;
433 } displayConfigs_t;
434 
435 struct DisplayControl {
436     /** Composition crop en/disable **/
437     bool enableCompositionCrop;
438     /** Resource assignment optimization for exynos composition **/
439     bool enableExynosCompositionOptimization;
440     /** Resource assignment optimization for client composition **/
441     bool enableClientCompositionOptimization;
442     /** Use G2D as much as possible **/
443     bool useMaxG2DSrc;
444     /** Low fps layer optimization **/
445     bool handleLowFpsLayers;
446     /** start m2mMPP before persentDisplay **/
447     bool earlyStartMPP;
448     /** Adjust display size of the layer having high priority */
449     bool adjustDisplayFrame;
450     /** setCursorPosition support **/
451     bool cursorSupport;
452     /** readback support **/
453     bool readbackSupport = false;
454     /** Reserve MPP regardless of plug state **/
455     bool forceReserveMPP = false;
456     /** Skip M2MMPP processing **/
457     bool skipM2mProcessing = true;
458     /** Enable multi-thread present **/
459     bool multiThreadedPresent = false;
460 };
461 
462 class ExynosDisplay {
463     public:
464         const uint32_t mDisplayId;
465         const uint32_t mType;
466         const uint32_t mIndex;
467         String8 mDeconNodeName;
468         uint32_t mXres;
469         uint32_t mYres;
470         uint32_t mXdpi;
471         uint32_t mYdpi;
472         uint32_t mVsyncPeriod;
473         int32_t mRefreshRate;
474         int32_t mBtsFrameScanoutPeriod;
475         int32_t mBtsPendingOperationRatePeriod;
476 
477         /* Constructor */
478         ExynosDisplay(uint32_t type, uint32_t index, ExynosDevice* device,
479                       const std::string& displayName);
480         /* Destructor */
481         virtual ~ExynosDisplay();
482 
483         ExynosDevice *mDevice;
484 
485         const String8 mDisplayName;
486         const String8 mDisplayTraceName;
487         HwcMountOrientation mMountOrientation = HwcMountOrientation::ROT_0;
488         mutable Mutex mDisplayMutex;
489 
490         /** State variables */
491         bool mPlugState;
492         std::optional<hwc2_power_mode_t> mPowerModeState;
493         hwc2_vsync_t mVsyncState;
494         bool mHasSingleBuffer;
495         bool mPauseDisplay = false;
496 
497         DisplayControl mDisplayControl;
498 
499         /**
500          * TODO : Should be defined as ExynosLayer type
501          * Layer list those sorted by z-order
502          */
503         ExynosSortedLayer mLayers;
504         std::vector<ExynosLayer*> mIgnoreLayers;
505 
506         ExynosResourceManager *mResourceManager;
507 
508         /**
509          * Layer index, target buffer information for GLES.
510          */
511         ExynosCompositionInfo mClientCompositionInfo;
512 
513         /**
514          * Layer index, target buffer information for G2D.
515          */
516         ExynosCompositionInfo mExynosCompositionInfo;
517 
518         /**
519          * Geometry change info is described by bit map.
520          * This flag is cleared when resource assignment for all displays
521          * is done.
522          * Geometry changed to layer REFRESH_RATE_INDICATOR will be excluded.
523          */
524         uint64_t  mGeometryChanged;
525 
526         /**
527          * The number of buffer updates in the current frame.
528          * Buffer update for layer REFRESH_RATE_INDICATOR will be excluded.
529          */
530         uint32_t mBufferUpdates;
531 
532         /**
533          * Rendering step information that is seperated by
534          * VALIDATED, ACCEPTED_CHANGE, PRESENTED.
535          */
536         rendering_state  mRenderingState;
537 
538         /**
539          * Rendering step information that is called by client
540          */
541         rendering_state  mHWCRenderingState;
542 
543         /**
544          * Window total bandwidth by enabled window, It's used as dynamic re-composition enable/disable.
545          */
546         uint32_t  mDisplayBW;
547 
548         /**
549          * Mode information Dynamic re-composition feature.
550          * DEVICE_2_CLIENT: All layers are composited by GLES composition.
551          * CLIENT_2_DEVICE: Device composition.
552          */
553         dynamic_recomp_mode mDynamicReCompMode;
554         bool mDREnable;
555         bool mDRDefault;
556         mutable Mutex mDRMutex;
557 
558         nsecs_t  mLastFpsTime;
559         uint64_t mFrameCount;
560         uint64_t mLastFrameCount;
561         uint64_t mErrorFrameCount;
562         uint64_t mLastModeSwitchTimeStamp;
563         uint64_t mLastUpdateTimeStamp;
564         uint64_t mUpdateEventCnt;
565         uint64_t mUpdateCallCnt;
566 
567         /* default DMA for the display */
568         decon_idma_type mDefaultDMA;
569 
570         /**
571          * DECON WIN_CONFIG information.
572          */
573         exynos_dpu_data mDpuData;
574 
575         /**
576          * Last win_config data is used as WIN_CONFIG skip decision or debugging.
577          */
578         exynos_dpu_data mLastDpuData;
579 
580         /**
581          * Restore release fenc from DECON.
582          */
583         int mLastRetireFence;
584 
585         bool mUseDpu;
586 
587         /**
588          * Max Window number, It should be set by display module(chip)
589          */
590         uint32_t mMaxWindowNum;
591         uint32_t mWindowNumUsed;
592         uint32_t mBaseWindowIndex;
593 
594         // Priority
595         uint32_t mNumMaxPriorityAllowed;
596         int32_t mCursorIndex;
597 
598         int32_t mColorTransformHint;
599 
600         ExynosLowFpsLayerInfo mLowFpsLayerInfo;
601 
602         // HDR capabilities
603         std::vector<int32_t> mHdrTypes;
604         float mMaxLuminance;
605         float mMaxAverageLuminance;
606         float mMinLuminance;
607 
608         std::unique_ptr<BrightnessController> mBrightnessController;
609 
610         /* For histogram */
611         std::unique_ptr<HistogramController> mHistogramController;
612 
613         std::unique_ptr<DisplayTe2Manager> mDisplayTe2Manager;
614 
615         std::shared_ptr<
616                 aidl::com::google::hardware::pixel::display::IDisplayProximitySensorCallback>
617                 mProximitySensorStateChangeCallback;
618 
619         /* For debugging */
620         hwc_display_contents_1_t *mHWC1LayerList;
621         int mBufferDumpCount = 0;
622         int mBufferDumpNum = 0;
623 
624         /* Support Multi-resolution scheme */
625         int mOldScalerMode;
626         int mNewScaledWidth;
627         int mNewScaledHeight;
628         int32_t mDeviceXres;
629         int32_t mDeviceYres;
630         ResolutionInfo mResolutionInfo;
631         std::map<uint32_t, displayConfigs_t> mDisplayConfigs;
632 
633         // WCG
634         android_color_mode_t mColorMode;
635 
636         // Skip present frame if there was no validate after power on
637         bool mSkipFrame;
638         // Drop frame during resolution switch because the merged display frame
639         // is not equal to the full-resolution yet.
640         // TODO(b/310656340): remove this if it has been fixed from SF.
641         bool mDropFrameDuringResSwitch = false;
642 
643         hwc_vsync_period_change_constraints_t mVsyncPeriodChangeConstraints;
644         hwc_vsync_period_change_timeline_t mVsyncAppliedTimeLine;
645         hwc_request_state_t mConfigRequestState;
646         hwc2_config_t mDesiredConfig;
647 
648         hwc2_config_t mActiveConfig = UINT_MAX;
649         hwc2_config_t mPendingConfig = UINT_MAX;
650         int64_t mLastVsyncTimestamp = 0;
651 
652         void initDisplay();
653 
654         int getId();
getDisplayMutex()655         Mutex& getDisplayMutex() {return mDisplayMutex; };
656 
657         int32_t setCompositionTargetExynosImage(uint32_t targetType, exynos_image *src_img, exynos_image *dst_img);
658         int32_t initializeValidateInfos();
659         int32_t addClientCompositionLayer(uint32_t layerIndex);
660         int32_t removeClientCompositionLayer(uint32_t layerIndex);
661         bool hasClientComposition();
662         int32_t addExynosCompositionLayer(uint32_t layerIndex, float totalUsedCapa);
663 
664         bool isPowerModeOff() const;
665         bool isSecureContentPresenting() const;
666 
667         /**
668          * Dynamic AFBC Control solution : To get the prepared information is applied to current or not.
669          */
670         bool comparePreferedLayers();
671 
672         /**
673          * @param *outLayer
674          */
675         int32_t destroyLayer(hwc2_layer_t outLayer);
676 
677         void destroyLayers();
678 
679         ExynosLayer *checkLayer(hwc2_layer_t addr);
680 
681         void checkIgnoreLayers();
682         virtual void doPreProcessing();
683 
684         int checkLayerFps();
685 
686         int switchDynamicReCompMode(dynamic_recomp_mode mode);
687 
688         int checkDynamicReCompMode();
689 
690         int handleDynamicReCompMode();
691 
692         void updateBrightnessState();
693 
694         /**
695          * @param compositionType
696          */
697         int skipStaticLayers(ExynosCompositionInfo& compositionInfo);
698         int handleStaticLayers(ExynosCompositionInfo& compositionInfo);
699 
700         int doPostProcessing();
701 
702         int doExynosComposition();
703 
704         int32_t configureOverlay(ExynosLayer *layer, exynos_win_config_data &cfg);
705         int32_t configureOverlay(ExynosCompositionInfo &compositionInfo);
706 
707         int32_t configureHandle(ExynosLayer &layer,  int fence_fd, exynos_win_config_data &cfg);
708 
709         virtual int setWinConfigData();
710 
711         virtual int setDisplayWinConfigData();
712 
713         virtual int32_t validateWinConfigData();
714 
715         virtual int deliverWinConfigData();
716 
717         virtual int setReleaseFences();
718 
719         virtual bool checkFrameValidation();
720 
721         /**
722          * Display Functions for HWC 2.0
723          */
724 
725         /**
726          * Descriptor: HWC2_FUNCTION_ACCEPT_DISPLAY_CHANGES
727          * HWC2_PFN_ACCEPT_DISPLAY_CHANGES
728          **/
729         virtual int32_t acceptDisplayChanges();
730 
731         /**
732          * Descriptor: HWC2_FUNCTION_CREATE_LAYER
733          * HWC2_PFN_CREATE_LAYER
734          */
735         virtual int32_t createLayer(hwc2_layer_t* outLayer);
736 
737         /**
738          * Descriptor: HWC2_FUNCTION_GET_ACTIVE_CONFIG
739          * HWC2_PFN_GET_ACTIVE_CONFIG
740          */
741         virtual int32_t getActiveConfig(hwc2_config_t* outConfig);
742 
743         /**
744          * Descriptor: HWC2_FUNCTION_GET_CHANGED_COMPOSITION_TYPES
745          * HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES
746          */
747         virtual int32_t getChangedCompositionTypes(
748                 uint32_t* outNumElements, hwc2_layer_t* outLayers,
749                 int32_t* /*hwc2_composition_t*/ outTypes);
750 
751         /**
752          * Descriptor: HWC2_FUNCTION_GET_CLIENT_TARGET_SUPPORT
753          * HWC2_PFN_GET_CLIENT_TARGET_SUPPORT
754          */
755         virtual int32_t getClientTargetSupport(
756                 uint32_t width, uint32_t height,
757                 int32_t /*android_pixel_format_t*/ format,
758                 int32_t /*android_dataspace_t*/ dataspace);
759 
760         /**
761          * Descriptor: HWC2_FUNCTION_GET_COLOR_MODES
762          * HWC2_PFN_GET_COLOR_MODES
763          */
764         virtual int32_t getColorModes(
765                 uint32_t* outNumModes,
766                 int32_t* /*android_color_mode_t*/ outModes);
767 
768         /* getDisplayAttribute(..., config, attribute, outValue)
769          * Descriptor: HWC2_FUNCTION_GET_DISPLAY_ATTRIBUTE
770          * HWC2_PFN_GET_DISPLAY_ATTRIBUTE
771          */
772         virtual int32_t getDisplayAttribute(
773                 hwc2_config_t config,
774                 int32_t /*hwc2_attribute_t*/ attribute, int32_t* outValue);
775 
776         /* getDisplayConfigs(..., outNumConfigs, outConfigs)
777          * Descriptor: HWC2_FUNCTION_GET_DISPLAY_CONFIGS
778          * HWC2_PFN_GET_DISPLAY_CONFIGS
779          */
780         virtual int32_t getDisplayConfigs(
781                 uint32_t* outNumConfigs,
782                 hwc2_config_t* outConfigs);
783 
784         /* getDisplayName(..., outSize, outName)
785          * Descriptor: HWC2_FUNCTION_GET_DISPLAY_NAME
786          * HWC2_PFN_GET_DISPLAY_NAME
787          */
788         virtual int32_t getDisplayName(uint32_t* outSize, char* outName);
789 
790         /* getDisplayRequests(..., outDisplayRequests, outNumElements, outLayers,
791          *     outLayerRequests)
792          * Descriptor: HWC2_FUNCTION_GET_DISPLAY_REQUESTS
793          * HWC2_PFN_GET_DISPLAY_REQUESTS
794          */
795         virtual int32_t getDisplayRequests(
796                 int32_t* /*hwc2_display_request_t*/ outDisplayRequests,
797                 uint32_t* outNumElements, hwc2_layer_t* outLayers,
798                 int32_t* /*hwc2_layer_request_t*/ outLayerRequests);
799 
800         /* getDisplayType(..., outType)
801          * Descriptor: HWC2_FUNCTION_GET_DISPLAY_TYPE
802          * HWC2_PFN_GET_DISPLAY_TYPE
803          */
804         virtual int32_t getDisplayType(
805                 int32_t* /*hwc2_display_type_t*/ outType);
806         /* getDozeSupport(..., outSupport)
807          * Descriptor: HWC2_FUNCTION_GET_DOZE_SUPPORT
808          * HWC2_PFN_GET_DOZE_SUPPORT
809          */
810         virtual int32_t getDozeSupport(int32_t* outSupport);
811 
812         /* getReleaseFences(..., outNumElements, outLayers, outFences)
813          * Descriptor: HWC2_FUNCTION_GET_RELEASE_FENCES
814          * HWC2_PFN_GET_RELEASE_FENCES
815          */
816         virtual int32_t getReleaseFences(
817                 uint32_t* outNumElements,
818                 hwc2_layer_t* outLayers, int32_t* outFences);
819 
820         enum {
821             SKIP_ERR_NONE = 0,
822             SKIP_ERR_CONFIG_DISABLED,
823             SKIP_ERR_FIRST_FRAME,
824             SKIP_ERR_GEOMETRY_CHAGNED,
825             SKIP_ERR_HAS_CLIENT_COMP,
826             SKIP_ERR_SKIP_STATIC_CHANGED,
827             SKIP_ERR_HAS_REQUEST,
828             SKIP_ERR_DISP_NOT_CONNECTED,
829             SKIP_ERR_DISP_NOT_POWER_ON,
830             SKIP_ERR_FORCE_VALIDATE,
831             SKIP_ERR_INVALID_CLIENT_TARGET_BUFFER
832         };
833         virtual int32_t canSkipValidate();
834 
835         /* presentDisplay(..., outRetireFence)
836          * Descriptor: HWC2_FUNCTION_PRESENT_DISPLAY
837          * HWC2_PFN_PRESENT_DISPLAY
838          */
839         virtual int32_t presentDisplay(int32_t* outRetireFence);
840         virtual int32_t presentPostProcessing();
841 
842         /* setActiveConfig(..., config)
843          * Descriptor: HWC2_FUNCTION_SET_ACTIVE_CONFIG
844          * HWC2_PFN_SET_ACTIVE_CONFIG
845          */
846         virtual int32_t setActiveConfig(hwc2_config_t config);
847 
848         /* setClientTarget(..., target, acquireFence, dataspace)
849          * Descriptor: HWC2_FUNCTION_SET_CLIENT_TARGET
850          * HWC2_PFN_SET_CLIENT_TARGET
851          */
852         virtual int32_t setClientTarget(
853                 buffer_handle_t target,
854                 int32_t acquireFence, int32_t /*android_dataspace_t*/ dataspace);
855 
856         /* setColorTransform(..., matrix, hint)
857          * Descriptor: HWC2_FUNCTION_SET_COLOR_TRANSFORM
858          * HWC2_PFN_SET_COLOR_TRANSFORM
859          */
860         virtual int32_t setColorTransform(
861                 const float* matrix,
862                 int32_t /*android_color_transform_t*/ hint);
863 
864         /* setColorMode(..., mode)
865          * Descriptor: HWC2_FUNCTION_SET_COLOR_MODE
866          * HWC2_PFN_SET_COLOR_MODE
867          */
868         virtual int32_t setColorMode(
869                 int32_t /*android_color_mode_t*/ mode);
870 
871         /* setOutputBuffer(..., buffer, releaseFence)
872          * Descriptor: HWC2_FUNCTION_SET_OUTPUT_BUFFER
873          * HWC2_PFN_SET_OUTPUT_BUFFER
874          */
875         virtual int32_t setOutputBuffer(
876                 buffer_handle_t buffer,
877                 int32_t releaseFence);
878 
879         virtual int clearDisplay(bool needModeClear = false);
880 
881         /* setPowerMode(..., mode)
882          * Descriptor: HWC2_FUNCTION_SET_POWER_MODE
883          * HWC2_PFN_SET_POWER_MODE
884          */
885         virtual int32_t setPowerMode(
886                 int32_t /*hwc2_power_mode_t*/ mode);
887 
getPowerMode()888         virtual std::optional<hwc2_power_mode_t> getPowerMode() { return mPowerModeState; }
889 
890         /* setVsyncEnabled(..., enabled)
891          * Descriptor: HWC2_FUNCTION_SET_VSYNC_ENABLED
892          * HWC2_PFN_SET_VSYNC_ENABLED
893          */
894         virtual int32_t setVsyncEnabled(
895                 int32_t /*hwc2_vsync_t*/ enabled);
896         int32_t setVsyncEnabledInternal(
897                 int32_t /*hwc2_vsync_t*/ enabled);
898 
899         /* validateDisplay(..., outNumTypes, outNumRequests)
900          * Descriptor: HWC2_FUNCTION_VALIDATE_DISPLAY
901          * HWC2_PFN_VALIDATE_DISPLAY
902          */
903         virtual int32_t validateDisplay(
904                 uint32_t* outNumTypes, uint32_t* outNumRequests);
905 
906         /* getHdrCapabilities(..., outNumTypes, outTypes, outMaxLuminance,
907          *     outMaxAverageLuminance, outMinLuminance)
908          * Descriptor: HWC2_FUNCTION_GET_HDR_CAPABILITIES
909          */
910         virtual int32_t getHdrCapabilities(uint32_t* outNumTypes, int32_t* /*android_hdr_t*/ outTypes, float* outMaxLuminance,
911                 float* outMaxAverageLuminance, float* outMinLuminance);
912 
913         virtual int32_t getRenderIntents(int32_t mode, uint32_t* outNumIntents,
914                 int32_t* /*android_render_intent_v1_1_t*/ outIntents);
915         virtual int32_t setColorModeWithRenderIntent(int32_t /*android_color_mode_t*/ mode,
916                 int32_t /*android_render_intent_v1_1_t */ intent);
917 
918         /* HWC 2.3 APIs */
919 
920         /* getDisplayIdentificationData(..., outPort, outDataSize, outData)
921          * Descriptor: HWC2_FUNCTION_GET_DISPLAY_IDENTIFICATION_DATA
922          * Parameters:
923          *   outPort - the connector to which the display is connected;
924          *             pointer will be non-NULL
925          *   outDataSize - if outData is NULL, the size in bytes of the data which would
926          *       have been returned; if outData is not NULL, the size of outData, which
927          *       must not exceed the value stored in outDataSize prior to the call;
928          *       pointer will be non-NULL
929          *   outData - the EDID 1.3 blob identifying the display
930          *
931          * Returns HWC2_ERROR_NONE or one of the following errors:
932          *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
933          */
934         int32_t getDisplayIdentificationData(uint8_t* outPort,
935                 uint32_t* outDataSize, uint8_t* outData);
936 
937         /* getDisplayCapabilities(..., outCapabilities)
938          * Descriptor: HWC2_FUNCTION_GET_DISPLAY_CAPABILITIES
939          * Parameters:
940          *   outNumCapabilities - if outCapabilities was nullptr, returns the number of capabilities
941          *       if outCapabilities was not nullptr, returns the number of capabilities stored in
942          *       outCapabilities, which must not exceed the value stored in outNumCapabilities prior
943          *       to the call; pointer will be non-NULL
944          *   outCapabilities - a list of supported capabilities.
945          *
946          * Returns HWC2_ERROR_NONE or one of the following errors:
947          *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
948          */
949         /* Capabilities
950            Invalid = HWC2_CAPABILITY_INVALID,
951            SidebandStream = HWC2_CAPABILITY_SIDEBAND_STREAM,
952            SkipClientColorTransform = HWC2_CAPABILITY_SKIP_CLIENT_COLOR_TRANSFORM,
953            PresentFenceIsNotReliable = HWC2_CAPABILITY_PRESENT_FENCE_IS_NOT_RELIABLE,
954            SkipValidate = HWC2_CAPABILITY_SKIP_VALIDATE,
955         */
956         int32_t getDisplayCapabilities(uint32_t* outNumCapabilities,
957                 uint32_t* outCapabilities);
958 
959         /* getDisplayBrightnessSupport(displayToken)
960          * Descriptor: HWC2_FUNCTION_GET_DISPLAY_BRIGHTNESS_SUPPORT
961          * Parameters:
962          *   outSupport - whether the display supports operations.
963          *
964          * Returns HWC2_ERROR_NONE or one of the following errors:
965          *   HWC2_ERROR_BAD_DISPLAY when the display is invalid.
966          */
967         int32_t getDisplayBrightnessSupport(bool* outSupport);
968 
969         /* setDisplayBrightness(displayToken, brightnesss, waitPresent)
970          * Descriptor: HWC2_FUNCTION_SET_DISPLAY_BRIGHTNESS
971          * Parameters:
972          *   brightness - a number between 0.0f (minimum brightness) and 1.0f (maximum brightness), or
973          *          -1.0f to turn the backlight off.
974          *   waitPresent - apply this brightness change at next Present time.
975          *
976          * Returns HWC2_ERROR_NONE or one of the following errors:
977          *   HWC2_ERROR_BAD_DISPLAY   when the display is invalid, or
978          *   HWC2_ERROR_UNSUPPORTED   when brightness operations are not supported, or
979          *   HWC2_ERROR_BAD_PARAMETER when the brightness is invalid, or
980          *   HWC2_ERROR_NO_RESOURCES  when the brightness cannot be applied.
981          */
982         virtual int32_t setDisplayBrightness(float brightness, bool waitPresent = false);
983 
984         /* getDisplayConnectionType(..., outType)
985          * Descriptor: HWC2_FUNCTION_GET_DISPLAY_CONNECTION_TYPE
986          * Optional for all HWC2 devices
987          *
988          * Returns whether the given physical display is internal or external.
989          *
990          * Parameters:
991          * outType - the connection type of the display; pointer will be non-NULL
992          *
993          * Returns HWC2_ERROR_NONE or one of the following errors:
994          * HWC2_ERROR_BAD_DISPLAY when the display is invalid or virtual.
995          */
996         int32_t getDisplayConnectionType(uint32_t* outType);
997 
998         /* getDisplayVsyncPeriod(..., outVsyncPeriods)
999          * Descriptor: HWC2_FUNCTION_GET_DISPLAY_VSYNC_PERIOD
1000          * Required for HWC2 devices for composer 2.4
1001          *
1002          * Retrieves which vsync period the display is currently using.
1003          *
1004          * If no display configuration is currently active, this function must
1005          * return BAD_CONFIG. If a vsync period is about to change due to a
1006          * setActiveConfigWithConstraints call, this function must return the current vsync period
1007          * until the change has taken place.
1008          *
1009          * Parameters:
1010          *     outVsyncPeriod - the current vsync period of the display.
1011          *
1012          * Returns HWC2_ERROR_NONE or one of the following errors:
1013          *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
1014          *   HWC2_ERROR_BAD_CONFIG - no configuration is currently active
1015          */
1016         int32_t getDisplayVsyncPeriod(hwc2_vsync_period_t* __unused outVsyncPeriod);
1017 
1018         /* setActiveConfigWithConstraints(...,
1019          *                                config,
1020          *                                vsyncPeriodChangeConstraints,
1021          *                                outTimeline)
1022          * Descriptor: HWC2_FUNCTION_SET_ACTIVE_CONFIG_WITH_CONSTRAINTS
1023          * Required for HWC2 devices for composer 2.4
1024          *
1025          * Sets the active configuration and the refresh rate for this display.
1026          * If the new config shares the same config group as the current config,
1027          * only the vsync period shall change.
1028          * Upon returning, the given display configuration, except vsync period, must be active and
1029          * remain so until either this function is called again or the display is disconnected.
1030          * When the display starts to refresh at the new vsync period, onVsync_2_4 callback must be
1031          * called with the new vsync period.
1032          *
1033          * Parameters:
1034          *     config - the new display configuration.
1035          *     vsyncPeriodChangeConstraints - constraints required for changing vsync period:
1036          *                                    desiredTimeNanos - the time in CLOCK_MONOTONIC after
1037          *                                                       which the vsync period may change
1038          *                                                       (i.e., the vsync period must not change
1039          *                                                       before this time).
1040          *                                    seamlessRequired - if true, requires that the vsync period
1041          *                                                       change must happen seamlessly without
1042          *                                                       a noticeable visual artifact.
1043          *                                                       When the conditions change and it may be
1044          *                                                       possible to change the vsync period
1045          *                                                       seamlessly, HWC2_CALLBACK_SEAMLESS_POSSIBLE
1046          *                                                       callback must be called to indicate that
1047          *                                                       caller should retry.
1048          *     outTimeline - the timeline for the vsync period change.
1049          *
1050          * Returns HWC2_ERROR_NONE or one of the following errors:
1051          *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in.
1052          *   HWC2_ERROR_BAD_CONFIG - an invalid configuration handle passed in.
1053          *   HWC2_ERROR_SEAMLESS_NOT_ALLOWED - when seamlessRequired was true but config provided doesn't
1054          *                                 share the same config group as the current config.
1055          *   HWC2_ERROR_SEAMLESS_NOT_POSSIBLE - when seamlessRequired was true but the display cannot
1056          *                                      achieve the vsync period change without a noticeable
1057          *                                      visual artifact.
1058          */
1059         int32_t setActiveConfigWithConstraints(hwc2_config_t __unused config,
1060                 hwc_vsync_period_change_constraints_t* __unused vsyncPeriodChangeConstraints,
1061                 hwc_vsync_period_change_timeline_t* __unused outTimeline);
1062 
1063         /**
1064          * setBootDisplayConfig(..., config)
1065          * Descriptor: HWC2_FUNCTION_SET_BOOT_DISPLAY_CONFIG
1066          * Optional for HWC2 devices
1067          *
1068          * Sets the display config in which the device boots.
1069          * If the device is unable to boot in this config for any reason (example HDMI display
1070          * changed), the implementation should try to find a config which matches the resolution
1071          * and refresh-rate of this config. If no such config exists, the implementation's
1072          * preferred display config should be used.
1073          *
1074          * See also:
1075          *     getPreferredBootDisplayConfig
1076          *
1077          * Parameters:
1078          *     config - is the new boot time config for the display.
1079          *
1080          * Returns HWC2_ERROR_NONE or one of the following errors:
1081          *     HWC2_ERROR_BAD_DISPLAY - when the display is invalid
1082          *     HWC2_ERROR_BAD_CONFIG - when the configuration is invalid
1083          *     HWC2_ERROR_UNSUPPORTED - when the display does not support boot display config
1084          */
1085         virtual int32_t setBootDisplayConfig(int32_t config);
1086 
1087         /**
1088          * clearBootDisplayConfig(...)
1089          * Descriptor: HWC2_FUNCTION_CLEAR_BOOT_DISPLAY_CONFIG
1090          * Optional for HWC2 devices
1091          *
1092          * Clears the boot display config.
1093          * The device should boot in the implementation's preferred display config.
1094          *
1095          * Returns HWC2_ERROR_NONE or one of the following errors:
1096          *     HWC2_ERROR_BAD_DISPLAY - when the display is invalid
1097          *     HWC2_ERROR_UNSUPPORTED - when the display does not support boot display config
1098          */
1099         virtual int32_t clearBootDisplayConfig();
1100 
1101         /**
1102          * getPreferredBootDisplayConfig(..., config*)
1103          * Descriptor: HWC2_FUNCTION_GET_PREFERRED_DISPLAY_CONFIG
1104          * Optional for HWC2 devices
1105          *
1106          * Returns the implementation's preferred display config.
1107          * This is display config used by the implementation at boot time, if the boot
1108          * display config has not been requested yet, or if it has been previously cleared.
1109          *
1110          * See also:
1111          *     setBootDisplayConfig
1112          *
1113          * Parameters:
1114          *     outConfig - is the implementation's preferred display config
1115          *
1116          * Returns HWC2_ERROR_NONE or one of the following errors:
1117          *     HWC2_ERROR_BAD_DISPLAY - when the display is invalid
1118          *     HWC2_ERROR_BAD_CONFIG - when the configuration is invalid
1119          *     HWC2_ERROR_UNSUPPORTED - when the display does not support boot display config
1120          */
1121         int32_t getPreferredBootDisplayConfig(int32_t* outConfig);
1122 
1123         virtual int32_t getPreferredDisplayConfigInternal(int32_t* outConfig);
1124 
1125         /* setAutoLowLatencyMode(displayToken, on)
1126          * Descriptor: HWC2_FUNCTION_SET_AUTO_LOW_LATENCY_MODE
1127          * Optional for HWC2 devices
1128          *
1129          * setAutoLowLatencyMode requests that the display goes into low latency mode. If the display
1130          * is connected via HDMI 2.1, then Auto Low Latency Mode should be triggered. If the display is
1131          * internally connected, then a custom low latency mode should be triggered (if available).
1132          *
1133          * Parameters:
1134          *   on - indicates whether to turn low latency mode on (=true) or off (=false)
1135          *
1136          * Returns HWC2_ERROR_NONE or one of the following errors:
1137          *   HWC2_ERROR_BAD_DISPLAY - when the display is invalid, or
1138          *   HWC2_ERROR_UNSUPPORTED - when the display does not support any low latency mode
1139          */
1140         int32_t setAutoLowLatencyMode(bool __unused on);
1141 
1142         /* getSupportedContentTypes(..., outSupportedContentTypes)
1143          * Descriptor: HWC2_FUNCTION_GET_SUPPORTED_CONTENT_TYPES
1144          * Optional for HWC2 devices
1145          *
1146          * getSupportedContentTypes returns a list of supported content types
1147          * (as described in the definition of ContentType above).
1148          * This list must not change after initialization.
1149          *
1150          * Parameters:
1151          *   outNumSupportedContentTypes - if outSupportedContentTypes was nullptr, returns the number
1152          *       of supported content types; if outSupportedContentTypes was not nullptr, returns the
1153          *       number of capabilities stored in outSupportedContentTypes, which must not exceed the
1154          *       value stored in outNumSupportedContentTypes prior to the call; pointer will be non-NULL
1155          *   outSupportedContentTypes - a list of supported content types.
1156          *
1157          * Returns HWC2_ERROR_NONE or one of the following errors:
1158          *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
1159          */
1160         int32_t getSupportedContentTypes(uint32_t* __unused outNumSupportedContentTypes,
1161                 uint32_t* __unused outSupportedContentTypes);
1162 
1163         /* setContentType(displayToken, contentType)
1164          * Descriptor: HWC2_FUNCTION_SET_CONTENT_TYPE
1165          * Optional for HWC2 devices
1166          *
1167          * setContentType instructs the display that the content being shown is of the given contentType
1168          * (one of GRAPHICS, PHOTO, CINEMA, GAME).
1169          *
1170          * According to the HDMI 1.4 specification, supporting all content types is optional. Whether
1171          * the display supports a given content type is reported by getSupportedContentTypes.
1172          *
1173          * Parameters:
1174          *   contentType - the type of content that is currently being shown on the display
1175          *
1176          * Returns HWC2_ERROR_NONE or one of the following errors:
1177          *   HWC2_ERROR_BAD_DISPLAY - when the display is invalid, or
1178          *   HWC2_ERROR_UNSUPPORTED - when the given content type is a valid content type, but is not
1179          *                            supported on this display, or
1180          *   HWC2_ERROR_BAD_PARAMETER - when the given content type is invalid
1181          */
1182         int32_t setContentType(int32_t /* hwc2_content_type_t */ __unused contentType);
1183 
1184         /* getClientTargetProperty(..., outClientTargetProperty)
1185          * Descriptor: HWC2_FUNCTION_GET_CLIENT_TARGET_PROPERTY
1186          * Optional for HWC2 devices
1187          *
1188          * Retrieves the client target properties for which the hardware composer
1189          * requests after the last call to validateDisplay. The client must set the
1190          * properties of the client target to match the returned values.
1191          * When this API is implemented, if client composition is needed, the hardware
1192          * composer must return meaningful client target property with dataspace not
1193          * setting to UNKNOWN.
1194          * When the returned dataspace is set to UNKNOWN, it means hardware composer
1195          * requests nothing, the client must ignore the returned client target property
1196          * structrue.
1197          *
1198          * Parameters:
1199          *   outClientTargetProperty - the client target properties that hardware
1200          *       composer requests. If dataspace field is set to UNKNOWN, it means
1201          *       the hardware composer requests nothing, the client must ignore the
1202          *       returned client target property structure.
1203          *   outDimmingStage - where should the SDR dimming happen. HWC3 only.
1204          * Returns HWC2_ERROR_NONE or one of the following errors:
1205          *   HWC2_ERROR_BAD_DISPLAY - an invalid display handle was passed in
1206          *   HWC2_ERROR_NOT_VALIDATED - validateDisplay has not been called for this
1207          *       display
1208          */
1209         virtual int32_t getClientTargetProperty(
1210                 hwc_client_target_property_t* outClientTargetProperty,
1211                 HwcDimmingStage *outDimmingStage = nullptr);
1212 
1213         /*
1214          * HWC3
1215          *
1216          * Execute any pending brightness changes.
1217          */
1218         int32_t flushDisplayBrightnessChange();
1219 
1220         /*
1221          * HWC3
1222          *
1223          * Get display mount orientation.
1224          *
1225          */
1226         int32_t getMountOrientation(HwcMountOrientation *orientation);
1227 
1228         /*
1229          * HWC3
1230          *
1231          * Retrieve the vrrConfig for the corresponding display configuration.
1232          * If the configuration doesn't exist, return a nullopt.
1233          *
1234          */
1235         std::optional<VrrConfig_t> getVrrConfigs(hwc2_config_t config);
1236 
1237         /* setActiveConfig MISCs */
1238         bool isBadConfig(hwc2_config_t config);
1239         bool needNotChangeConfig(hwc2_config_t config);
1240         int32_t updateInternalDisplayConfigVariables(
1241                 hwc2_config_t config, bool updateVsync = true);
1242         int32_t resetConfigRequestStateLocked(hwc2_config_t config);
1243         int32_t updateConfigRequestAppliedTime();
1244         int32_t updateVsyncAppliedTimeLine(int64_t actualChangeTime);
1245         int32_t getDisplayVsyncPeriodInternal(
1246                 hwc2_vsync_period_t* outVsyncPeriod);
1247         virtual int32_t doDisplayConfigInternal(hwc2_config_t config);
1248         int32_t doDisplayConfigPostProcess(ExynosDevice *dev);
1249         int32_t getConfigAppliedTime(const uint64_t desiredTime,
1250                 const uint64_t actualChangeTime,
1251                 int64_t &appliedTime, int64_t &refreshTime);
1252         void updateBtsFrameScanoutPeriod(int32_t frameScanoutPeriod, bool configApplied = false);
1253         void tryUpdateBtsFromOperationRate(bool beforeValidateDisplay);
1254         uint32_t getBtsRefreshRate() const;
checkBtsReassignResource(const int32_t __unused vsyncPeriod,const int32_t __unused btsVsyncPeriod)1255         virtual void checkBtsReassignResource(const int32_t __unused vsyncPeriod,
1256                                               const int32_t __unused btsVsyncPeriod) {}
1257 
1258         /* TODO : TBD */
1259         int32_t setCursorPositionAsync(uint32_t x_pos, uint32_t y_pos);
1260 
1261         int32_t getReadbackBufferAttributes(int32_t* /*android_pixel_format_t*/ outFormat,
1262                 int32_t* /*android_dataspace_t*/ outDataspace);
1263         int32_t setReadbackBuffer(buffer_handle_t buffer, int32_t releaseFence, bool requestedService = false);
1264         void setReadbackBufferInternal(buffer_handle_t buffer, int32_t releaseFence, bool requestedService = false);
1265         int32_t getReadbackBufferFence(int32_t* outFence);
1266         /* This function is called by ExynosDisplayInterface class to set acquire fence*/
1267         int32_t setReadbackBufferAcqFence(int32_t acqFence);
1268 
1269         int32_t uncacheLayerBuffers(ExynosLayer* layer, const std::vector<buffer_handle_t>& buffers,
1270                                     std::vector<buffer_handle_t>& outClearableBuffers);
1271 
1272         virtual void miniDump(String8& result);
1273         virtual void dump(String8& result, const std::vector<std::string>& args = {});
1274 
1275         void dumpLocked(String8& result) REQUIRES(mDisplayMutex);
1276         void dumpAllBuffers() REQUIRES(mDisplayMutex);
1277 
1278         virtual int32_t startPostProcessing();
1279 
1280         void dumpConfig(const exynos_win_config_data &c);
1281         void dumpConfig(String8 &result, const exynos_win_config_data &c);
1282         void printConfig(exynos_win_config_data &c);
1283 
1284         unsigned int getLayerRegion(ExynosLayer *layer,
1285                 hwc_rect *rect_area, uint32_t regionType);
1286 
1287         int handleWindowUpdate();
1288         bool windowUpdateExceptions();
1289 
1290         /* For debugging */
setHWC1LayerList(hwc_display_contents_1_t * contents)1291         void setHWC1LayerList(hwc_display_contents_1_t *contents) {mHWC1LayerList = contents;};
1292         void traceLayerTypes();
1293 
1294         bool validateExynosCompositionLayer();
1295         void printDebugInfos(String8 &reason);
1296 
1297         bool checkConfigChanged(const exynos_dpu_data &lastConfigsData,
1298                 const exynos_dpu_data &newConfigsData);
1299         int checkConfigDstChanged(const exynos_dpu_data &lastConfigData,
1300                 const exynos_dpu_data &newConfigData, uint32_t index);
1301 
1302         uint32_t getRestrictionIndex(int halFormat);
1303         void closeFences();
1304         void closeFencesForSkipFrame(rendering_state renderingState);
1305 
1306         int32_t getLayerCompositionTypeForValidationType(uint32_t layerIndex);
1307         void setHWCControl(uint32_t ctrl, int32_t val);
1308         void setGeometryChanged(uint64_t changedBit);
1309         void clearGeometryChanged();
1310 
getPanelName()1311         virtual const std::string& getPanelName() { return mPanelName; };
1312 
1313         virtual void setDDIScalerEnable(int width, int height);
1314         virtual int getDDIScalerMode(int width, int height);
1315         void increaseMPPDstBufIndex();
1316         virtual void initDisplayInterface(uint32_t interfaceType);
updateColorConversionInfo()1317         virtual int32_t updateColorConversionInfo() { return NO_ERROR; };
resetColorMappingInfo(ExynosMPPSource *)1318         virtual int32_t resetColorMappingInfo(ExynosMPPSource* /*mppSrc*/) { return NO_ERROR; }
updatePresentColorConversionInfo()1319         virtual int32_t updatePresentColorConversionInfo() { return NO_ERROR; };
checkRrCompensationEnabled()1320         virtual bool checkRrCompensationEnabled() { return false; };
getColorAdjustedDbv(uint32_t &)1321         virtual int32_t getColorAdjustedDbv(uint32_t &) { return NO_ERROR; }
1322 
SetCurrentPanelGammaSource(const displaycolor::DisplayType,const PanelGammaSource &)1323         virtual int32_t SetCurrentPanelGammaSource(const displaycolor::DisplayType /* type */,
1324                                                    const PanelGammaSource& /* source */) {
1325             return HWC2_ERROR_UNSUPPORTED;
1326         }
GetCurrentPanelGammaSource()1327         virtual PanelGammaSource GetCurrentPanelGammaSource() const {
1328             return PanelGammaSource::GAMMA_DEFAULT;
1329         }
initLbe()1330         virtual void initLbe(){};
isLbeSupported()1331         virtual bool isLbeSupported() { return false; }
setLbeState(LbeState __unused state)1332         virtual void setLbeState(LbeState __unused state) {}
setLbeAmbientLight(int __unused value)1333         virtual void setLbeAmbientLight(int __unused value) {}
getLbeState()1334         virtual LbeState getLbeState() { return LbeState::OFF; }
1335 
1336         int32_t checkPowerHalExtHintSupport(const std::string& mode);
1337 
isLhbmSupported()1338         virtual bool isLhbmSupported() { return false; }
setLhbmState(bool __unused enabled)1339         virtual int32_t setLhbmState(bool __unused enabled) { return NO_ERROR; }
getLhbmState()1340         virtual bool getLhbmState() { return false; };
setEarlyWakeupDisplay()1341         virtual void setEarlyWakeupDisplay() {}
setExpectedPresentTime(uint64_t __unused timestamp,int __unused frameIntervalNs)1342         virtual void setExpectedPresentTime(uint64_t __unused timestamp,
1343                                             int __unused frameIntervalNs) {}
getPendingExpectedPresentTime()1344         virtual uint64_t getPendingExpectedPresentTime() { return 0; }
getPendingFrameInterval()1345         virtual int getPendingFrameInterval() { return 0; }
applyExpectedPresentTime()1346         virtual void applyExpectedPresentTime() {}
1347         virtual int32_t getDisplayIdleTimerSupport(bool& outSupport);
1348         virtual int32_t getDisplayMultiThreadedPresentSupport(bool& outSupport);
setDisplayIdleTimer(const int32_t __unused timeoutMs)1349         virtual int32_t setDisplayIdleTimer(const int32_t __unused timeoutMs) {
1350             return HWC2_ERROR_UNSUPPORTED;
1351         }
handleDisplayIdleEnter(const uint32_t __unused idleTeRefreshRate)1352         virtual void handleDisplayIdleEnter(const uint32_t __unused idleTeRefreshRate) {}
1353 
getPanelCalibrationStatus()1354         virtual PanelCalibrationStatus getPanelCalibrationStatus() {
1355             return PanelCalibrationStatus::UNCALIBRATED;
1356         }
isDbmSupported()1357         virtual bool isDbmSupported() { return false; }
setDbmState(bool __unused enabled)1358         virtual int32_t setDbmState(bool __unused enabled) { return NO_ERROR; }
1359 
1360         /* getDisplayPreAssignBit support mIndex up to 1.
1361            It supports only dual LCD and 2 external displays */
getDisplayPreAssignBit()1362         inline uint32_t getDisplayPreAssignBit() const {
1363             uint32_t type = SECOND_DISPLAY_START_BIT * mIndex + mType;
1364             return 1 << type;
1365         }
1366 
1367         void cleanupAfterClientDeath();
1368         int32_t getRCDLayerSupport(bool& outSupport) const;
1369         int32_t setDebugRCDLayerEnabled(bool enable);
1370 
1371         /* ignore / accept brightness update requests */
1372         virtual int32_t ignoreBrightnessUpdateRequests(bool ignore);
1373 
1374         /* set brightness to specific nits value */
1375         virtual int32_t setBrightnessNits(const float nits);
1376 
1377         /* set brightness by dbv value */
1378         virtual int32_t setBrightnessDbv(const uint32_t dbv);
1379 
getPanelSysfsPath()1380         virtual std::string getPanelSysfsPath() const { return std::string(); }
1381 
onVsync(int64_t __unused timestamp)1382         virtual void onVsync(int64_t __unused timestamp) { return; };
1383 
1384         displaycolor::DisplayType getDcDisplayType() const;
1385 
notifyExpectedPresent(int64_t __unused timestamp,int32_t __unused frameIntervalNs)1386         virtual int32_t notifyExpectedPresent(int64_t __unused timestamp,
1387                                               int32_t __unused frameIntervalNs) {
1388             return HWC2_ERROR_UNSUPPORTED;
1389         };
1390 
setPresentTimeoutController(uint32_t __unused controllerType)1391         virtual int32_t setPresentTimeoutController(uint32_t __unused controllerType) {
1392             return HWC2_ERROR_UNSUPPORTED;
1393         }
1394 
setPresentTimeoutParameters(int __unused timeoutNs,const std::vector<std::pair<uint32_t,uint32_t>> & __unused settings)1395         virtual int32_t setPresentTimeoutParameters(
1396                 int __unused timeoutNs,
1397                 const std::vector<std::pair<uint32_t, uint32_t>>& __unused settings) {
1398             return HWC2_ERROR_UNSUPPORTED;
1399         }
1400 
setFixedTe2Rate(const int __unused rateHz)1401         virtual int32_t setFixedTe2Rate(const int __unused rateHz) { return NO_ERROR; }
onProximitySensorStateChanged(bool __unused active)1402         virtual void onProximitySensorStateChanged(bool __unused active) { return; }
isProximitySensorStateCallbackSupported()1403         bool isProximitySensorStateCallbackSupported() { return mDisplayTe2Manager != nullptr; }
1404 
setDisplayTemperature(const int __unused temperature)1405         virtual int32_t setDisplayTemperature(const int __unused temperature) { return NO_ERROR; }
1406 
registerRefreshRateChangeListener(std::shared_ptr<RefreshRateChangeListener> __unused listener)1407         virtual int32_t registerRefreshRateChangeListener(
1408                 std::shared_ptr<RefreshRateChangeListener> __unused listener) {
1409             return NO_ERROR;
1410         }
1411 
setForceColorUpdate(bool __unused force)1412         virtual void setForceColorUpdate(bool __unused force) { return; }
1413 
1414     protected:
1415         virtual bool getHDRException(ExynosLayer *layer);
1416         virtual int32_t getActiveConfigInternal(hwc2_config_t* outConfig);
1417         virtual int32_t setActiveConfigInternal(hwc2_config_t config, bool force);
1418 
1419         void updateRefreshRateHint();
1420         bool isFullScreenComposition();
1421 
1422         std::string mPanelName;
1423 
1424     public:
1425         /**
1426          * This will be initialized with differnt class
1427          * that inherits ExynosDisplayInterface according to
1428          * interface type.
1429          */
1430         std::unique_ptr<ExynosDisplayInterface> mDisplayInterface;
1431         void requestLhbm(bool on);
1432 
setMinIdleRefreshRate(const int __unused fps,const RrThrottleRequester __unused requester)1433         virtual int32_t setMinIdleRefreshRate(const int __unused fps,
1434                                               const RrThrottleRequester __unused requester) {
1435             return NO_ERROR;
1436         }
setRefreshRateThrottleNanos(const int64_t __unused delayNanos,const RrThrottleRequester __unused requester)1437         virtual int32_t setRefreshRateThrottleNanos(const int64_t __unused delayNanos,
1438                                                     const RrThrottleRequester __unused requester) {
1439             return NO_ERROR;
1440         }
1441 
updateAppliedActiveConfig(const hwc2_config_t,const int64_t)1442         virtual void updateAppliedActiveConfig(const hwc2_config_t /*newConfig*/,
1443                                                const int64_t /*ts*/) {}
1444 
isConfigSettingEnabled()1445         virtual bool isConfigSettingEnabled() { return true; }
enableConfigSetting(bool)1446         virtual void enableConfigSetting(bool /*en*/) {}
1447 
1448         // is the hint session both enabled and supported
1449         bool usePowerHintSession();
1450 
setPeakRefreshRate(float rr)1451         void setPeakRefreshRate(float rr) { mPeakRefreshRate = rr; }
1452         uint32_t getPeakRefreshRate();
1453         VsyncPeriodNanos getVsyncPeriod(const int32_t config);
1454         uint32_t getRefreshRate(const int32_t config);
1455         uint32_t getConfigId(const int32_t refreshRate, const int32_t width, const int32_t height);
1456 
1457         // check if there are any dimmed layers
1458         bool isMixedComposition();
isPriorFrameMixedCompostion()1459         bool isPriorFrameMixedCompostion() { return mPriorFrameMixedComposition; }
1460         int lookupDisplayConfigs(const int32_t& width,
1461                                  const int32_t& height,
1462                                  const int32_t& fps,
1463                                  const int32_t& vsyncRate,
1464                                  int32_t* outConfig);
1465         int lookupDisplayConfigsRelaxed(const int32_t& width,
1466                                         const int32_t& height,
1467                                         const int32_t& fps,
1468                                         int32_t* outConfig);
1469 
1470     private:
1471         bool skipStaticLayerChanged(ExynosCompositionInfo& compositionInfo);
1472 
1473         bool shouldSignalNonIdle();
1474 
1475         /// minimum possible dim rate in the case hbm peak is 1000 nits and norml
1476         // display brightness is 2 nits
1477         static constexpr float kGhbmMinDimRatio = 0.002;
1478 
1479         /// consider HDR as full screen playback when its frame coverage
1480         //exceeds this threshold.
1481         static constexpr float kHdrFullScreen = 0.5;
1482         uint32_t mHdrFullScrenAreaThreshold;
1483 
1484         // peak refresh rate
1485         float mPeakRefreshRate = -1.0f;
1486 
1487         // track if the last frame is a mixed composition, to detect mixed
1488         // composition to non-mixed composition transition.
1489         bool mPriorFrameMixedComposition;
1490 
1491         /* Display hint to notify power hal */
1492         class PowerHalHintWorker : public Worker {
1493         public:
1494             PowerHalHintWorker(uint32_t displayId, const String8& displayTraceName);
1495             virtual ~PowerHalHintWorker();
1496             int Init();
1497 
1498             void signalRefreshRate(hwc2_power_mode_t powerMode, int32_t refreshRate);
1499             void signalNonIdle();
1500             void signalActualWorkDuration(nsecs_t actualDurationNanos);
1501             void signalTargetWorkDuration(nsecs_t targetDurationNanos);
1502 
1503             void addBinderTid(pid_t tid);
1504             void removeBinderTid(pid_t tid);
1505 
1506             bool signalStartHintSession();
1507             void trackThisThread();
1508 
1509             // is the hint session both enabled and supported
1510             bool usePowerHintSession();
1511             // is it known if the hint session is enabled + supported yet
1512             bool checkPowerHintSessionReady();
1513 
1514         protected:
1515             void Routine() override;
1516 
1517         private:
1518             static void BinderDiedCallback(void*);
1519             int32_t connectPowerHal();
1520             int32_t connectPowerHalExt();
1521             int32_t checkPowerHalExtHintSupport(const std::string& mode);
1522             int32_t sendPowerHalExtHint(const std::string& mode, bool enabled);
1523 
1524             int32_t checkRefreshRateHintSupport(const int32_t refreshRate);
1525             int32_t updateRefreshRateHintInternal(const hwc2_power_mode_t powerMode,
1526                                                   const int32_t refreshRate);
1527             int32_t sendRefreshRateHint(const int32_t refreshRate, bool enabled);
1528             void forceUpdateHints();
1529 
1530             int32_t checkIdleHintSupport();
1531             int32_t updateIdleHint(const int64_t deadlineTime, const bool forceUpdate);
1532             bool needUpdateIdleHintLocked(int64_t& timeout) REQUIRES(mutex_);
1533 
1534             // for adpf cpu hints
1535             int32_t sendActualWorkDuration();
1536             int32_t updateTargetWorkDuration();
1537 
1538             // Update checking methods
1539             bool needUpdateTargetWorkDurationLocked() REQUIRES(mutex_);
1540             bool needSendActualWorkDurationLocked() REQUIRES(mutex_);
1541 
1542             // is it known if the hint session is enabled + supported yet
1543             bool checkPowerHintSessionReadyLocked();
1544             // Hint session lifecycle management
1545             int32_t startHintSession();
1546 
1547             int32_t checkPowerHintSessionSupport();
1548             bool mNeedUpdateRefreshRateHint;
1549 
1550             // The last refresh rate hint that is still being enabled
1551             // If all refresh rate hints are disabled, then mLastRefreshRateHint = 0
1552             int mLastRefreshRateHint;
1553 
1554             // support list of refresh rate hints
1555             std::map<int32_t, bool> mRefreshRateHintSupportMap;
1556 
1557             bool mIdleHintIsEnabled;
1558             bool mForceUpdateIdleHint;
1559             int64_t mIdleHintDeadlineTime;
1560 
1561             // whether idle hint support is checked
1562             bool mIdleHintSupportIsChecked;
1563 
1564             // whether idle hint is supported
1565             bool mIdleHintIsSupported;
1566 
1567             String8 mDisplayTraceName;
1568             std::string mIdleHintStr;
1569             std::string mRefreshRateHintPrefixStr;
1570 
1571             hwc2_power_mode_t mPowerModeState;
1572             int32_t mRefreshRate;
1573 
1574             uint32_t mConnectRetryCount;
isPowerHalExist()1575             bool isPowerHalExist() { return mConnectRetryCount < 10; }
1576 
1577             ndk::ScopedAIBinder_DeathRecipient mDeathRecipient;
1578 
1579             // for power HAL extension hints
1580             std::shared_ptr<aidl::google::hardware::power::extension::pixel::IPowerExt>
1581                     mPowerHalExtAidl;
1582 
1583             // for normal power HAL hints
1584             std::shared_ptr<aidl::android::hardware::power::IPower> mPowerHalAidl;
1585             // Max amount the error term can vary without causing an actual value report,
1586             // as well as the target durations if not normalized
1587             static constexpr const std::chrono::nanoseconds kAllowedDeviation = 300us;
1588             // Target value used for initialization and normalization,
1589             // the actual value does not really matter
1590             static constexpr const std::chrono::nanoseconds kDefaultTarget = 50ms;
1591             // Whether to normalize all the actual values as error terms relative to a constant
1592             // target. This saves a binder call by not setting the target
1593             static const bool sNormalizeTarget;
1594             // Whether we should emit ATRACE_INT data for hint sessions
1595             static const bool sTraceHintSessionData;
1596             // Whether we use or disable the rate limiter for target and actual values
1597             static const bool sUseRateLimiter;
1598             std::shared_ptr<aidl::android::hardware::power::IPowerHintSession> mPowerHintSession;
1599             // queue of actual durations waiting to be reported
1600             std::vector<WorkDuration> mPowerHintQueue;
1601             // display-specific binder thread tids
1602             std::set<pid_t> mBinderTids;
1603             // indicates that the tid list has changed, so the session must be rebuilt
1604             bool mTidsUpdated = false;
1605 
1606             static std::mutex sSharedDisplayMutex;
1607             struct SharedDisplayData {
1608                 std::optional<bool> hintSessionEnabled;
1609                 std::optional<int32_t> hintSessionSupported;
1610             };
1611             // caches the output of usePowerHintSession to avoid sSharedDisplayMutex
1612             std::atomic<std::optional<bool>> mUsePowerHintSession{std::nullopt};
1613             // this lets us know if we can skip calling checkPowerHintSessionSupport
1614             bool mHintSessionSupportChecked = false;
1615             // used to indicate to all displays whether hint sessions are enabled/supported
1616             static SharedDisplayData sSharedDisplayData GUARDED_BY(sSharedDisplayMutex);
1617             // latest target that was signalled
1618             nsecs_t mTargetWorkDuration = kDefaultTarget.count();
1619             // last target duration reported to PowerHAL
1620             nsecs_t mLastTargetDurationReported = kDefaultTarget.count();
1621             // latest actual duration signalled
1622             std::optional<nsecs_t> mActualWorkDuration;
1623             // last error term reported to PowerHAL, used for rate limiting
1624             std::optional<nsecs_t> mLastErrorSent;
1625             // timestamp of the last report we sent, used to avoid stale sessions
1626             nsecs_t mLastActualReportTimestamp = 0;
1627             // amount of time after the last message was sent before the session goes stale
1628             // actually 100ms but we use 80 here to ideally avoid going stale
1629             static constexpr const std::chrono::nanoseconds kStaleTimeout = 80ms;
1630             // An adjustable safety margin which moves the "target" earlier to allow flinger to
1631             // go a bit over without dropping a frame, especially since we can't measure
1632             // the exact time HWC finishes composition so "actual" durations are measured
1633             // from the end of present() instead, which is a bit later.
1634             static constexpr const std::chrono::nanoseconds kTargetSafetyMargin = 2ms;
1635         };
1636 
1637         // union here permits use as a key in the unordered_map without a custom hash
1638         union AveragesKey {
1639             struct {
1640                 uint16_t layers;
1641                 bool validated;
1642                 bool beforeReleaseFence;
1643             };
1644             uint32_t value;
AveragesKey(size_t layers,bool validated,bool beforeReleaseFence)1645             AveragesKey(size_t layers, bool validated, bool beforeReleaseFence)
1646                   : layers(static_cast<uint16_t>(layers)),
1647                     validated(validated),
1648                     beforeReleaseFence(beforeReleaseFence) {}
uint32_t()1649             operator uint32_t() const { return value; }
1650         };
1651 
1652         static const constexpr int kAveragesBufferSize = 3;
1653         std::unordered_map<uint32_t, RollingAverage<kAveragesBufferSize>> mRollingAverages;
1654         // mPowerHalHint should be declared only after mDisplayId and mDisplayTraceName have been
1655         // declared since mDisplayId and mDisplayTraceName are needed as the parameter of
1656         // PowerHalHintWorker's constructor
1657         PowerHalHintWorker mPowerHalHint;
1658 
1659         std::optional<nsecs_t> mValidateStartTime;
1660         nsecs_t mPresentStartTime;
1661         std::optional<nsecs_t> mValidationDuration;
1662         // cached value used to skip evaluation once set
1663         std::optional<bool> mUsePowerHintSession;
1664         // tracks the time right before we start to wait for the fence
1665         std::optional<nsecs_t> mRetireFenceWaitTime;
1666         // tracks the time right after we finish waiting for the fence
1667         std::optional<nsecs_t> mRetireFenceAcquireTime;
1668         // tracks the time when the retire fence previously signaled
1669         std::optional<nsecs_t> mRetireFencePreviousSignalTime;
1670         // tracks the expected present time of the last frame
1671         std::optional<nsecs_t> mLastExpectedPresentTime;
1672         // tracks the expected present time of the current frame
1673         nsecs_t mExpectedPresentTime;
1674         // set once at the start of composition to ensure consistency
1675         bool mUsePowerHints = false;
1676         nsecs_t getExpectedPresentTime(nsecs_t startTime);
1677         nsecs_t getPredictedPresentTime(nsecs_t startTime);
1678         void updateAverages(nsecs_t endTime);
1679         std::optional<nsecs_t> getPredictedDuration(bool duringValidation);
1680         atomic_bool mDebugRCDLayerEnabled = true;
1681 
1682     protected:
getDisplayVsyncPeriodFromConfig(hwc2_config_t config)1683         inline uint32_t getDisplayVsyncPeriodFromConfig(hwc2_config_t config) {
1684             int32_t vsync_period;
1685             getDisplayAttribute(config, HWC2_ATTRIBUTE_VSYNC_PERIOD, &vsync_period);
1686             assert(vsync_period > 0);
1687             return static_cast<uint32_t>(vsync_period);
1688         }
1689         inline int32_t getDisplayFrameScanoutPeriodFromConfig(hwc2_config_t config);
1690         virtual void calculateTimelineLocked(
1691                 hwc2_config_t config,
1692                 hwc_vsync_period_change_constraints_t* vsyncPeriodChangeConstraints,
1693                 hwc_vsync_period_change_timeline_t* outTimeline);
1694 
1695     public:
1696         /* Override for each display's meaning of 'enabled state'
1697          * Primary : Power on, this function overrided in primary display module
1698          * Exteranal : Plug-in, default */
isEnabled()1699         virtual bool isEnabled() { return mPlugState; }
1700 
1701         // Resource TDM (Time-Division Multiplexing)
1702         std::map<std::pair<int32_t, int32_t>, DisplayTDMInfo> mDisplayTDMInfo;
1703 
1704         class RotatingLogFileWriter {
1705         public:
1706             RotatingLogFileWriter(uint32_t maxFileCount, uint32_t thresholdSizePerFile,
1707                                   std::string extension = ".txt")
mMaxFileCount(maxFileCount)1708                   : mMaxFileCount(maxFileCount),
1709                     mThresholdSizePerFile(thresholdSizePerFile),
1710                     mPrefixName(""),
1711                     mExtension(extension),
1712                     mLastFileIndex(-1),
1713                     mFile(nullptr) {}
1714 
~RotatingLogFileWriter()1715             ~RotatingLogFileWriter() {
1716                 if (mFile) {
1717                     fclose(mFile);
1718                 }
1719             }
1720 
1721             bool chooseOpenedFile();
write(const String8 & content)1722             void write(const String8& content) {
1723                 if (mFile) {
1724                     fwrite(content.c_str(), 1, content.size(), mFile);
1725                 }
1726             }
flush()1727             void flush() {
1728                 if (mFile) {
1729                     fflush(mFile);
1730                 }
1731             }
setPrefixName(const std::string & prefixName)1732             void setPrefixName(const std::string& prefixName) { mPrefixName = prefixName; }
1733 
1734         private:
1735             FILE* openLogFile(const std::string& filename, const std::string& mode);
1736             std::optional<nsecs_t> getLastModifiedTimestamp(const std::string& filename);
1737 
1738             uint32_t mMaxFileCount;
1739             uint32_t mThresholdSizePerFile;
1740             std::string mPrefixName;
1741             std::string mExtension;
1742             int32_t mLastFileIndex;
1743             FILE* mFile;
1744         };
1745         mutable RotatingLogFileWriter mErrLogFileWriter;
1746         RotatingLogFileWriter mDebugDumpFileWriter;
1747         RotatingLogFileWriter mFenceFileWriter;
1748 
1749     protected:
1750         class OperationRateManager {
1751         public:
OperationRateManager()1752             OperationRateManager() {}
~OperationRateManager()1753             virtual ~OperationRateManager() {}
1754 
onLowPowerMode(bool __unused enabled)1755             virtual int32_t onLowPowerMode(bool __unused enabled) { return 0; }
onPeakRefreshRate(uint32_t __unused rate)1756             virtual int32_t onPeakRefreshRate(uint32_t __unused rate) { return 0; }
onConfig(hwc2_config_t __unused cfg)1757             virtual int32_t onConfig(hwc2_config_t __unused cfg) { return 0; }
onBrightness(uint32_t __unused dbv)1758             virtual int32_t onBrightness(uint32_t __unused dbv) { return 0; }
onPowerMode(int32_t __unused mode)1759             virtual int32_t onPowerMode(int32_t __unused mode) { return 0; }
getTargetOperationRate()1760             virtual int32_t getTargetOperationRate() const { return 0; }
1761         };
1762 
1763     public:
1764         std::unique_ptr<OperationRateManager> mOperationRateManager;
isOperationRateSupported()1765         bool isOperationRateSupported() { return mOperationRateManager != nullptr; }
1766         void handleTargetOperationRate();
1767 
1768         bool mHpdStatus;
1769 
1770         virtual void invalidate();
1771         virtual bool checkHotplugEventUpdated(bool &hpdStatus);
1772         virtual void handleHotplugEvent(bool hpdStatus);
1773         virtual void hotplug();
1774 
1775         void contentProtectionUpdated(HdcpLevels hdcpLevels);
1776 
1777         class RefreshRateIndicator {
1778         public:
1779             virtual ~RefreshRateIndicator() = default;
init()1780             virtual int32_t init() { return NO_ERROR; }
disable()1781             virtual int32_t disable() { return NO_ERROR; }
updateRefreshRate(int __unused refreshRate)1782             virtual void updateRefreshRate(int __unused refreshRate) {}
checkOnPresentDisplay()1783             virtual void checkOnPresentDisplay() {}
checkOnSetActiveConfig(int __unused refreshRate)1784             virtual void checkOnSetActiveConfig(int __unused refreshRate) {}
1785         };
1786 
1787         class SysfsBasedRRIHandler : public RefreshRateIndicator,
1788                                      public DrmSysfsEventHandler,
1789                                      public std::enable_shared_from_this<SysfsBasedRRIHandler> {
1790         public:
1791             SysfsBasedRRIHandler(ExynosDisplay* display);
1792             virtual ~SysfsBasedRRIHandler() = default;
1793 
1794             int32_t init() override;
1795             int32_t disable() override;
1796             void updateRefreshRate(int refreshRate) override;
1797             void checkOnPresentDisplay() override;
1798 
1799             void handleSysfsEvent() override;
getFd()1800             int getFd() override { return mFd.get(); }
1801 
1802         private:
1803             void updateRefreshRateLocked(int refreshRate) REQUIRES(mMutex);
1804             void setAllowWakeup(bool enabled);
1805 
1806             ExynosDisplay* mDisplay;
1807             int mLastRefreshRate GUARDED_BY(mMutex);
1808             nsecs_t mLastCallbackTime GUARDED_BY(mMutex);
1809             std::atomic_bool mIgnoringLastUpdate = false;
1810             bool mCanIgnoreIncreaseUpdate GUARDED_BY(mMutex) = false;
1811             UniqueFd mFd;
1812             std::mutex mMutex;
1813 
1814             static constexpr auto kRefreshRateStatePathFormat =
1815                     "/sys/class/backlight/panel%d-backlight/state";
1816             static constexpr auto kRefreshRateAllowWakeupStateChangePathFormat =
1817                     "/sys/class/backlight/panel%d-backlight/allow_wakeup_by_state_change";
1818         };
1819 
1820         class ActiveConfigBasedRRIHandler : public RefreshRateIndicator {
1821         public:
1822             ActiveConfigBasedRRIHandler(ExynosDisplay* display);
1823             virtual ~ActiveConfigBasedRRIHandler() = default;
1824 
1825             int32_t init() override;
1826             void updateRefreshRate(int refreshRate) override;
1827             void checkOnSetActiveConfig(int refreshRate) override;
1828 
1829         private:
1830             void updateVsyncPeriod(int vsyncPeriod);
1831 
1832             ExynosDisplay* mDisplay;
1833             int mLastRefreshRate;
1834         };
1835 
1836         std::shared_ptr<RefreshRateIndicator> mRefreshRateIndicatorHandler;
1837         virtual int32_t setRefreshRateChangedCallbackDebugEnabled(bool enabled);
1838         nsecs_t getLastLayerUpdateTime();
1839         bool mUpdateRRIndicatorOnly = false;
1840         bool checkUpdateRRIndicatorOnly();
1841         bool isUpdateRRIndicatorOnly();
checkPreblendingRequirement()1842         virtual void checkPreblendingRequirement(){};
1843 
1844         void resetColorMappingInfoForClientComp();
1845         void storePrevValidateCompositionType();
1846 
isVrrSupported()1847         virtual bool isVrrSupported() const { return false; }
1848 };
1849 
1850 #endif //_EXYNOSDISPLAY_H
1851