1 /*
2 * Copyright (C) 2019 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 _EXYNOSDISPLAYDRMINTERFACE_H
18 #define _EXYNOSDISPLAYDRMINTERFACE_H
19
20 #include <drm/samsung_drm.h>
21 #include <utils/Condition.h>
22 #include <utils/Mutex.h>
23 #include <xf86drmMode.h>
24
25 #include <list>
26 #include <unordered_map>
27
28 #include "ExynosDisplay.h"
29 #include "ExynosDisplayInterface.h"
30 #include "ExynosHWC.h"
31 #include "ExynosMPP.h"
32 #include "drmconnector.h"
33 #include "drmcrtc.h"
34 #include "histogram/histogram.h"
35 #include "vsyncworker.h"
36
37 /* Max plane number of buffer object */
38 #define HWC_DRM_BO_MAX_PLANES 4
39
40 #ifndef HWC_FORCE_PANIC_PATH
41 #define HWC_FORCE_PANIC_PATH "/d/dpu/panic"
42 #endif
43
44 using namespace android;
45
46 class ExynosDevice;
47
48 template <typename T>
49 using DrmArray = std::array<T, HWC_DRM_BO_MAX_PLANES>;
50
51 class FramebufferManager {
52 public:
FramebufferManager()53 FramebufferManager(){};
54 ~FramebufferManager();
55 void init(int drmFd);
56
57 // get buffer for provided config, if a buffer with same config is already cached it will be
58 // reused otherwise one will be allocated. returns fbId that can be used to attach to the
59 // plane, any buffers allocated/reused with this call will be bound to the corresponding
60 // layer. Those fbIds will be cleaned up once the layer was destroyed.
61 int32_t getBuffer(const exynos_win_config_data &config, uint32_t &fbId);
62
63 bool checkShrink();
64
65 void cleanup(const ExynosLayer *layer);
66
67 // The flip function is to help clean up the cached fbIds of destroyed
68 // layers after the previous fdIds were update successfully on the
69 // screen.
70 // This should be called after the frame update.
71 void flip(bool hasSecureFrameBuffer);
72
73 // release all currently tracked buffers, this can be called for example when display is turned
74 // off
75 void releaseAll();
76
77 private:
78 // this struct should contain elements that can be used to identify framebuffer more easily
79 struct Framebuffer {
80 struct BufferDesc {
81 uint64_t bufferId;
82 int drmFormat;
83 bool isSecure;
84 bool operator==(const Framebuffer::BufferDesc &rhs) const {
85 return (bufferId == rhs.bufferId && drmFormat == rhs.drmFormat &&
86 isSecure == rhs.isSecure);
87 }
88 };
89 struct SolidColorDesc {
90 uint32_t width;
91 uint32_t height;
92 bool operator==(const Framebuffer::SolidColorDesc &rhs) const {
93 return (width == rhs.width && height == rhs.height);
94 }
95 };
96
FramebufferFramebuffer97 explicit Framebuffer(int fd, uint32_t fb, BufferDesc desc)
98 : drmFd(fd), fbId(fb), bufferDesc(desc){};
FramebufferFramebuffer99 explicit Framebuffer(int fd, uint32_t fb, SolidColorDesc desc)
100 : drmFd(fd), fbId(fb), colorDesc(desc){};
~FramebufferFramebuffer101 ~Framebuffer() { drmModeRmFB(drmFd, fbId); };
102 int drmFd;
103 uint32_t fbId;
104 union {
105 BufferDesc bufferDesc;
106 SolidColorDesc colorDesc;
107 };
108 };
109 using FBList = std::list<std::unique_ptr<Framebuffer>>;
110
111 template <class UnaryPredicate>
112 uint32_t findCachedFbId(const ExynosLayer *layer, UnaryPredicate predicate);
113 int addFB2WithModifiers(uint32_t state, uint32_t width, uint32_t height, uint32_t drmFormat,
114 const DrmArray<uint32_t> &handles,
115 const DrmArray<uint32_t> &pitches,
116 const DrmArray<uint32_t> &offsets,
117 const DrmArray<uint64_t> &modifier, uint32_t *buf_id,
118 uint32_t flags);
119 bool validateLayerInfo(uint32_t state, uint32_t pixel_format,
120 const DrmArray<uint32_t> &handles,
121 const DrmArray<uint64_t> &modifier);
122 uint32_t getBufHandleFromFd(int fd);
123 void freeBufHandle(uint32_t handle);
124 void removeFBsThreadRoutine();
125
126 void markInuseLayerLocked(const ExynosLayer *layer) REQUIRES(mMutex);
127 void destroyUnusedLayersLocked() REQUIRES(mMutex);
128 void destroySecureFramebufferLocked() REQUIRES(mMutex);
129
130 int mDrmFd = -1;
131
132 // mCachedLayerBuffers map keep the relationship between Layer and
133 // FBList. The map entry will be deleted once the layer is destroyed.
134 std::map<const ExynosLayer *, FBList> mCachedLayerBuffers;
135
136 // mCleanBuffers list keeps fbIds of destroyed layers. Those fbIds will
137 // be destroyed in mRmFBThread thread.
138 FBList mCleanBuffers;
139
140 // mCacheShrinkPending is set when we want to clean up unused layers
141 // in mCachedLayerBuffers. When the flag is set, mCachedLayersInuse will
142 // keep in-use layers in this frame update. Those unused layers will be
143 // freed at the end of the update.
144 // TODO: have a better way to maintain inuse layers
145 bool mCacheShrinkPending = false;
146 bool mHasSecureFramebuffer = false;
147 std::set<const ExynosLayer *> mCachedLayersInuse;
148
149 std::thread mRmFBThread;
150 bool mRmFBThreadRunning = false;
151 Condition mFlipDone;
152 Mutex mMutex;
153
154 static constexpr size_t MAX_CACHED_LAYERS = 16;
155 static constexpr size_t MAX_CACHED_BUFFERS_PER_LAYER = 32;
156 static constexpr size_t MAX_CACHED_SECURE_BUFFERS_PER_G2D_LAYER = 3;
157 };
158
isFramebuffer(const ExynosLayer * layer)159 inline bool isFramebuffer(const ExynosLayer *layer) {
160 return layer == nullptr;
161 }
162
163 template <class UnaryPredicate>
findCachedFbId(const ExynosLayer * layer,UnaryPredicate predicate)164 uint32_t FramebufferManager::findCachedFbId(const ExynosLayer *layer, UnaryPredicate predicate) {
165 Mutex::Autolock lock(mMutex);
166 markInuseLayerLocked(layer);
167 const auto &cachedBuffers = mCachedLayerBuffers[layer];
168 const auto it = std::find_if(cachedBuffers.begin(), cachedBuffers.end(), predicate);
169 return (it != cachedBuffers.end()) ? (*it)->fbId : 0;
170 }
171
172 class ExynosDisplayDrmInterface :
173 public ExynosDisplayInterface,
174 public VsyncCallback
175 {
176 public:
177 class DrmModeAtomicReq {
178 public:
179 DrmModeAtomicReq(ExynosDisplayDrmInterface *displayInterface);
180 ~DrmModeAtomicReq();
181
182 DrmModeAtomicReq(const DrmModeAtomicReq&) = delete;
183 DrmModeAtomicReq& operator=(const DrmModeAtomicReq&) = delete;
184
pset()185 drmModeAtomicReqPtr pset() { return mPset; };
savePset()186 void savePset() {
187 if (mSavedPset) {
188 drmModeAtomicFree(mSavedPset);
189 }
190 mSavedPset = drmModeAtomicDuplicate(mPset);
191 }
restorePset()192 void restorePset() {
193 if (mPset) {
194 drmModeAtomicFree(mPset);
195 }
196 mPset = mSavedPset;
197 mSavedPset = NULL;
198 }
199
setError(int err)200 void setError(int err) { mError = err; };
getError()201 int getError() { return mError; };
202 int32_t atomicAddProperty(const uint32_t id,
203 const DrmProperty &property,
204 uint64_t value, bool optional = false);
205 String8& dumpAtomicCommitInfo(String8 &result, bool debugPrint = false);
206 int commit(uint32_t flags, bool loggingForDebug = false);
addOldBlob(uint32_t blob_id)207 void addOldBlob(uint32_t blob_id) {
208 mOldBlobs.push_back(blob_id);
209 };
destroyOldBlobs()210 int destroyOldBlobs() {
211 for (auto &blob : mOldBlobs) {
212 int ret = mDrmDisplayInterface->mDrmDevice->DestroyPropertyBlob(blob);
213 if (ret) {
214 HWC_LOGE(mDrmDisplayInterface->mExynosDisplay,
215 "Failed to destroy old blob after commit %d", ret);
216 return ret;
217 }
218 }
219 mOldBlobs.clear();
220 return NO_ERROR;
221 };
222 private:
223 drmModeAtomicReqPtr mPset;
224 drmModeAtomicReqPtr mSavedPset;
225 int mError = 0;
226 ExynosDisplayDrmInterface *mDrmDisplayInterface = NULL;
227 /* Destroy old blobs after commit */
228 std::vector<uint32_t> mOldBlobs;
drmFd()229 int drmFd() const { return mDrmDisplayInterface->mDrmDevice->fd(); }
230 };
231 class ExynosVsyncCallback {
232 public:
enableVSync(bool enable)233 void enableVSync(bool enable) {
234 mVsyncEnabled = enable;
235 resetVsyncTimeStamp();
236 };
getVSyncEnabled()237 bool getVSyncEnabled() { return mVsyncEnabled; };
setDesiredVsyncPeriod(uint64_t period)238 void setDesiredVsyncPeriod(uint64_t period) {
239 mDesiredVsyncPeriod = period;
240 resetVsyncTimeStamp();
241 };
getDesiredVsyncPeriod()242 uint64_t getDesiredVsyncPeriod() { return mDesiredVsyncPeriod;};
getVsyncTimeStamp()243 uint64_t getVsyncTimeStamp() { return mVsyncTimeStamp; };
getVsyncPeriod()244 uint64_t getVsyncPeriod() { return mVsyncPeriod; };
245 bool Callback(int display, int64_t timestamp);
resetVsyncTimeStamp()246 void resetVsyncTimeStamp() { mVsyncTimeStamp = 0; };
resetDesiredVsyncPeriod()247 void resetDesiredVsyncPeriod() { mDesiredVsyncPeriod = 0;};
248 private:
249 bool mVsyncEnabled = false;
250 uint64_t mVsyncTimeStamp = 0;
251 uint64_t mVsyncPeriod = 0;
252 uint64_t mDesiredVsyncPeriod = 0;
253 };
254 void Callback(int display, int64_t timestamp) override;
255
256 ExynosDisplayDrmInterface(ExynosDisplay *exynosDisplay);
257 ~ExynosDisplayDrmInterface();
258 virtual void init(ExynosDisplay *exynosDisplay);
259 virtual int32_t setPowerMode(int32_t mode);
260 virtual int32_t setLowPowerMode() override;
isDozeModeAvailable()261 virtual bool isDozeModeAvailable() const {
262 return mDozeDrmMode.h_display() > 0 && mDozeDrmMode.v_display() > 0;
263 };
264 virtual int32_t setVsyncEnabled(uint32_t enabled);
265 virtual int32_t getDisplayConfigs(
266 uint32_t* outNumConfigs,
267 hwc2_config_t* outConfigs);
268 virtual void dumpDisplayConfigs();
269 virtual bool supportDataspace(int32_t dataspace);
270 virtual int32_t getColorModes(uint32_t* outNumModes, int32_t* outModes);
271 virtual int32_t setColorMode(int32_t mode);
272 virtual int32_t setActiveConfig(hwc2_config_t config);
273 virtual int32_t setCursorPositionAsync(uint32_t x_pos, uint32_t y_pos);
274 virtual int32_t updateHdrCapabilities();
275 virtual int32_t deliverWinConfigData();
276 virtual int32_t clearDisplay(bool needModeClear = false);
277 virtual int32_t disableSelfRefresh(uint32_t disable);
278 virtual int32_t setForcePanic();
getDisplayFd()279 virtual int getDisplayFd() { return mDrmDevice->fd(); };
280 virtual int32_t initDrmDevice(DrmDevice *drmDevice);
281 virtual uint32_t getDrmDisplayId(uint32_t type, uint32_t index);
getMaxWindowNum()282 virtual uint32_t getMaxWindowNum() { return mMaxWindowNum; };
283 virtual int32_t getReadbackBufferAttributes(int32_t* /*android_pixel_format_t*/ outFormat,
284 int32_t* /*android_dataspace_t*/ outDataspace);
285 virtual int32_t getDisplayIdentificationData(uint8_t* outPort,
286 uint32_t* outDataSize, uint8_t* outData);
287
288 /* For HWC 2.4 APIs */
289 virtual int32_t getDisplayVsyncPeriod(
290 hwc2_vsync_period_t* outVsyncPeriod);
291 virtual int32_t getConfigChangeDuration();
292 virtual int32_t getVsyncAppliedTime(hwc2_config_t config,
293 int64_t* actualChangeTime);
294 virtual int32_t setActiveConfigWithConstraints(
295 hwc2_config_t config, bool test = false);
296
setDisplayColorSetting(ExynosDisplayDrmInterface::DrmModeAtomicReq __unused & drmReq)297 virtual int32_t setDisplayColorSetting(
298 ExynosDisplayDrmInterface::DrmModeAtomicReq __unused &drmReq) {
299 return NO_ERROR;
300 }
setPlaneColorSetting(ExynosDisplayDrmInterface::DrmModeAtomicReq & drmReq,const std::unique_ptr<DrmPlane> & plane,const exynos_win_config_data & config,uint32_t & solidColor)301 virtual int32_t setPlaneColorSetting(
302 ExynosDisplayDrmInterface::DrmModeAtomicReq &drmReq,
303 const std::unique_ptr<DrmPlane> &plane,
304 const exynos_win_config_data& config,
305 uint32_t &solidColor)
306 { return NO_ERROR;};
307 virtual void destroyLayer(ExynosLayer *layer) override;
308
309 /* For HWC 3.0 APIs */
310 virtual int32_t getDisplayIdleTimerSupport(bool &outSupport);
311 virtual int32_t getDefaultModeId(int32_t *modeId) override;
312
313 virtual int32_t waitVBlank();
getDesiredRefreshRate()314 float getDesiredRefreshRate() { return mDesiredModeState.mode.v_refresh(); }
315
316 /* For Histogram */
setDisplayHistogramSetting(ExynosDisplayDrmInterface::DrmModeAtomicReq & drmReq)317 virtual int32_t setDisplayHistogramSetting(
318 ExynosDisplayDrmInterface::DrmModeAtomicReq &drmReq) {
319 return NO_ERROR;
320 }
getFrameCount()321 int32_t getFrameCount() { return mFrameCounter; }
registerHistogramInfo(const std::shared_ptr<IDLHistogram> & info)322 virtual void registerHistogramInfo(const std::shared_ptr<IDLHistogram> &info) { return; }
setHistogramControl(hidl_histogram_control_t enabled)323 virtual int32_t setHistogramControl(hidl_histogram_control_t enabled) { return NO_ERROR; }
setHistogramData(void * bin)324 virtual int32_t setHistogramData(void *bin) { return NO_ERROR; }
getActiveModeHDisplay()325 int32_t getActiveModeHDisplay() { return mActiveModeState.mode.h_display(); }
getActiveModeVDisplay()326 int32_t getActiveModeVDisplay() { return mActiveModeState.mode.v_display(); }
panelHsize()327 int32_t panelHsize() { return mPanelResolutionHsize; }
panelVsize()328 int32_t panelVsize() { return mPanelResolutionVsize; }
329 int32_t getPanelResolution();
getCrtcId()330 uint32_t getCrtcId() { return mDrmCrtc->id(); }
331
332 protected:
333 enum class HalMipiSyncType : uint32_t {
334 HAL_MIPI_CMD_SYNC_REFRESH_RATE = 0,
335 HAL_MIPI_CMD_SYNC_LHBM,
336 HAL_MIPI_CMD_SYNC_GHBM,
337 HAL_MIPI_CMD_SYNC_BL,
338 };
339
340 struct ModeState {
341 enum ModeStateType {
342 MODE_STATE_NONE = 0U,
343 MODE_STATE_REFRESH_RATE = 1U << 0,
344 MODE_STATE_RESOLUTION = 1U << 1,
345 MODE_STATE_FORCE_MODE_SET = 1U << 2,
346 };
347 DrmMode mode;
348 uint32_t blob_id = 0;
349 uint32_t old_blob_id = 0;
setModeModeState350 void setMode(const DrmMode newMode, const uint32_t modeBlob,
351 DrmModeAtomicReq &drmReq) {
352 if (newMode.v_refresh() != mode.v_refresh()) {
353 mModeState |= ModeStateType::MODE_STATE_REFRESH_RATE;
354 }
355 if (isFullModeSwitch(newMode)) {
356 mModeState |= ModeStateType::MODE_STATE_RESOLUTION;
357 }
358
359 drmReq.addOldBlob(old_blob_id);
360 mode = newMode;
361 old_blob_id = blob_id;
362 blob_id = modeBlob;
363 };
resetModeState364 void reset() {
365 *this = {};
366 };
applyModeState367 void apply(ModeState &toModeState, DrmModeAtomicReq &drmReq) {
368 toModeState.setMode(mode, blob_id, drmReq);
369 drmReq.addOldBlob(old_blob_id);
370 reset();
371 };
372
373 int32_t mModeState = ModeStateType::MODE_STATE_NONE;
forceModeSetModeState374 void forceModeSet() { mModeState |= ModeStateType::MODE_STATE_FORCE_MODE_SET; }
clearPendingModeStateModeState375 void clearPendingModeState() { mModeState = ModeStateType::MODE_STATE_NONE; }
needsModeSetModeState376 bool needsModeSet() const { return mModeState != ModeStateType::MODE_STATE_NONE; }
isSeamlessModeState377 bool isSeamless() const { return !(mModeState & ModeStateType::MODE_STATE_RESOLUTION); }
isFullModeSwitchModeState378 bool isFullModeSwitch(const DrmMode &newMode) {
379 if ((mode.h_display() != newMode.h_display()) ||
380 (mode.v_display() != newMode.v_display()))
381 return true;
382 return false;
383 }
384 };
385 int32_t createModeBlob(const DrmMode &mode, uint32_t &modeBlob);
386 int32_t setDisplayMode(DrmModeAtomicReq &drmReq, const uint32_t modeBlob);
387 int32_t clearDisplayMode(DrmModeAtomicReq &drmReq);
388 int32_t clearDisplayPlanes(DrmModeAtomicReq &drmReq);
389 int32_t chosePreferredConfig();
390 int getDeconChannel(ExynosMPP *otfMPP);
391 /*
392 * This function adds FB and gets new fb id if fbId is 0,
393 * if fbId is not 0, this reuses fbId.
394 */
395 int32_t setupCommitFromDisplayConfig(DrmModeAtomicReq &drmReq,
396 const exynos_win_config_data &config,
397 const uint32_t configIndex,
398 const std::unique_ptr<DrmPlane> &plane,
399 uint32_t &fbId);
400
401 int32_t setupPartialRegion(DrmModeAtomicReq &drmReq);
402 void parseBlendEnums(const DrmProperty &property);
403 void parseStandardEnums(const DrmProperty &property);
404 void parseTransferEnums(const DrmProperty &property);
405 void parseRangeEnums(const DrmProperty &property);
406 void parseColorModeEnums(const DrmProperty &property);
407 void parseMipiSyncEnums(const DrmProperty &property);
408 void updateMountOrientation();
409
410 int32_t setupWritebackCommit(DrmModeAtomicReq &drmReq);
411 int32_t clearWritebackCommit(DrmModeAtomicReq &drmReq);
412
413 private:
414 int32_t updateColorSettings(DrmModeAtomicReq &drmReq, uint64_t dqeEnabled);
415 int32_t getLowPowerDrmModeModeInfo();
416 int32_t setActiveDrmMode(DrmMode const &mode);
setMaxWindowNum(uint32_t num)417 void setMaxWindowNum(uint32_t num) { mMaxWindowNum = num; };
418
419 protected:
420 struct PartialRegionState {
421 struct drm_clip_rect partial_rect = {0, 0, 0, 0};
422 uint32_t blob_id = 0;
isUpdatedPartialRegionState423 bool isUpdated(drm_clip_rect rect) {
424 return ((partial_rect.x1 != rect.x1) ||
425 (partial_rect.y1 != rect.y1) ||
426 (partial_rect.x2 != rect.x2) ||
427 (partial_rect.y2 != rect.y2));
428 };
429 };
430
431 struct BlockingRegionState {
432 struct decon_win_rect mRegion;
433 uint32_t mBlobId = 0;
434
435 inline bool operator==(const decon_win_rect &rhs) const {
436 return mRegion.x == rhs.x && mRegion.y == rhs.y && mRegion.w == rhs.w &&
437 mRegion.h == rhs.h;
438 }
439 inline bool operator!=(const decon_win_rect &rhs) const { return !(*this == rhs); }
440 };
441
442 class DrmReadbackInfo {
443 public:
444 void init(DrmDevice *drmDevice, uint32_t displayId);
~DrmReadbackInfo()445 ~DrmReadbackInfo() {
446 if (mDrmDevice == NULL)
447 return;
448 if (mOldFbId > 0)
449 drmModeRmFB(mDrmDevice->fd(), mOldFbId);
450 if (mFbId > 0)
451 drmModeRmFB(mDrmDevice->fd(), mFbId);
452 }
getWritebackConnector()453 DrmConnector* getWritebackConnector() { return mWritebackConnector; };
setFbId(uint32_t fbId)454 void setFbId(uint32_t fbId) {
455 if ((mDrmDevice != NULL) && (mOldFbId > 0))
456 drmModeRmFB(mDrmDevice->fd(), mOldFbId);
457 mOldFbId = mFbId;
458 mFbId = fbId;
459 }
460 void pickFormatDataspace();
461 static constexpr uint32_t PREFERRED_READBACK_FORMAT =
462 HAL_PIXEL_FORMAT_RGBA_8888;
463 uint32_t mReadbackFormat = HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
464 bool mNeedClearReadbackCommit = false;
465 private:
466 DrmDevice *mDrmDevice = NULL;
467 DrmConnector *mWritebackConnector = NULL;
468 uint32_t mFbId = 0;
469 uint32_t mOldFbId = 0;
470 std::vector<uint32_t> mSupportedFormats;
471 };
472 DrmDevice *mDrmDevice;
473 DrmCrtc *mDrmCrtc;
474 DrmConnector *mDrmConnector;
475 VSyncWorker mDrmVSyncWorker;
476 ExynosVsyncCallback mVsyncCallback;
477 ModeState mActiveModeState;
478 ModeState mDesiredModeState;
479 PartialRegionState mPartialRegionState;
480 BlockingRegionState mBlockState;
481 /* Mapping plane id to ExynosMPP, key is plane id */
482 std::unordered_map<uint32_t, ExynosMPP*> mExynosMPPsForPlane;
483
484 DrmEnumParser::MapHal2DrmEnum mBlendEnums;
485 DrmEnumParser::MapHal2DrmEnum mStandardEnums;
486 DrmEnumParser::MapHal2DrmEnum mTransferEnums;
487 DrmEnumParser::MapHal2DrmEnum mRangeEnums;
488 DrmEnumParser::MapHal2DrmEnum mColorModeEnums;
489 DrmEnumParser::MapHal2DrmEnum mMipiSyncEnums;
490
491 DrmReadbackInfo mReadbackInfo;
492 FramebufferManager mFBManager;
493
494 private:
495 int32_t getDisplayFakeEdid(uint8_t &outPort, uint32_t &outDataSize, uint8_t *outData);
496
497 DrmMode mDozeDrmMode;
498 uint32_t mMaxWindowNum = 0;
499 int32_t mFrameCounter = 0;
500 int32_t mPanelResolutionHsize = 0;
501 int32_t mPanelResolutionVsize = 0;
502 };
503
504 #endif
505