drm_output.cpp 36.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
/********************************************************************
 KWin - the KDE window manager
 This file is part of the KDE project.

Copyright (C) 2015 Martin Gräßlin <mgraesslin@kde.org>

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
*********************************************************************/
#include "drm_output.h"
#include "drm_backend.h"
22 23 24 25 26
#include "drm_object_plane.h"
#include "drm_object_crtc.h"
#include "drm_object_connector.h"

#include <errno.h>
27 28

#include "composite.h"
29
#include "logind.h"
30
#include "logging.h"
31
#include "main.h"
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
#include "screens_drm.h"
#include "wayland_server.h"
// KWayland
#include <KWayland/Server/display.h>
#include <KWayland/Server/output_interface.h>
#include <KWayland/Server/outputchangeset.h>
#include <KWayland/Server/outputdevice_interface.h>
#include <KWayland/Server/outputmanagement_interface.h>
#include <KWayland/Server/outputconfiguration_interface.h>
// KF5
#include <KConfigGroup>
#include <KLocalizedString>
#include <KSharedConfig>
// Qt
#include <QCryptographicHash>
// drm
#include <xf86drm.h>
#include <xf86drmMode.h>
#include <libdrm/drm_mode.h>


namespace KWin
{

DrmOutput::DrmOutput(DrmBackend *backend)
    : QObject()
    , m_backend(backend)
{
}

DrmOutput::~DrmOutput()
{
    hideCursor();
65
    m_crtc->blank();
66 67 68 69 70 71 72 73 74 75 76 77 78 79

    if (m_primaryPlane) {
        // TODO: when having multiple planes, also clean up these
        m_primaryPlane->setOutput(nullptr);

        if (m_backend->deleteBufferAfterPageFlip()) {
            delete m_primaryPlane->current();
        }
        m_primaryPlane->setCurrent(nullptr);
    }

    m_crtc->setOutput(nullptr);
    m_conn->setOutput(nullptr);

80 81 82 83
    delete m_waylandOutput.data();
    delete m_waylandOutputDevice.data();
}

84
void DrmOutput::releaseGbm()
85
{
86 87
    if (DrmBuffer *b = m_crtc->current()) {
        b->releaseGbm();
88
    }
89 90
    if (m_primaryPlane && m_primaryPlane->current()) {
        m_primaryPlane->current()->releaseGbm();
91 92 93
    }
}

94 95
void DrmOutput::hideCursor()
{
96
    drmModeSetCursor(m_backend->fd(), m_crtc->id(), 0, 0, 0);
97 98
}

Roman Gilg's avatar
Roman Gilg committed
99
void DrmOutput::showCursor(DrmDumbBuffer *c)
100 101
{
    const QSize &s = c->size();
102
    drmModeSetCursor(m_backend->fd(), m_crtc->id(), c->handle(), s.width(), s.height());
103 104 105 106
}

void DrmOutput::moveCursor(const QPoint &globalPos)
{
107
    const QPoint p = ((globalPos - m_globalPos) * m_scale) - m_backend->softwareCursorHotspot();
108
    drmModeMoveCursor(m_backend->fd(), m_crtc->id(), p.x(), p.y());
109 110
}

David Edmundson's avatar
David Edmundson committed
111
QSize DrmOutput::pixelSize() const
112
{
113 114 115
    if (m_orientation == Qt::PortraitOrientation || m_orientation == Qt::InvertedPortraitOrientation) {
        return QSize(m_mode.vdisplay, m_mode.hdisplay);
    }
116 117 118
    return QSize(m_mode.hdisplay, m_mode.vdisplay);
}

119 120 121 122 123 124 125 126
QSize DrmOutput::physicalSize() const
{
    if (m_orientation == Qt::PortraitOrientation || m_orientation == Qt::InvertedPortraitOrientation) {
        return QSize(m_physicalSize.height(), m_physicalSize.width());
    }
    return m_physicalSize;
}

127 128
QRect DrmOutput::geometry() const
{
David Edmundson's avatar
David Edmundson committed
129
    return QRect(m_globalPos, pixelSize() / scale());
130 131
}

David Edmundson's avatar
David Edmundson committed
132 133 134 135 136 137
qreal DrmOutput::scale() const
{
    return m_scale;
}


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
static KWayland::Server::OutputInterface::DpmsMode toWaylandDpmsMode(DrmOutput::DpmsMode mode)
{
    using namespace KWayland::Server;
    switch (mode) {
    case DrmOutput::DpmsMode::On:
        return OutputInterface::DpmsMode::On;
    case DrmOutput::DpmsMode::Standby:
        return OutputInterface::DpmsMode::Standby;
    case DrmOutput::DpmsMode::Suspend:
        return OutputInterface::DpmsMode::Suspend;
    case DrmOutput::DpmsMode::Off:
        return OutputInterface::DpmsMode::Off;
    default:
        Q_UNREACHABLE();
    }
}

static DrmOutput::DpmsMode fromWaylandDpmsMode(KWayland::Server::OutputInterface::DpmsMode wlMode)
{
    using namespace KWayland::Server;
    switch (wlMode) {
    case OutputInterface::DpmsMode::On:
        return DrmOutput::DpmsMode::On;
    case OutputInterface::DpmsMode::Standby:
        return DrmOutput::DpmsMode::Standby;
    case OutputInterface::DpmsMode::Suspend:
        return DrmOutput::DpmsMode::Suspend;
    case OutputInterface::DpmsMode::Off:
        return DrmOutput::DpmsMode::Off;
    default:
        Q_UNREACHABLE();
    }
}

172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192
static QHash<int, QByteArray> s_connectorNames = {
    {DRM_MODE_CONNECTOR_Unknown, QByteArrayLiteral("Unknown")},
    {DRM_MODE_CONNECTOR_VGA, QByteArrayLiteral("VGA")},
    {DRM_MODE_CONNECTOR_DVII, QByteArrayLiteral("DVI-I")},
    {DRM_MODE_CONNECTOR_DVID, QByteArrayLiteral("DVI-D")},
    {DRM_MODE_CONNECTOR_DVIA, QByteArrayLiteral("DVI-A")},
    {DRM_MODE_CONNECTOR_Composite, QByteArrayLiteral("Composite")},
    {DRM_MODE_CONNECTOR_SVIDEO, QByteArrayLiteral("SVIDEO")},
    {DRM_MODE_CONNECTOR_LVDS, QByteArrayLiteral("LVDS")},
    {DRM_MODE_CONNECTOR_Component, QByteArrayLiteral("Component")},
    {DRM_MODE_CONNECTOR_9PinDIN, QByteArrayLiteral("DIN")},
    {DRM_MODE_CONNECTOR_DisplayPort, QByteArrayLiteral("DP")},
    {DRM_MODE_CONNECTOR_HDMIA, QByteArrayLiteral("HDMI-A")},
    {DRM_MODE_CONNECTOR_HDMIB, QByteArrayLiteral("HDMI-B")},
    {DRM_MODE_CONNECTOR_TV, QByteArrayLiteral("TV")},
    {DRM_MODE_CONNECTOR_eDP, QByteArrayLiteral("eDP")},
    {DRM_MODE_CONNECTOR_VIRTUAL, QByteArrayLiteral("Virtual")},
    {DRM_MODE_CONNECTOR_DSI, QByteArrayLiteral("DSI")}
};


193
bool DrmOutput::init(drmModeConnector *connector)
194 195 196 197
{
    initEdid(connector);
    initDpms(connector);
    initUuid();
198 199 200 201
    if (m_backend->atomicModeSetting()) {
        if (!initPrimaryPlane()) {
            return false;
        }
202
    } else if (!m_crtc->blank()) {
203 204
        return false;
    }
205

206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
    setDpms(DpmsMode::On);
    if (!m_waylandOutput.isNull()) {
        delete m_waylandOutput.data();
        m_waylandOutput.clear();
    }
    m_waylandOutput = waylandServer()->display()->createOutput();
    if (!m_waylandOutputDevice.isNull()) {
        delete m_waylandOutputDevice.data();
        m_waylandOutputDevice.clear();
    }
    m_waylandOutputDevice = waylandServer()->display()->createOutputDevice();
    m_waylandOutputDevice->setUuid(m_uuid);

    if (!m_edid.eisaId.isEmpty()) {
        m_waylandOutput->setManufacturer(QString::fromLatin1(m_edid.eisaId));
    } else {
        m_waylandOutput->setManufacturer(i18n("unknown"));
    }
    m_waylandOutputDevice->setManufacturer(m_waylandOutput->manufacturer());

226 227 228
    QString connectorName = s_connectorNames.value(connector->connector_type, QByteArrayLiteral("Unknown"));
    QString modelName;

229 230 231 232 233 234
    if (!m_edid.monitorName.isEmpty()) {
        QString model = QString::fromLatin1(m_edid.monitorName);
        if (!m_edid.serialNumber.isEmpty()) {
            model.append('/');
            model.append(QString::fromLatin1(m_edid.serialNumber));
        }
235
        modelName = model;
236
    } else if (!m_edid.serialNumber.isEmpty()) {
237
        modelName = QString::fromLatin1(m_edid.serialNumber);
238
    } else {
239
        modelName = i18n("unknown");
240 241
    }

242 243 244
    m_waylandOutput->setModel(connectorName + QStringLiteral("-") + QString::number(connector->connector_type_id) + QStringLiteral("-") + modelName);
    m_waylandOutputDevice->setModel(m_waylandOutput->model());
    
245 246 247 248 249 250 251 252 253 254 255 256
    QSize physicalSize = !m_edid.physicalSize.isEmpty() ? m_edid.physicalSize : QSize(connector->mmWidth, connector->mmHeight);
    // the size might be completely borked. E.g. Samsung SyncMaster 2494HS reports 160x90 while in truth it's 520x292
    // as this information is used to calculate DPI info, it's going to result in everything being huge
    const QByteArray unknown = QByteArrayLiteral("unkown");
    KConfigGroup group = kwinApp()->config()->group("EdidOverwrite").group(m_edid.eisaId.isEmpty() ? unknown : m_edid.eisaId)
                                                       .group(m_edid.monitorName.isEmpty() ? unknown : m_edid.monitorName)
                                                       .group(m_edid.serialNumber.isEmpty() ? unknown : m_edid.serialNumber);
    if (group.hasKey("PhysicalSize")) {
        const QSize overwriteSize = group.readEntry("PhysicalSize", physicalSize);
        qCWarning(KWIN_DRM) << "Overwriting monitor physical size for" << m_edid.eisaId << "/" << m_edid.monitorName << "/" << m_edid.serialNumber << " from " << physicalSize << "to " << overwriteSize;
        physicalSize = overwriteSize;
    }
257
    m_physicalSize = physicalSize;
258 259 260 261 262
    m_waylandOutput->setPhysicalSize(physicalSize);
    m_waylandOutputDevice->setPhysicalSize(physicalSize);

    // read in mode information
    for (int i = 0; i < connector->count_modes; ++i) {
263 264 265 266

        // TODO: in AMS here we could read and store for later every mode's blob_id
        // would simplify isCurrentMode(..) and presentAtomically(..) in case of mode set

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
        auto *m = &connector->modes[i];
        KWayland::Server::OutputInterface::ModeFlags flags;
        KWayland::Server::OutputDeviceInterface::ModeFlags deviceflags;
        if (isCurrentMode(m)) {
            flags |= KWayland::Server::OutputInterface::ModeFlag::Current;
            deviceflags |= KWayland::Server::OutputDeviceInterface::ModeFlag::Current;
        }
        if (m->type & DRM_MODE_TYPE_PREFERRED) {
            flags |= KWayland::Server::OutputInterface::ModeFlag::Preferred;
            deviceflags |= KWayland::Server::OutputDeviceInterface::ModeFlag::Preferred;
        }

        // Calculate higher precision (mHz) refresh rate
        // logic based on Weston, see compositor-drm.c
        quint64 refreshRate = (m->clock * 1000000LL / m->htotal + m->vtotal / 2) / m->vtotal;
        if (m->flags & DRM_MODE_FLAG_INTERLACE) {
            refreshRate *= 2;
        }
        if (m->flags & DRM_MODE_FLAG_DBLSCAN) {
            refreshRate /= 2;
        }
        if (m->vscan > 1) {
            refreshRate /= m->vscan;
        }
        m_waylandOutput->addMode(QSize(m->hdisplay, m->vdisplay), flags, refreshRate);

        KWayland::Server::OutputDeviceInterface::Mode mode;
        mode.id = i;
        mode.size = QSize(m->hdisplay, m->vdisplay);
        mode.flags = deviceflags;
        mode.refreshRate = refreshRate;
        qCDebug(KWIN_DRM) << "Adding mode: " << i << mode.size;
        m_waylandOutputDevice->addMode(mode);
    }

    // set dpms
    if (!m_dpms.isNull()) {
        m_waylandOutput->setDpmsSupported(true);
        m_waylandOutput->setDpmsMode(toWaylandDpmsMode(m_dpmsMode));
        connect(m_waylandOutput.data(), &KWayland::Server::OutputInterface::dpmsModeRequested, this,
            [this] (KWayland::Server::OutputInterface::DpmsMode mode) {
                setDpms(fromWaylandDpmsMode(mode));
            }, Qt::QueuedConnection
        );
    }

    m_waylandOutput->create();
    qCDebug(KWIN_DRM) << "Created OutputDevice";
    m_waylandOutputDevice->create();
316
    return true;
317 318 319 320 321
}

void DrmOutput::initUuid()
{
    QCryptographicHash hash(QCryptographicHash::Md5);
322
    hash.addData(QByteArray::number(m_conn->id()));
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 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
    hash.addData(m_edid.eisaId);
    hash.addData(m_edid.monitorName);
    hash.addData(m_edid.serialNumber);
    m_uuid = hash.result().toHex().left(10);
}

bool DrmOutput::isCurrentMode(const drmModeModeInfo *mode) const
{
    return mode->clock       == m_mode.clock
        && mode->hdisplay    == m_mode.hdisplay
        && mode->hsync_start == m_mode.hsync_start
        && mode->hsync_end   == m_mode.hsync_end
        && mode->htotal      == m_mode.htotal
        && mode->hskew       == m_mode.hskew
        && mode->vdisplay    == m_mode.vdisplay
        && mode->vsync_start == m_mode.vsync_start
        && mode->vsync_end   == m_mode.vsync_end
        && mode->vtotal      == m_mode.vtotal
        && mode->vscan       == m_mode.vscan
        && mode->vrefresh    == m_mode.vrefresh
        && mode->flags       == m_mode.flags
        && mode->type        == m_mode.type
        && qstrcmp(mode->name, m_mode.name) == 0;
}

static bool verifyEdidHeader(drmModePropertyBlobPtr edid)
{
    const uint8_t *data = reinterpret_cast<uint8_t*>(edid->data);
    if (data[0] != 0x00) {
        return false;
    }
    for (int i = 1; i < 7; ++i) {
        if (data[i] != 0xFF) {
            return false;
        }
    }
    if (data[7] != 0x00) {
        return false;
    }
    return true;
}

static QByteArray extractEisaId(drmModePropertyBlobPtr edid)
{
    /*
     * From EDID standard section 3.4:
     * The ID Manufacturer Name field, shown in Table 3.5, contains a 2-byte representation of the monitor's
     * manufacturer. This is the same as the EISA ID. It is based on compressed ASCII, “0001=A” ... “11010=Z”.
     *
     * The table:
     * | Byte |        Bit                    |
     * |      | 7 | 6 | 5 | 4 | 3 | 2 | 1 | 0 |
     * ----------------------------------------
     * |  1   | 0)| (4| 3 | 2 | 1 | 0)| (4| 3 |
     * |      | * |    Character 1    | Char 2|
     * ----------------------------------------
     * |  2   | 2 | 1 | 0)| (4| 3 | 2 | 1 | 0)|
     * |      | Character2|      Character 3  |
     * ----------------------------------------
     **/
    const uint8_t *data = reinterpret_cast<uint8_t*>(edid->data);
    static const uint offset = 0x8;
    char id[4];
    if (data[offset] >> 7) {
        // bit at position 7 is not a 0
        return QByteArray();
    }
    // shift two bits to right, and with 7 right most bits
    id[0] = 'A' + ((data[offset] >> 2) & 0x1f) -1;
    // for first byte: take last two bits and shift them 3 to left (000xx000)
    // for second byte: shift 5 bits to right and take 3 right most bits (00000xxx)
    // or both together
    id[1] = 'A' + (((data[offset] & 0x3) << 3) | ((data[offset + 1] >> 5) & 0x7)) - 1;
    // take five right most bits
    id[2] = 'A' + (data[offset + 1] & 0x1f) - 1;
    id[3] = '\0';
    return QByteArray(id);
}

static void extractMonitorDescriptorDescription(drmModePropertyBlobPtr blob, DrmOutput::Edid &edid)
{
    // see section 3.10.3
    const uint8_t *data = reinterpret_cast<uint8_t*>(blob->data);
    static const uint offset = 0x36;
    static const uint blockLength = 18;
    for (int i = 0; i < 5; ++i) {
        const uint co = offset + i * blockLength;
        // Flag = 0000h when block used as descriptor
        if (data[co] != 0) {
            continue;
        }
        if (data[co + 1] != 0) {
            continue;
        }
        // Reserved = 00h when block used as descriptor
        if (data[co + 2] != 0) {
            continue;
        }
        /*
         * FFh: Monitor Serial Number - Stored as ASCII, code page # 437, ≤ 13 bytes.
         * FEh: ASCII String - Stored as ASCII, code page # 437, ≤ 13 bytes.
         * FDh: Monitor range limits, binary coded
         * FCh: Monitor name, stored as ASCII, code page # 437
         * FBh: Descriptor contains additional color point data
         * FAh: Descriptor contains additional Standard Timing Identifications
         * F9h - 11h: Currently undefined
         * 10h: Dummy descriptor, used to indicate that the descriptor space is unused
         * 0Fh - 00h: Descriptor defined by manufacturer.
         */
        if (data[co + 3] == 0xfc && edid.monitorName.isEmpty()) {
            edid.monitorName = QByteArray((const char *)(&data[co + 5]), 12).trimmed();
        }
        if (data[co + 3] == 0xfe) {
            const QByteArray id = QByteArray((const char *)(&data[co + 5]), 12).trimmed();
            if (!id.isEmpty()) {
                edid.eisaId = id;
            }
        }
        if (data[co + 3] == 0xff) {
            edid.serialNumber = QByteArray((const char *)(&data[co + 5]), 12).trimmed();
        }
    }
}

static QByteArray extractSerialNumber(drmModePropertyBlobPtr edid)
{
    // see section 3.4
    const uint8_t *data = reinterpret_cast<uint8_t*>(edid->data);
    static const uint offset = 0x0C;
    /*
     * The ID serial number is a 32-bit serial number used to differentiate between individual instances of the same model
     * of monitor. Its use is optional. When used, the bit order for this field follows that shown in Table 3.6. The EDID
     * structure Version 1 Revision 1 and later offer a way to represent the serial number of the monitor as an ASCII string
     * in a separate descriptor block.
     */
    uint32_t serialNumber = 0;
    serialNumber  = (uint32_t) data[offset + 0];
    serialNumber |= (uint32_t) data[offset + 1] << 8;
    serialNumber |= (uint32_t) data[offset + 2] << 16;
    serialNumber |= (uint32_t) data[offset + 3] << 24;
    if (serialNumber == 0) {
        return QByteArray();
    }
    return QByteArray::number(serialNumber);
}

static QSize extractPhysicalSize(drmModePropertyBlobPtr edid)
{
    const uint8_t *data = reinterpret_cast<uint8_t*>(edid->data);
    return QSize(data[0x15], data[0x16]) * 10;
}

void DrmOutput::initEdid(drmModeConnector *connector)
{
    ScopedDrmPointer<_drmModePropertyBlob, &drmModeFreePropertyBlob> edid;
    for (int i = 0; i < connector->count_props; ++i) {
        ScopedDrmPointer<_drmModeProperty, &drmModeFreeProperty> property(drmModeGetProperty(m_backend->fd(), connector->props[i]));
        if (!property) {
            continue;
        }
        if ((property->flags & DRM_MODE_PROP_BLOB) && qstrcmp(property->name, "EDID") == 0) {
            edid.reset(drmModeGetPropertyBlob(m_backend->fd(), connector->prop_values[i]));
        }
    }
    if (!edid) {
        return;
    }

    // for documentation see: http://read.pudn.com/downloads110/ebook/456020/E-EDID%20Standard.pdf
    if (edid->length < 128) {
        return;
    }
    if (!verifyEdidHeader(edid.data())) {
        return;
    }
    m_edid.eisaId = extractEisaId(edid.data());
    m_edid.serialNumber = extractSerialNumber(edid.data());

    // parse monitor descriptor description
    extractMonitorDescriptorDescription(edid.data(), m_edid);

    m_edid.physicalSize = extractPhysicalSize(edid.data());
}

507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522
bool DrmOutput::initPrimaryPlane()
{
    for (int i = 0; i < m_backend->planes().size(); ++i) {
        DrmPlane* p = m_backend->planes()[i];
        if (!p) {
            continue;
        }
        if (p->type() != DrmPlane::TypeIndex::Primary) {
            continue;
        }
        if (p->output()) {     // Plane already has an output
            continue;
        }
        if (m_primaryPlane) {     // Output already has a primary plane
            continue;
        }
523
        if (!p->isCrtcSupported(m_crtc->resIndex())) {
524 525 526 527
            continue;
        }
        p->setOutput(this);
        m_primaryPlane = p;
528
        qCDebug(KWIN_DRM) << "Initialized primary plane" << p->id() << "on CRTC" << m_crtc->id();
529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550
        return true;
    }
    qCCritical(KWIN_DRM) << "Failed to initialize primary plane.";
    return false;
}

bool DrmOutput::initCursorPlane()       // TODO: Add call in init (but needs layer support in general first)
{
    for (int i = 0; i < m_backend->planes().size(); ++i) {
        DrmPlane* p = m_backend->planes()[i];
        if (!p) {
            continue;
        }
        if (p->type() != DrmPlane::TypeIndex::Cursor) {
            continue;
        }
        if (p->output()) {     // Plane already has an output
            continue;
        }
        if (m_cursorPlane) {     // Output already has a cursor plane
            continue;
        }
551
        if (!p->isCrtcSupported(m_crtc->resIndex())) {
552 553 554 555
            continue;
        }
        p->setOutput(this);
        m_cursorPlane = p;
556
        qCDebug(KWIN_DRM) << "Initialized cursor plane" << p->id() << "on CRTC" << m_crtc->id();
557 558 559 560 561
        return true;
    }
    return false;
}

562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580
void DrmOutput::initDpms(drmModeConnector *connector)
{
    for (int i = 0; i < connector->count_props; ++i) {
        ScopedDrmPointer<_drmModeProperty, &drmModeFreeProperty> property(drmModeGetProperty(m_backend->fd(), connector->props[i]));
        if (!property) {
            continue;
        }
        if (qstrcmp(property->name, "DPMS") == 0) {
            m_dpms.swap(property);
            break;
        }
    }
}

void DrmOutput::setDpms(DrmOutput::DpmsMode mode)
{
    if (m_dpms.isNull()) {
        return;
    }
581
    if (mode == m_dpmsModePending) {
582
        qCDebug(KWIN_DRM) << "New DPMS mode equals old mode. DPMS unchanged.";
583 584
        return;
    }
585

586
    m_dpmsModePending = mode;
587

588 589 590 591 592 593 594 595
    if (m_backend->atomicModeSetting()) {
        m_modesetRequested = true;
        if (mode == DpmsMode::On) {
            if (m_pageFlipPending) {
                m_pageFlipPending = false;
                Compositor::self()->bufferSwapComplete();
            }
            dpmsOnHandler();
596
        } else {
597 598 599 600
            m_dpmsAtomicOffPending = true;
            if (!m_pageFlipPending) {
                dpmsAtomicOff();
            }
601 602
        }
    } else {
603
        if (drmModeConnectorSetProperty(m_backend->fd(), m_conn->id(), m_dpms->prop_id, uint64_t(mode)) < 0) {
604
            m_dpmsModePending = m_dpmsMode;
605 606 607
            qCWarning(KWIN_DRM) << "Setting DPMS failed";
            return;
        }
608 609 610 611 612 613
        if (mode == DpmsMode::On) {
            dpmsOnHandler();
        } else {
            dpmsOffHandler();
        }
        m_dpmsMode = m_dpmsModePending;
614
    }
615 616 617 618 619
}

void DrmOutput::dpmsOnHandler()
{
    qCDebug(KWIN_DRM) << "DPMS mode set for output" << m_crtc->id() << "to On.";
620

621
    if (m_waylandOutput) {
622
        m_waylandOutput->setDpmsMode(toWaylandDpmsMode(m_dpmsModePending));
623 624
    }
    emit dpmsChanged();
625 626 627

    m_backend->checkOutputsAreOn();
    if (!m_backend->atomicModeSetting()) {
628
        m_crtc->blank();
629
    }
630 631 632 633 634 635 636 637 638 639 640 641 642 643 644
    if (Compositor *compositor = Compositor::self()) {
        compositor->addRepaintFull();
    }
}

void DrmOutput::dpmsOffHandler()
{
    qCDebug(KWIN_DRM) << "DPMS mode set for output" << m_crtc->id() << "to Off.";

    if (m_waylandOutput) {
        m_waylandOutput->setDpmsMode(toWaylandDpmsMode(m_dpmsModePending));
    }
    emit dpmsChanged();

    m_backend->outputWentOff();
645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673
}

QString DrmOutput::name() const
{
    if (!m_waylandOutput) {
        return i18n("unknown");
    }
    return QStringLiteral("%1 %2").arg(m_waylandOutput->manufacturer()).arg(m_waylandOutput->model());
}

int DrmOutput::currentRefreshRate() const
{
    if (!m_waylandOutput) {
        return 60000;
    }
    return m_waylandOutput->refreshRate();
}

void DrmOutput::setGlobalPos(const QPoint &pos)
{
    m_globalPos = pos;
    if (m_waylandOutput) {
        m_waylandOutput->setGlobalPosition(pos);
    }
    if (m_waylandOutputDevice) {
        m_waylandOutputDevice->setGlobalPosition(pos);
    }
}

David Edmundson's avatar
David Edmundson committed
674 675 676 677 678 679 680 681 682 683 684
void DrmOutput::setScale(qreal scale)
{
    m_scale = scale;
    if (m_waylandOutput) {
        m_waylandOutput->setScale(scale);
    }
    if (m_waylandOutputDevice) {
        m_waylandOutputDevice->setScale(scale);
    }
}

685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709
void DrmOutput::setChanges(KWayland::Server::OutputChangeSet *changes)
{
    m_changeset = changes;
    qCDebug(KWIN_DRM) << "set changes in DrmOutput";
    commitChanges();
}

bool DrmOutput::commitChanges()
{
    Q_ASSERT(!m_waylandOutputDevice.isNull());
    Q_ASSERT(!m_waylandOutput.isNull());

    if (m_changeset.isNull()) {
        qCDebug(KWIN_DRM) << "no changes";
        // No changes to an output is an entirely valid thing
        return true;
    }

    if (m_changeset->enabledChanged()) {
        qCDebug(KWIN_DRM) << "Setting enabled:";
        m_waylandOutputDevice->setEnabled(m_changeset->enabled());
    }
    if (m_changeset->modeChanged()) {
        qCDebug(KWIN_DRM) << "Setting new mode:" << m_changeset->mode();
        m_waylandOutputDevice->setCurrentMode(m_changeset->mode());
710
        updateMode(m_changeset->mode());
711 712 713 714 715
        // FIXME: implement for wl_output
    }
    if (m_changeset->transformChanged()) {
        qCDebug(KWIN_DRM) << "Server setting transform: " << (int)(m_changeset->transform());
        m_waylandOutputDevice->setTransform(m_changeset->transform());
716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781
        using KWayland::Server::OutputDeviceInterface;
        using KWayland::Server::OutputInterface;
        switch (m_changeset->transform()) {
        case OutputDeviceInterface::Transform::Normal:
            if (m_primaryPlane) {
                m_primaryPlane->setTransformation(DrmPlane::Transformation::Rotate0);
            }
            if (m_waylandOutput) {
                m_waylandOutput->setTransform(OutputInterface::Transform::Normal);
            }
            m_orientation = Qt::PrimaryOrientation;
            break;
        case OutputDeviceInterface::Transform::Rotated90:
            if (m_primaryPlane) {
                m_primaryPlane->setTransformation(DrmPlane::Transformation::Rotate90);
            }
            if (m_waylandOutput) {
                m_waylandOutput->setTransform(OutputInterface::Transform::Rotated90);
            }
            m_orientation = Qt::PortraitOrientation;
            break;
        case OutputDeviceInterface::Transform::Rotated180:
            if (m_primaryPlane) {
                m_primaryPlane->setTransformation(DrmPlane::Transformation::Rotate180);
            }
            if (m_waylandOutput) {
                m_waylandOutput->setTransform(OutputInterface::Transform::Rotated180);
            }
            m_orientation = Qt::InvertedLandscapeOrientation;
            break;
        case OutputDeviceInterface::Transform::Rotated270:
            if (m_primaryPlane) {
                m_primaryPlane->setTransformation(DrmPlane::Transformation::Rotate270);
            }
            if (m_waylandOutput) {
                m_waylandOutput->setTransform(OutputInterface::Transform::Rotated270);
            }
            m_orientation = Qt::InvertedPortraitOrientation;
            break;
        case OutputDeviceInterface::Transform::Flipped:
            // TODO: what is this exactly?
            if (m_waylandOutput) {
                m_waylandOutput->setTransform(OutputInterface::Transform::Flipped);
            }
            break;
        case OutputDeviceInterface::Transform::Flipped90:
            // TODO: what is this exactly?
            if (m_waylandOutput) {
                m_waylandOutput->setTransform(OutputInterface::Transform::Flipped90);
            }
            break;
        case OutputDeviceInterface::Transform::Flipped180:
            // TODO: what is this exactly?
            if (m_waylandOutput) {
                m_waylandOutput->setTransform(OutputInterface::Transform::Flipped180);
            }
            break;
        case OutputDeviceInterface::Transform::Flipped270:
            // TODO: what is this exactly?
            if (m_waylandOutput) {
                m_waylandOutput->setTransform(OutputInterface::Transform::Flipped270);
            }
            break;
        }
        m_modesetRequested = true;
        emit modeChanged();
782 783 784
    }
    if (m_changeset->positionChanged()) {
        qCDebug(KWIN_DRM) << "Server setting position: " << m_changeset->position();
785
        setGlobalPos(m_changeset->position());
786 787 788 789
        // may just work already!
    }
    if (m_changeset->scaleChanged()) {
        qCDebug(KWIN_DRM) << "Setting scale:" << m_changeset->scale();
David Edmundson's avatar
David Edmundson committed
790
        setScale(m_changeset->scale());
791 792 793 794
    }
    return true;
}

795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812
void DrmOutput::updateMode(int modeIndex)
{
    // get all modes on the connector
    ScopedDrmPointer<_drmModeConnector, &drmModeFreeConnector> connector(drmModeGetConnector(m_backend->fd(), m_conn->id()));
    if (connector->count_modes <= modeIndex) {
        // TODO: error?
        return;
    }
    if (isCurrentMode(&connector->modes[modeIndex])) {
        // nothing to do
        return;
    }
    m_previousMode = m_mode;
    m_mode = connector->modes[modeIndex];
    m_modesetRequested = true;
    emit modeChanged();
}

813 814
void DrmOutput::pageFlipped()
{
815 816
    m_pageFlipPending = false;

817 818 819
    if (!m_crtc) {
        return;
    }
820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845
    // Egl based surface buffers get destroyed, QPainter based dumb buffers not
    // TODO: split up DrmOutput in two for dumb and egl/gbm surface buffer compatible subclasses completely?
    if (m_backend->deleteBufferAfterPageFlip()) {
        if (m_backend->atomicModeSetting()) {
            if (!m_primaryPlane->next()) {
                // on manual vt switch
                // TODO: when we later use overlay planes it might happen, that we have a page flip with only
                //       damage on one of these, and therefore the primary plane has no next buffer
                //       -> Then we don't want to return here!
                if (m_primaryPlane->current()) {
                    m_primaryPlane->current()->releaseGbm();
                }
                return;
            }
            for (DrmPlane *p : m_nextPlanesFlipList) {
                p->flipBufferWithDelete();
            }
            m_nextPlanesFlipList.clear();
        } else {
            if (!m_crtc->next()) {
                // on manual vt switch
                if (DrmBuffer *b = m_crtc->current()) {
                    b->releaseGbm();
                }
            }
            m_crtc->flipBuffer();
846 847
        }
    } else {
848 849 850
        if (m_backend->atomicModeSetting()){
            for (DrmPlane *p : m_nextPlanesFlipList) {
                p->flipBuffer();
851
            }
852 853 854
            m_nextPlanesFlipList.clear();
        } else {
            m_crtc->flipBuffer();
855
        }
856
        m_crtc->flipBuffer();
857 858 859 860 861 862 863 864 865 866 867 868
    }
}

bool DrmOutput::present(DrmBuffer *buffer)
{
    if (m_backend->atomicModeSetting()) {
        return presentAtomically(buffer);
    } else {
        return presentLegacy(buffer);
    }
}

869
bool DrmOutput::dpmsAtomicOff()
870
{
871 872 873 874 875 876 877 878 879
    m_dpmsAtomicOffPending = false;

    // TODO: With multiple planes: deactivate all of them here
    delete m_primaryPlane->next();
    m_primaryPlane->setNext(nullptr);
    m_nextPlanesFlipList << m_primaryPlane;

    if (!doAtomicCommit(AtomicCommitMode::Test)) {
        qCDebug(KWIN_DRM) << "Atomic test commit to Dpms Off failed. Aborting.";
880 881
        return false;
    }
882 883
    if (!doAtomicCommit(AtomicCommitMode::Real)) {
        qCDebug(KWIN_DRM) << "Atomic commit to Dpms Off failed. This should have never happened! Aborting.";
884 885
        return false;
    }
886 887
    m_nextPlanesFlipList.clear();
    dpmsOffHandler();
888

889
    return true;
890

891
}
892

893 894 895 896 897
bool DrmOutput::presentAtomically(DrmBuffer *buffer)
{
    if (!LogindIntegration::self()->isActiveSession()) {
        qCWarning(KWIN_DRM) << "Logind session not active.";
        return false;
898 899
    }

900 901 902
    if (m_pageFlipPending) {
        qCWarning(KWIN_DRM) << "Page not yet flipped.";
        return false;
903 904
    }

905 906 907 908 909
    m_primaryPlane->setNext(buffer);
    m_nextPlanesFlipList << m_primaryPlane;

    if (!doAtomicCommit(AtomicCommitMode::Test)) {
        //TODO: When we use planes for layered rendering, fallback to renderer instead. Also for direct scanout?
910
        //TODO: Probably should undo setNext and reset the flip list
911
        qCDebug(KWIN_DRM) << "Atomic test commit failed. Aborting present.";
912 913
        return false;
    }
914 915
    if (!doAtomicCommit(AtomicCommitMode::Real)) {
        qCDebug(KWIN_DRM) << "Atomic commit failed. This should have never happened! Aborting present.";
916
        //TODO: Probably should undo setNext and reset the flip list
917
        return false;
918
    }
919
    m_pageFlipPending = true;
920 921 922 923 924
    return true;
}

bool DrmOutput::presentLegacy(DrmBuffer *buffer)
{
925
    if (m_crtc->next()) {
926 927 928
        return false;
    }
    if (!LogindIntegration::self()->isActiveSession()) {
929
        m_crtc->setNext(buffer);
930 931 932 933 934 935 936
        return false;
    }
    if (m_dpmsMode != DpmsMode::On) {
        return false;
    }

    // Do we need to set a new mode first?
Roman Gilg's avatar
Roman Gilg committed
937 938
    if (!m_crtc->current() || m_crtc->current()->needsModeChange(buffer)) {
        if (!setModeLegacy(buffer)) {
939
            return false;
Roman Gilg's avatar
Roman Gilg committed
940
        }
941
    }
942
    const bool ok = drmModePageFlip(m_backend->fd(), m_crtc->id(), buffer->bufferId(), DRM_MODE_PAGE_FLIP_EVENT, this) == 0;
943
    if (ok) {
944
        m_crtc->setNext(buffer);
945 946 947 948 949 950 951 952
    } else {
        qCWarning(KWIN_DRM) << "Page flip failed:" << strerror(errno);
    }
    return ok;
}

bool DrmOutput::setModeLegacy(DrmBuffer *buffer)
{
953 954
    uint32_t connId = m_conn->id();
    if (drmModeSetCrtc(m_backend->fd(), m_crtc->id(), buffer->bufferId(), 0, 0, &connId, 1, &m_mode) == 0) {
955 956 957 958 959 960 961
        return true;
    } else {
        qCWarning(KWIN_DRM) << "Mode setting failed";
        return false;
    }
}

962
bool DrmOutput::doAtomicCommit(AtomicCommitMode mode)
963
{
964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022
    drmModeAtomicReq *req = drmModeAtomicAlloc();

    auto errorHandler = [this, mode, req] () {
        if (mode == AtomicCommitMode::Test) {
            // TODO: when we later test overlay planes, make sure we change only the right stuff back
        }
        if (req) {
            drmModeAtomicFree(req);
        }

        if (m_dpmsMode != m_dpmsModePending) {
            qCWarning(KWIN_DRM) << "Setting DPMS failed";
            m_dpmsModePending = m_dpmsMode;
            if (m_dpmsMode != DpmsMode::On) {
                dpmsOffHandler();
            }
        }

        // TODO: see above, rework later for overlay planes!
        for (DrmPlane *p : m_nextPlanesFlipList) {
            p->setNext(nullptr);
        }
        m_nextPlanesFlipList.clear();

    };

    if (!req) {
            qCWarning(KWIN_DRM) << "DRM: couldn't allocate atomic request";
            errorHandler();
            return false;
    }

    uint32_t flags = 0;

    // Do we need to set a new mode?
    if (m_modesetRequested) {
        if (m_dpmsModePending == DpmsMode::On) {
            if (drmModeCreatePropertyBlob(m_backend->fd(), &m_mode, sizeof(m_mode), &m_blobId) != 0) {
                qCWarning(KWIN_DRM) << "Failed to create property blob";
                errorHandler();
                return false;
            }
        }
        if (!atomicReqModesetPopulate(req, m_dpmsModePending == DpmsMode::On)){
            qCWarning(KWIN_DRM) << "Failed to populate Atomic Modeset";
            errorHandler();
            return false;
        }
        flags |= DRM_MODE_ATOMIC_ALLOW_MODESET;
    }

    if (mode == AtomicCommitMode::Real) {
        if (m_dpmsModePending == DpmsMode::On) {
            if (!(flags & DRM_MODE_ATOMIC_ALLOW_MODESET)) {
                // TODO: Evaluating this condition should only be necessary, as long as we expect older kernels than 4.10.
                flags |= DRM_MODE_ATOMIC_NONBLOCK;
            }
            flags |= DRM_MODE_PAGE_FLIP_EVENT;
        }
1023
    } else {
1024
        flags |= DRM_MODE_ATOMIC_TEST_ONLY;
1025 1026 1027
    }

    bool ret = true;
1028 1029 1030 1031 1032
    // TODO: Make sure when we use more than one plane at a time, that we go through this list in the right order.
    for (int i = m_nextPlanesFlipList.size() - 1; 0 <= i; i-- ) {
        DrmPlane *p = m_nextPlanesFlipList[i];
        ret &= p->atomicPopulate(req);
    }
1033

1034 1035 1036 1037 1038
    if (!ret) {
        qCWarning(KWIN_DRM) << "Failed to populate atomic planes. Abort atomic commit!";
        errorHandler();
        return false;
    }
1039

1040 1041 1042 1043 1044
    if (drmModeAtomicCommit(m_backend->fd(), req, flags, this)) {
        qCWarning(KWIN_DRM) << "Atomic request failed to commit:" << strerror(errno);
        errorHandler();
        return false;
    }
1045

1046 1047 1048 1049
    if (mode == AtomicCommitMode::Real && (flags & DRM_MODE_ATOMIC_ALLOW_MODESET)) {
        qCDebug(KWIN_DRM) << "Atomic Modeset successful.";
        m_modesetRequested = false;
        m_dpmsMode = m_dpmsModePending;
1050
    }
1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080

    drmModeAtomicFree(req);
    return true;
}

bool DrmOutput::atomicReqModesetPopulate(drmModeAtomicReq *req, bool enable)
{
    if (enable) {
        m_primaryPlane->setValue(int(DrmPlane::PropertyIndex::SrcX), 0);
        m_primaryPlane->setValue(int(DrmPlane::PropertyIndex::SrcY), 0);
        m_primaryPlane->setValue(int(DrmPlane::PropertyIndex::SrcW), m_mode.hdisplay << 16);
        m_primaryPlane->setValue(int(DrmPlane::PropertyIndex::SrcH), m_mode.vdisplay << 16);
        m_primaryPlane->setValue(int(DrmPlane::PropertyIndex::CrtcW), m_mode.hdisplay);
        m_primaryPlane->setValue(int(DrmPlane::PropertyIndex::CrtcH), m_mode.vdisplay);
        m_primaryPlane->setValue(int(DrmPlane::PropertyIndex::CrtcId), m_crtc->id());
    } else {
        if (m_backend->deleteBufferAfterPageFlip()) {
            delete m_primaryPlane->current();
            delete m_primaryPlane->next();
        }
        m_primaryPlane->setCurrent(nullptr);
        m_primaryPlane->setNext(nullptr);

        m_primaryPlane->setValue(int(DrmPlane::PropertyIndex::SrcX), 0);
        m_primaryPlane->setValue(int(DrmPlane::PropertyIndex::SrcY), 0);
        m_primaryPlane->setValue(int(DrmPlane::PropertyIndex::SrcW), 0);
        m_primaryPlane->setValue(int(DrmPlane::PropertyIndex::SrcH), 0);
        m_primaryPlane->setValue(int(DrmPlane::PropertyIndex::CrtcW), 0);
        m_primaryPlane->setValue(int(DrmPlane::PropertyIndex::CrtcH), 0);
        m_primaryPlane->setValue(int(DrmPlane::PropertyIndex::CrtcId), 0);
1081
    }
1082 1083 1084 1085 1086 1087 1088 1089 1090
    m_conn->setValue(int(DrmConnector::PropertyIndex::CrtcId), enable ? m_crtc->id() : 0);
    m_crtc->setValue(int(DrmCrtc::PropertyIndex::ModeId), enable ? m_blobId : 0);
    m_crtc->setValue(int(DrmCrtc::PropertyIndex::Active), enable);

    bool ret = true;
    ret &= m_conn->atomicPopulate(req);
    ret &= m_crtc->atomicPopulate(req);

    return ret;
1091
}
1092 1093

}