• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2015 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 #undef NDEBUG /* Required for assert to work */
18 
19 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
20 #define LOG_TAG "drmhwc"
21 
22 #include "DrmAtomicStateManager.h"
23 
24 #include <drm/drm_mode.h>
25 #include <sync/sync.h>
26 #include <utils/Trace.h>
27 
28 #include <cassert>
29 
30 #include "drm/DrmCrtc.h"
31 #include "drm/DrmDevice.h"
32 #include "drm/DrmPlane.h"
33 #include "drm/DrmUnique.h"
34 #include "utils/log.h"
35 
36 namespace android {
37 
CreateInstance(DrmDisplayPipeline * pipe)38 auto DrmAtomicStateManager::CreateInstance(DrmDisplayPipeline *pipe)
39     -> std::shared_ptr<DrmAtomicStateManager> {
40   auto dasm = std::shared_ptr<DrmAtomicStateManager>(
41       new DrmAtomicStateManager());
42 
43   dasm->pipe_ = pipe;
44   std::thread(&DrmAtomicStateManager::ThreadFn, dasm.get(), dasm).detach();
45 
46   return dasm;
47 }
48 
49 // NOLINTNEXTLINE (readability-function-cognitive-complexity): Fixme
CommitFrame(AtomicCommitArgs & args)50 auto DrmAtomicStateManager::CommitFrame(AtomicCommitArgs &args) -> int {
51   // NOLINTNEXTLINE(misc-const-correctness)
52   ATRACE_CALL();
53 
54   if (args.active && *args.active == active_frame_state_.crtc_active_state) {
55     /* Don't set the same state twice */
56     args.active.reset();
57   }
58 
59   if (!args.HasInputs()) {
60     /* nothing to do */
61     return 0;
62   }
63 
64   if (!active_frame_state_.crtc_active_state) {
65     /* Force activate display */
66     args.active = true;
67   }
68 
69   auto new_frame_state = NewFrameState();
70 
71   auto *drm = pipe_->device;
72   auto *connector = pipe_->connector->Get();
73   auto *crtc = pipe_->crtc->Get();
74 
75   auto pset = MakeDrmModeAtomicReqUnique();
76   if (!pset) {
77     ALOGE("Failed to allocate property set");
78     return -ENOMEM;
79   }
80 
81   int out_fence = -1;
82   if (!args.writeback_fb) {
83     if (!crtc->GetOutFencePtrProperty().  //
84          AtomicSet(*pset, uint64_t(&out_fence))) {
85       return -EINVAL;
86     }
87   } else {
88     if (!connector->GetWritebackOutFenceProperty().  //
89          AtomicSet(*pset, uint64_t(&out_fence))) {
90       return -EINVAL;
91     }
92 
93     if (!connector->GetWritebackFbIdProperty().  //
94          AtomicSet(*pset, args.writeback_fb->GetFbId())) {
95       return -EINVAL;
96     }
97 
98     if (args.writeback_release_fence) {
99       sync_wait(*args.writeback_release_fence, -1);
100       args.writeback_release_fence.reset();
101     }
102   }
103 
104   bool nonblock = !args.blocking;
105 
106   if (args.active) {
107     nonblock = false;
108     new_frame_state.crtc_active_state = *args.active;
109     if (!crtc->GetActiveProperty().AtomicSet(*pset, *args.active ? 1 : 0) ||
110         !connector->GetCrtcIdProperty().AtomicSet(*pset, crtc->GetId())) {
111       return -EINVAL;
112     }
113   }
114 
115   if (args.display_mode) {
116     new_frame_state.mode_blob = args.display_mode.value().CreateModeBlob(*drm);
117 
118     if (!new_frame_state.mode_blob) {
119       ALOGE("Failed to create mode_blob");
120       return -EINVAL;
121     }
122 
123     auto raw_mode = args.display_mode.value().GetRawMode();
124     whole_display_rect_.i_rect = {0, 0, raw_mode.hdisplay, raw_mode.vdisplay};
125 
126     if (!crtc->GetModeProperty().AtomicSet(*pset, *new_frame_state.mode_blob)) {
127       return -EINVAL;
128     }
129   }
130 
131   if (args.color_matrix && crtc->GetCtmProperty()) {
132     auto blob = drm->RegisterUserPropertyBlob(args.color_matrix.get(),
133                                               sizeof(drm_color_ctm));
134     new_frame_state.ctm_blob = std::move(blob);
135 
136     if (!new_frame_state.ctm_blob) {
137       ALOGE("Failed to create CTM blob");
138       return -EINVAL;
139     }
140 
141     if (!crtc->GetCtmProperty().AtomicSet(*pset, *new_frame_state.ctm_blob))
142       return -EINVAL;
143   }
144 
145   if (args.colorspace && connector->GetColorspaceProperty()) {
146     if (!connector->GetColorspaceProperty()
147              .AtomicSet(*pset, connector->GetColorspacePropertyValue(
148                                    *args.colorspace)))
149       return -EINVAL;
150   }
151 
152   if (args.content_type && connector->GetContentTypeProperty()) {
153     if (!connector->GetContentTypeProperty().AtomicSet(*pset,
154                                                        *args.content_type))
155       return -EINVAL;
156   }
157 
158   if (args.hdr_metadata && connector->GetHdrOutputMetadataProperty()) {
159     auto blob = drm->RegisterUserPropertyBlob(args.hdr_metadata.get(),
160                                               sizeof(hdr_output_metadata));
161     new_frame_state.hdr_metadata_blob = std::move(blob);
162     if (!new_frame_state.hdr_metadata_blob) {
163       ALOGE("Failed to create %s blob",
164             connector->GetHdrOutputMetadataProperty().GetName().c_str());
165       return -EINVAL;
166     }
167 
168     if (!connector->GetHdrOutputMetadataProperty()
169              .AtomicSet(*pset, *new_frame_state.hdr_metadata_blob))
170       return -EINVAL;
171   }
172 
173   if (args.min_bpc && connector->GetMinBpcProperty()) {
174     int err;
175     uint64_t range_min, range_max = 0;
176     std::tie(err, range_min) = connector->GetMinBpcProperty().RangeMin();
177     if (err)
178       return err;
179     std::tie(err, range_max) = connector->GetMinBpcProperty().RangeMax();
180     if (err)
181       return err;
182 
183     // Adjust requested min bpc to be within the property range
184     int32_t min_bpc_val = std::max(args.min_bpc.value(), static_cast<int32_t>(range_min));
185     min_bpc_val = std::min(min_bpc_val, static_cast<int32_t>(range_max));
186     if (!connector->GetMinBpcProperty().AtomicSet(*pset, min_bpc_val))
187       return -EINVAL;
188   }
189 
190   auto unused_planes = new_frame_state.used_planes;
191 
192   if (args.composition) {
193     new_frame_state.used_planes.clear();
194 
195     for (auto &joining : args.composition->plan) {
196       DrmPlane *plane = joining.plane->Get();
197       LayerData &layer = joining.layer;
198 
199       new_frame_state.used_framebuffers.emplace_back(layer.fb);
200       new_frame_state.used_planes.emplace_back(joining.plane);
201 
202       /* Remove from 'unused' list, since plane is re-used */
203       auto &v = unused_planes;
204       v.erase(std::remove(v.begin(), v.end(), joining.plane), v.end());
205 
206       if (plane->AtomicSetState(*pset, layer, joining.z_pos, crtc->GetId(),
207                                 whole_display_rect_) != 0) {
208         return -EINVAL;
209       }
210     }
211   }
212 
213   if (args.composition) {
214     for (auto &plane : unused_planes) {
215       if (plane->Get()->AtomicDisablePlane(*pset) != 0) {
216         return -EINVAL;
217       }
218     }
219   }
220 
221   uint32_t flags = DRM_MODE_ATOMIC_ALLOW_MODESET;
222 
223   if (args.test_only) {
224     return drmModeAtomicCommit(*drm->GetFd(), pset.get(),
225                                flags | DRM_MODE_ATOMIC_TEST_ONLY, drm);
226   }
227 
228   if (last_present_fence_) {
229     // NOLINTNEXTLINE(misc-const-correctness)
230     ATRACE_NAME("WaitPriorFramePresented");
231 
232     constexpr int kTimeoutMs = 500;
233     const int err = sync_wait(*last_present_fence_, kTimeoutMs);
234     if (err != 0) {
235       ALOGE("sync_wait(fd=%i) returned: %i (errno: %i)", *last_present_fence_,
236             err, errno);
237     }
238 
239     CleanupPriorFrameResources();
240   }
241 
242   if (nonblock) {
243     flags |= DRM_MODE_ATOMIC_NONBLOCK;
244   }
245 
246   auto err = drmModeAtomicCommit(*drm->GetFd(), pset.get(), flags, drm);
247 
248   if (err != 0) {
249     ALOGE("Failed to commit pset ret=%d\n", err);
250     return err;
251   }
252 
253   args.out_fence = MakeSharedFd(out_fence);
254 
255   if (nonblock) {
256     {
257       const std::unique_lock lock(mutex_);
258       last_present_fence_ = args.out_fence;
259       staged_frame_state_ = std::move(new_frame_state);
260       frames_staged_++;
261     }
262     cv_.notify_all();
263   } else {
264     active_frame_state_ = std::move(new_frame_state);
265   }
266 
267   return 0;
268 }
269 
ThreadFn(const std::shared_ptr<DrmAtomicStateManager> & dasm)270 void DrmAtomicStateManager::ThreadFn(
271     const std::shared_ptr<DrmAtomicStateManager> &dasm) {
272   int tracking_at_the_moment = -1;
273   auto &main_mutex = pipe_->device->GetResMan().GetMainLock();
274 
275   for (;;) {
276     SharedFd present_fence;
277 
278     {
279       std::unique_lock lk(mutex_);
280       cv_.wait(lk);
281 
282       if (exit_thread_ || dasm.use_count() == 1)
283         break;
284 
285       if (frames_staged_ <= tracking_at_the_moment)
286         continue;
287 
288       tracking_at_the_moment = frames_staged_;
289 
290       present_fence = last_present_fence_;
291       if (!present_fence)
292         continue;
293     }
294 
295     {
296       // NOLINTNEXTLINE(misc-const-correctness)
297       ATRACE_NAME("AsyncWaitForBuffersSwap");
298       constexpr int kTimeoutMs = 500;
299       auto err = sync_wait(*present_fence, kTimeoutMs);
300       if (err != 0) {
301         ALOGE("sync_wait(fd=%i) returned: %i (errno: %i)", *present_fence, err,
302               errno);
303       }
304     }
305 
306     {
307       const std::unique_lock mlk(main_mutex);
308       const std::unique_lock lk(mutex_);
309       if (exit_thread_)
310         break;
311 
312       /* If resources is already cleaned-up by main thread, skip */
313       if (tracking_at_the_moment > frames_tracked_)
314         CleanupPriorFrameResources();
315     }
316   }
317 
318   ALOGI("DrmAtomicStateManager thread exit");
319 }
320 
CleanupPriorFrameResources()321 void DrmAtomicStateManager::CleanupPriorFrameResources() {
322   assert(frames_staged_ - frames_tracked_ == 1);
323   assert(last_present_fence_);
324 
325   // NOLINTNEXTLINE(misc-const-correctness)
326   ATRACE_NAME("CleanupPriorFrameResources");
327   frames_tracked_++;
328   active_frame_state_ = std::move(staged_frame_state_);
329   last_present_fence_ = {};
330 }
331 
ExecuteAtomicCommit(AtomicCommitArgs & args)332 auto DrmAtomicStateManager::ExecuteAtomicCommit(AtomicCommitArgs &args) -> int {
333   auto err = CommitFrame(args);
334 
335   if (!args.test_only) {
336     if (err != 0) {
337       ALOGE("Composite failed for pipeline %s",
338             pipe_->connector->Get()->GetName().c_str());
339       // Disable the hw used by the last active composition. This allows us to
340       // signal the release fences from that composition to avoid hanging.
341       AtomicCommitArgs cl_args{};
342       cl_args.composition = std::make_shared<DrmKmsPlan>();
343       if (CommitFrame(cl_args) != 0) {
344         ALOGE("Failed to clean-up active composition for pipeline %s",
345               pipe_->connector->Get()->GetName().c_str());
346       }
347       return err;
348     }
349   }
350 
351   return err;
352 }  // namespace android
353 
ActivateDisplayUsingDPMS()354 auto DrmAtomicStateManager::ActivateDisplayUsingDPMS() -> int {
355   return drmModeConnectorSetProperty(*pipe_->device->GetFd(),
356                                      pipe_->connector->Get()->GetId(),
357                                      pipe_->connector->Get()
358                                          ->GetDpmsProperty()
359                                          .GetId(),
360                                      DRM_MODE_DPMS_ON);
361 }
362 
363 }  // namespace android
364