summaryrefslogtreecommitdiff
path: root/chromium/ui/ozone/platform/drm/gpu/hardware_display_controller.cc
blob: ed387cbc7dc3b8ed0a65b405c60bb3006478d07b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/ozone/platform/drm/gpu/hardware_display_controller.h"

#include <drm.h>
#include <string.h>
#include <xf86drm.h>
#include <memory>
#include <utility>

#include "base/bind.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "base/trace_event/trace_event.h"
#include "third_party/libdrm/src/include/drm/drm_fourcc.h"
#include "third_party/skia/include/core/SkCanvas.h"
#include "third_party/skia/include/core/SkImage.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gfx/geometry/size.h"
#include "ui/gfx/gpu_fence.h"
#include "ui/gfx/linux/drm_util_linux.h"
#include "ui/gfx/native_pixmap.h"
#include "ui/gfx/presentation_feedback.h"
#include "ui/gfx/swap_result.h"
#include "ui/ozone/platform/drm/common/drm_util.h"
#include "ui/ozone/platform/drm/gpu/crtc_controller.h"
#include "ui/ozone/platform/drm/gpu/drm_device.h"
#include "ui/ozone/platform/drm/gpu/drm_dumb_buffer.h"
#include "ui/ozone/platform/drm/gpu/hardware_display_plane.h"
#include "ui/ozone/platform/drm/gpu/page_flip_request.h"

// Vendor ID for downstream, interim ChromeOS specific modifiers.
#define DRM_FORMAT_MOD_VENDOR_CHROMEOS 0xf0
// TODO(gurchetansingh) Remove once DRM_FORMAT_MOD_ARM_AFBC is used by all
// kernels and allocators.
#define DRM_FORMAT_MOD_CHROMEOS_ROCKCHIP_AFBC fourcc_mod_code(CHROMEOS, 1)

namespace ui {

namespace {

void CompletePageFlip(
    base::WeakPtr<HardwareDisplayController> hardware_display_controller_,
    PresentationOnceCallback callback,
    DrmOverlayPlaneList plane_list,
    const gfx::PresentationFeedback& presentation_feedback) {
  if (hardware_display_controller_) {
    hardware_display_controller_->OnPageFlipComplete(std::move(plane_list),
                                                     presentation_feedback);
  }
  std::move(callback).Run(presentation_feedback);
}

void DrawCursor(DrmDumbBuffer* cursor, const SkBitmap& image) {
  SkRect damage;
  image.getBounds(&damage);

  // Clear to transparent in case |image| is smaller than the canvas.
  SkCanvas* canvas = cursor->GetCanvas();
  canvas->clear(SK_ColorTRANSPARENT);
  canvas->drawImageRect(image.asImage(), damage, SkSamplingOptions());
}

}  // namespace

HardwareDisplayController::HardwareDisplayController(
    std::unique_ptr<CrtcController> controller,
    const gfx::Point& origin)
    : origin_(origin) {
  AddCrtc(std::move(controller));
  AllocateCursorBuffers();
}

HardwareDisplayController::~HardwareDisplayController() = default;

void HardwareDisplayController::GetModesetProps(
    CommitRequest* commit_request,
    const DrmOverlayPlaneList& modeset_planes,
    const drmModeModeInfo& mode) {
  GetModesetPropsForCrtcs(commit_request, modeset_planes,
                          /*use_current_crtc_mode=*/false, mode);
}

void HardwareDisplayController::GetEnableProps(
    CommitRequest* commit_request,
    const DrmOverlayPlaneList& modeset_planes) {
  // TODO(markyacoub): Simplify and remove the use of empty_mode.
  drmModeModeInfo empty_mode = {};
  GetModesetPropsForCrtcs(commit_request, modeset_planes,
                          /*use_current_crtc_mode=*/true, empty_mode);
}

void HardwareDisplayController::GetModesetPropsForCrtcs(
    CommitRequest* commit_request,
    const DrmOverlayPlaneList& modeset_planes,
    bool use_current_crtc_mode,
    const drmModeModeInfo& mode) {
  DCHECK(commit_request);

  GetDrmDevice()->plane_manager()->BeginFrame(&owned_hardware_planes_);

  for (const auto& controller : crtc_controllers_) {
    drmModeModeInfo modeset_mode =
        use_current_crtc_mode ? controller->mode() : mode;

    DrmOverlayPlaneList overlays = DrmOverlayPlane::Clone(modeset_planes);

    CrtcCommitRequest request = CrtcCommitRequest::EnableCrtcRequest(
        controller->crtc(), controller->connector(), modeset_mode, origin_,
        &owned_hardware_planes_, std::move(overlays));
    commit_request->push_back(std::move(request));
  }
}

void HardwareDisplayController::GetDisableProps(CommitRequest* commit_request) {
  for (const auto& controller : crtc_controllers_) {
    CrtcCommitRequest request = CrtcCommitRequest::DisableCrtcRequest(
        controller->crtc(), controller->connector(), &owned_hardware_planes_);
    commit_request->push_back(std::move(request));
  }
}

void HardwareDisplayController::UpdateState(
    const CrtcCommitRequest& crtc_request) {
  // Verify that the current state matches the requested state.
  if (crtc_request.should_enable() && IsEnabled()) {
    DCHECK(!crtc_request.overlays().empty());
    // TODO(markyacoub): This should be absorbed in the commit request.
    ResetCursor();
    OnModesetComplete(crtc_request.overlays());
  }
}

void HardwareDisplayController::SchedulePageFlip(
    DrmOverlayPlaneList plane_list,
    SwapCompletionOnceCallback submission_callback,
    PresentationOnceCallback presentation_callback) {
  DCHECK(!page_flip_request_);
  scoped_refptr<PageFlipRequest> page_flip_request =
      base::MakeRefCounted<PageFlipRequest>(GetRefreshInterval());
  std::unique_ptr<gfx::GpuFence> out_fence;

  bool status =
      ScheduleOrTestPageFlip(plane_list, page_flip_request, &out_fence);
  if (!status) {
    for (const auto& plane : plane_list) {
      // If the page flip failed and we see that the buffer has been allocated
      // before the latest modeset, it could mean it was an in-flight buffer
      // carrying an obsolete configuration.
      // Request a buffer reallocation to reflect the new change.
      if (plane.buffer &&
          plane.buffer->modeset_sequence_id_at_allocation() <
              plane.buffer->drm_device()->modeset_sequence_id()) {
        std::move(submission_callback)
            .Run(gfx::SwapResult::SWAP_NAK_RECREATE_BUFFERS, nullptr);
        std::move(presentation_callback)
            .Run(gfx::PresentationFeedback::Failure());
        return;
      }
    }
  }

  CHECK(status) << "SchedulePageFlip failed";

  if (page_flip_request->page_flip_count() == 0) {
    // Apparently, there was nothing to do. This probably should not be
    // able to happen but both CrtcController::AssignOverlayPlanes and
    // HardwareDisplayPlaneManagerLegacy::Commit appear to have cases
    // where we ACK without actually scheduling a page flip.
    std::move(submission_callback).Run(gfx::SwapResult::SWAP_ACK, nullptr);
    std::move(presentation_callback).Run(gfx::PresentationFeedback::Failure());
    return;
  }

  std::move(submission_callback)
      .Run(gfx::SwapResult::SWAP_ACK, std::move(out_fence));

  // Everything was submitted successfully, wait for asynchronous completion.
  page_flip_request->TakeCallback(
      base::BindOnce(&CompletePageFlip, weak_ptr_factory_.GetWeakPtr(),
                     std::move(presentation_callback), std::move(plane_list)));
  page_flip_request_ = std::move(page_flip_request);
}

bool HardwareDisplayController::TestPageFlip(
    const DrmOverlayPlaneList& plane_list) {
  return ScheduleOrTestPageFlip(plane_list, nullptr, nullptr);
}

bool HardwareDisplayController::ScheduleOrTestPageFlip(
    const DrmOverlayPlaneList& plane_list,
    scoped_refptr<PageFlipRequest> page_flip_request,
    std::unique_ptr<gfx::GpuFence>* out_fence) {
  TRACE_EVENT0("drm", "HDC::SchedulePageFlip");
  DCHECK(IsEnabled());

  // Ignore requests with no planes to schedule.
  if (plane_list.empty())
    return true;

  DrmOverlayPlaneList pending_planes = DrmOverlayPlane::Clone(plane_list);
  std::sort(pending_planes.begin(), pending_planes.end(),
            [](const DrmOverlayPlane& l, const DrmOverlayPlane& r) {
              return l.z_order < r.z_order;
            });
  GetDrmDevice()->plane_manager()->BeginFrame(&owned_hardware_planes_);

  bool status = true;
  for (const auto& controller : crtc_controllers_) {
    status &= controller->AssignOverlayPlanes(
        &owned_hardware_planes_, pending_planes, /*is_modesetting=*/false);
  }

  status &= GetDrmDevice()->plane_manager()->Commit(
      &owned_hardware_planes_, page_flip_request, out_fence);

  return status;
}

std::vector<uint64_t> HardwareDisplayController::GetFormatModifiers(
    uint32_t fourcc_format) const {
  if (crtc_controllers_.empty())
    return std::vector<uint64_t>();

  std::vector<uint64_t> modifiers =
      crtc_controllers_[0]->GetFormatModifiers(fourcc_format);

  for (size_t i = 1; i < crtc_controllers_.size(); ++i) {
    std::vector<uint64_t> other =
        crtc_controllers_[i]->GetFormatModifiers(fourcc_format);
    std::vector<uint64_t> intersection;

    std::set_intersection(modifiers.begin(), modifiers.end(), other.begin(),
                          other.end(), std::back_inserter(intersection));
    modifiers = std::move(intersection);
  }

  return modifiers;
}

std::vector<uint64_t> HardwareDisplayController::GetSupportedModifiers(
    uint32_t fourcc_format) const {
  if (preferred_format_modifier_.empty())
    return std::vector<uint64_t>();

  auto it = preferred_format_modifier_.find(fourcc_format);
  if (it != preferred_format_modifier_.end())
    return std::vector<uint64_t>{it->second};

  return GetFormatModifiers(fourcc_format);
}

std::vector<uint64_t>
HardwareDisplayController::GetFormatModifiersForTestModeset(
    uint32_t fourcc_format) {
  // If we're about to test, clear the current preferred modifier.
  preferred_format_modifier_.clear();

  std::vector<uint64_t> filtered_modifiers;
  const auto& modifiers = GetFormatModifiers(fourcc_format);
  for (auto modifier : modifiers) {
    // AFBC for modeset buffers doesn't work correctly, as we can't fill it with
    // a valid AFBC buffer. For now, don't use AFBC for modeset buffers.
    // TODO: Use AFBC for modeset buffers if it is available.
    // See https://crbug.com/852675.
    if (modifier != DRM_FORMAT_MOD_CHROMEOS_ROCKCHIP_AFBC) {
      filtered_modifiers.push_back(modifier);
    }
  }
  return filtered_modifiers;
}

void HardwareDisplayController::UpdatePreferredModiferForFormat(
    gfx::BufferFormat buffer_format,
    uint64_t modifier) {
  uint32_t fourcc_format = GetFourCCFormatFromBufferFormat(buffer_format);
  base::InsertOrAssign(preferred_format_modifier_, fourcc_format, modifier);

  uint32_t opaque_fourcc_format =
      GetFourCCFormatForOpaqueFramebuffer(buffer_format);
  base::InsertOrAssign(preferred_format_modifier_, opaque_fourcc_format,
                       modifier);
}

void HardwareDisplayController::MoveCursor(const gfx::Point& location) {
  cursor_location_ = location;
  UpdateCursorLocation();
}

void HardwareDisplayController::SetCursor(SkBitmap bitmap) {
  if (bitmap.drawsNothing()) {
    current_cursor_ = nullptr;
  } else {
    current_cursor_ = NextCursorBuffer();
    DrawCursor(current_cursor_, bitmap);
  }

  UpdateCursorImage();
}

void HardwareDisplayController::AddCrtc(
    std::unique_ptr<CrtcController> controller) {
  scoped_refptr<DrmDevice> drm = controller->drm();
  DCHECK(crtc_controllers_.empty() || drm == GetDrmDevice());

  // Check if this controller owns any planes and ensure we keep track of them.
  const std::vector<std::unique_ptr<HardwareDisplayPlane>>& all_planes =
      drm->plane_manager()->planes();
  uint32_t crtc = controller->crtc();
  for (const auto& plane : all_planes) {
    if (plane->in_use() && (plane->owning_crtc() == crtc))
      owned_hardware_planes_.old_plane_list.push_back(plane.get());
  }

  crtc_controllers_.push_back(std::move(controller));
}

std::unique_ptr<CrtcController> HardwareDisplayController::RemoveCrtc(
    const scoped_refptr<DrmDevice>& drm,
    uint32_t crtc) {
  auto controller_it = std::find_if(
      crtc_controllers_.begin(), crtc_controllers_.end(),
      [drm, crtc](const std::unique_ptr<CrtcController>& crtc_controller) {
        return crtc_controller->drm() == drm && crtc_controller->crtc() == crtc;
      });
  if (controller_it == crtc_controllers_.end())
    return nullptr;

  std::unique_ptr<CrtcController> controller(std::move(*controller_it));
  crtc_controllers_.erase(controller_it);

  // Move all the planes that have been committed in the last pageflip for this
  // CRTC at the end of the collection.
  auto first_plane_to_disable_it =
      std::partition(owned_hardware_planes_.old_plane_list.begin(),
                     owned_hardware_planes_.old_plane_list.end(),
                     [crtc](const HardwareDisplayPlane* plane) {
                       return plane->owning_crtc() != crtc;
                     });

  // Disable the planes enabled with the last commit on |crtc|, otherwise
  // the planes will be visible if the crtc is reassigned to another connector.
  HardwareDisplayPlaneList hardware_plane_list;
  std::copy(first_plane_to_disable_it,
            owned_hardware_planes_.old_plane_list.end(),
            std::back_inserter(hardware_plane_list.old_plane_list));
  drm->plane_manager()->DisableOverlayPlanes(&hardware_plane_list);

  // Remove the planes assigned to |crtc|.
  owned_hardware_planes_.old_plane_list.erase(
      first_plane_to_disable_it, owned_hardware_planes_.old_plane_list.end());

  return controller;
}

bool HardwareDisplayController::HasCrtc(const scoped_refptr<DrmDevice>& drm,
                                        uint32_t crtc) const {
  for (const auto& controller : crtc_controllers_) {
    if (controller->drm() == drm && controller->crtc() == crtc)
      return true;
  }

  return false;
}

bool HardwareDisplayController::IsMirrored() const {
  return crtc_controllers_.size() > 1;
}

bool HardwareDisplayController::IsEnabled() const {
  bool is_enabled = true;

  for (const auto& controller : crtc_controllers_)
    is_enabled &= controller->is_enabled();

  return is_enabled;
}

gfx::Size HardwareDisplayController::GetModeSize() const {
  // If there are multiple CRTCs they should all have the same size.
  return gfx::Size(crtc_controllers_[0]->mode().hdisplay,
                   crtc_controllers_[0]->mode().vdisplay);
}

base::TimeDelta HardwareDisplayController::GetRefreshInterval() const {
  // If there are multiple CRTCs they should all have the same refresh rate.
  float vrefresh = ModeRefreshRate(crtc_controllers_[0]->mode());
  return vrefresh ? base::TimeDelta::FromSeconds(1) / vrefresh
                  : base::TimeDelta();
}

base::TimeTicks HardwareDisplayController::GetTimeOfLastFlip() const {
  return time_of_last_flip_;
}

scoped_refptr<DrmDevice> HardwareDisplayController::GetDrmDevice() const {
  DCHECK(!crtc_controllers_.empty());
  // TODO(dnicoara) When we support mirroring across DRM devices, figure out
  // which device should be used for allocations.
  return crtc_controllers_[0]->drm();
}

void HardwareDisplayController::OnPageFlipComplete(
    DrmOverlayPlaneList pending_planes,
    const gfx::PresentationFeedback& presentation_feedback) {
  if (!page_flip_request_)
    return;  // Modeset occured during this page flip.
  time_of_last_flip_ = presentation_feedback.timestamp;
  current_planes_ = std::move(pending_planes);
  for (const auto& controller : crtc_controllers_) {
    GetDrmDevice()->plane_manager()->ResetModesetStateForCrtc(
        controller->crtc());
  }
  page_flip_request_ = nullptr;
}

void HardwareDisplayController::OnModesetComplete(
    const DrmOverlayPlaneList& modeset_planes) {
  // Modesetting is blocking so it has an immediate effect. We can assume that
  // the current planes have been updated. However, if a page flip is still
  // pending, set the pending planes to the same values so that the callback
  // keeps the correct state.
  page_flip_request_ = nullptr;
  owned_hardware_planes_.legacy_page_flips.clear();
  current_planes_ = DrmOverlayPlane::Clone(modeset_planes);
  time_of_last_flip_ = base::TimeTicks::Now();
}

void HardwareDisplayController::AllocateCursorBuffers() {
  TRACE_EVENT0("drm", "HDC::AllocateCursorBuffers");
  gfx::Size max_cursor_size = GetMaximumCursorSize(GetDrmDevice()->get_fd());
  SkImageInfo info = SkImageInfo::MakeN32Premul(max_cursor_size.width(),
                                                max_cursor_size.height());
  for (size_t i = 0; i < base::size(cursor_buffers_); ++i) {
    cursor_buffers_[i] = std::make_unique<DrmDumbBuffer>(GetDrmDevice());
    // Don't register a framebuffer for cursors since they are special (they
    // aren't modesetting buffers and drivers may fail to register them due to
    // their small sizes).
    if (!cursor_buffers_[i]->Initialize(info)) {
      LOG(FATAL) << "Failed to initialize cursor buffer";
      return;
    }
  }
}

DrmDumbBuffer* HardwareDisplayController::NextCursorBuffer() {
  ++cursor_frontbuffer_;
  cursor_frontbuffer_ %= base::size(cursor_buffers_);
  return cursor_buffers_[cursor_frontbuffer_].get();
}

void HardwareDisplayController::UpdateCursorImage() {
  uint32_t handle = 0;
  gfx::Size size;

  if (current_cursor_) {
    handle = current_cursor_->GetHandle();
    size = current_cursor_->GetSize();
  }

  for (const auto& controller : crtc_controllers_)
    controller->SetCursor(handle, size);
}

void HardwareDisplayController::UpdateCursorLocation() {
  for (const auto& controller : crtc_controllers_)
    controller->MoveCursor(cursor_location_);
}

void HardwareDisplayController::ResetCursor() {
  UpdateCursorLocation();
  UpdateCursorImage();
}

}  // namespace ui