linux/drivers/gpu/drm/drm_dp_helper.c
<<
>>
Prefs
   1/*
   2 * Copyright © 2009 Keith Packard
   3 *
   4 * Permission to use, copy, modify, distribute, and sell this software and its
   5 * documentation for any purpose is hereby granted without fee, provided that
   6 * the above copyright notice appear in all copies and that both that copyright
   7 * notice and this permission notice appear in supporting documentation, and
   8 * that the name of the copyright holders not be used in advertising or
   9 * publicity pertaining to distribution of the software without specific,
  10 * written prior permission.  The copyright holders make no representations
  11 * about the suitability of this software for any purpose.  It is provided "as
  12 * is" without express or implied warranty.
  13 *
  14 * THE COPYRIGHT HOLDERS DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
  15 * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
  16 * EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE FOR ANY SPECIAL, INDIRECT OR
  17 * CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
  18 * DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  19 * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  20 * OF THIS SOFTWARE.
  21 */
  22
  23#include <linux/delay.h>
  24#include <linux/errno.h>
  25#include <linux/i2c.h>
  26#include <linux/init.h>
  27#include <linux/kernel.h>
  28#include <linux/module.h>
  29#include <linux/sched.h>
  30#include <linux/seq_file.h>
  31
  32#include <drm/drm_dp_helper.h>
  33#include <drm/drm_print.h>
  34#include <drm/drm_vblank.h>
  35
  36#include "drm_crtc_helper_internal.h"
  37
  38/**
  39 * DOC: dp helpers
  40 *
  41 * These functions contain some common logic and helpers at various abstraction
  42 * levels to deal with Display Port sink devices and related things like DP aux
  43 * channel transfers, EDID reading over DP aux channels, decoding certain DPCD
  44 * blocks, ...
  45 */
  46
  47/* Helpers for DP link training */
  48static u8 dp_link_status(const u8 link_status[DP_LINK_STATUS_SIZE], int r)
  49{
  50        return link_status[r - DP_LANE0_1_STATUS];
  51}
  52
  53static u8 dp_get_lane_status(const u8 link_status[DP_LINK_STATUS_SIZE],
  54                             int lane)
  55{
  56        int i = DP_LANE0_1_STATUS + (lane >> 1);
  57        int s = (lane & 1) * 4;
  58        u8 l = dp_link_status(link_status, i);
  59        return (l >> s) & 0xf;
  60}
  61
  62bool drm_dp_channel_eq_ok(const u8 link_status[DP_LINK_STATUS_SIZE],
  63                          int lane_count)
  64{
  65        u8 lane_align;
  66        u8 lane_status;
  67        int lane;
  68
  69        lane_align = dp_link_status(link_status,
  70                                    DP_LANE_ALIGN_STATUS_UPDATED);
  71        if ((lane_align & DP_INTERLANE_ALIGN_DONE) == 0)
  72                return false;
  73        for (lane = 0; lane < lane_count; lane++) {
  74                lane_status = dp_get_lane_status(link_status, lane);
  75                if ((lane_status & DP_CHANNEL_EQ_BITS) != DP_CHANNEL_EQ_BITS)
  76                        return false;
  77        }
  78        return true;
  79}
  80EXPORT_SYMBOL(drm_dp_channel_eq_ok);
  81
  82bool drm_dp_clock_recovery_ok(const u8 link_status[DP_LINK_STATUS_SIZE],
  83                              int lane_count)
  84{
  85        int lane;
  86        u8 lane_status;
  87
  88        for (lane = 0; lane < lane_count; lane++) {
  89                lane_status = dp_get_lane_status(link_status, lane);
  90                if ((lane_status & DP_LANE_CR_DONE) == 0)
  91                        return false;
  92        }
  93        return true;
  94}
  95EXPORT_SYMBOL(drm_dp_clock_recovery_ok);
  96
  97u8 drm_dp_get_adjust_request_voltage(const u8 link_status[DP_LINK_STATUS_SIZE],
  98                                     int lane)
  99{
 100        int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
 101        int s = ((lane & 1) ?
 102                 DP_ADJUST_VOLTAGE_SWING_LANE1_SHIFT :
 103                 DP_ADJUST_VOLTAGE_SWING_LANE0_SHIFT);
 104        u8 l = dp_link_status(link_status, i);
 105
 106        return ((l >> s) & 0x3) << DP_TRAIN_VOLTAGE_SWING_SHIFT;
 107}
 108EXPORT_SYMBOL(drm_dp_get_adjust_request_voltage);
 109
 110u8 drm_dp_get_adjust_request_pre_emphasis(const u8 link_status[DP_LINK_STATUS_SIZE],
 111                                          int lane)
 112{
 113        int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
 114        int s = ((lane & 1) ?
 115                 DP_ADJUST_PRE_EMPHASIS_LANE1_SHIFT :
 116                 DP_ADJUST_PRE_EMPHASIS_LANE0_SHIFT);
 117        u8 l = dp_link_status(link_status, i);
 118
 119        return ((l >> s) & 0x3) << DP_TRAIN_PRE_EMPHASIS_SHIFT;
 120}
 121EXPORT_SYMBOL(drm_dp_get_adjust_request_pre_emphasis);
 122
 123u8 drm_dp_get_adjust_request_post_cursor(const u8 link_status[DP_LINK_STATUS_SIZE],
 124                                         unsigned int lane)
 125{
 126        unsigned int offset = DP_ADJUST_REQUEST_POST_CURSOR2;
 127        u8 value = dp_link_status(link_status, offset);
 128
 129        return (value >> (lane << 1)) & 0x3;
 130}
 131EXPORT_SYMBOL(drm_dp_get_adjust_request_post_cursor);
 132
 133void drm_dp_link_train_clock_recovery_delay(const u8 dpcd[DP_RECEIVER_CAP_SIZE])
 134{
 135        unsigned long rd_interval = dpcd[DP_TRAINING_AUX_RD_INTERVAL] &
 136                                         DP_TRAINING_AUX_RD_MASK;
 137
 138        if (rd_interval > 4)
 139                DRM_DEBUG_KMS("AUX interval %lu, out of range (max 4)\n",
 140                              rd_interval);
 141
 142        if (rd_interval == 0 || dpcd[DP_DPCD_REV] >= DP_DPCD_REV_14)
 143                rd_interval = 100;
 144        else
 145                rd_interval *= 4 * USEC_PER_MSEC;
 146
 147        usleep_range(rd_interval, rd_interval * 2);
 148}
 149EXPORT_SYMBOL(drm_dp_link_train_clock_recovery_delay);
 150
 151void drm_dp_link_train_channel_eq_delay(const u8 dpcd[DP_RECEIVER_CAP_SIZE])
 152{
 153        unsigned long rd_interval = dpcd[DP_TRAINING_AUX_RD_INTERVAL] &
 154                                         DP_TRAINING_AUX_RD_MASK;
 155
 156        if (rd_interval > 4)
 157                DRM_DEBUG_KMS("AUX interval %lu, out of range (max 4)\n",
 158                              rd_interval);
 159
 160        if (rd_interval == 0)
 161                rd_interval = 400;
 162        else
 163                rd_interval *= 4 * USEC_PER_MSEC;
 164
 165        usleep_range(rd_interval, rd_interval * 2);
 166}
 167EXPORT_SYMBOL(drm_dp_link_train_channel_eq_delay);
 168
 169u8 drm_dp_link_rate_to_bw_code(int link_rate)
 170{
 171        /* Spec says link_bw = link_rate / 0.27Gbps */
 172        return link_rate / 27000;
 173}
 174EXPORT_SYMBOL(drm_dp_link_rate_to_bw_code);
 175
 176int drm_dp_bw_code_to_link_rate(u8 link_bw)
 177{
 178        /* Spec says link_rate = link_bw * 0.27Gbps */
 179        return link_bw * 27000;
 180}
 181EXPORT_SYMBOL(drm_dp_bw_code_to_link_rate);
 182
 183#define AUX_RETRY_INTERVAL 500 /* us */
 184
 185static inline void
 186drm_dp_dump_access(const struct drm_dp_aux *aux,
 187                   u8 request, uint offset, void *buffer, int ret)
 188{
 189        const char *arrow = request == DP_AUX_NATIVE_READ ? "->" : "<-";
 190
 191        if (ret > 0)
 192                DRM_DEBUG_DP("%s: 0x%05x AUX %s (ret=%3d) %*ph\n",
 193                             aux->name, offset, arrow, ret, min(ret, 20), buffer);
 194        else
 195                DRM_DEBUG_DP("%s: 0x%05x AUX %s (ret=%3d)\n",
 196                             aux->name, offset, arrow, ret);
 197}
 198
 199/**
 200 * DOC: dp helpers
 201 *
 202 * The DisplayPort AUX channel is an abstraction to allow generic, driver-
 203 * independent access to AUX functionality. Drivers can take advantage of
 204 * this by filling in the fields of the drm_dp_aux structure.
 205 *
 206 * Transactions are described using a hardware-independent drm_dp_aux_msg
 207 * structure, which is passed into a driver's .transfer() implementation.
 208 * Both native and I2C-over-AUX transactions are supported.
 209 */
 210
 211static int drm_dp_dpcd_access(struct drm_dp_aux *aux, u8 request,
 212                              unsigned int offset, void *buffer, size_t size)
 213{
 214        struct drm_dp_aux_msg msg;
 215        unsigned int retry, native_reply;
 216        int err = 0, ret = 0;
 217
 218        memset(&msg, 0, sizeof(msg));
 219        msg.address = offset;
 220        msg.request = request;
 221        msg.buffer = buffer;
 222        msg.size = size;
 223
 224        mutex_lock(&aux->hw_mutex);
 225
 226        /*
 227         * The specification doesn't give any recommendation on how often to
 228         * retry native transactions. We used to retry 7 times like for
 229         * aux i2c transactions but real world devices this wasn't
 230         * sufficient, bump to 32 which makes Dell 4k monitors happier.
 231         */
 232        for (retry = 0; retry < 32; retry++) {
 233                if (ret != 0 && ret != -ETIMEDOUT) {
 234                        usleep_range(AUX_RETRY_INTERVAL,
 235                                     AUX_RETRY_INTERVAL + 100);
 236                }
 237
 238                ret = aux->transfer(aux, &msg);
 239                if (ret >= 0) {
 240                        native_reply = msg.reply & DP_AUX_NATIVE_REPLY_MASK;
 241                        if (native_reply == DP_AUX_NATIVE_REPLY_ACK) {
 242                                if (ret == size)
 243                                        goto unlock;
 244
 245                                ret = -EPROTO;
 246                        } else
 247                                ret = -EIO;
 248                }
 249
 250                /*
 251                 * We want the error we return to be the error we received on
 252                 * the first transaction, since we may get a different error the
 253                 * next time we retry
 254                 */
 255                if (!err)
 256                        err = ret;
 257        }
 258
 259        DRM_DEBUG_KMS("Too many retries, giving up. First error: %d\n", err);
 260        ret = err;
 261
 262unlock:
 263        mutex_unlock(&aux->hw_mutex);
 264        return ret;
 265}
 266
 267/**
 268 * drm_dp_dpcd_read() - read a series of bytes from the DPCD
 269 * @aux: DisplayPort AUX channel
 270 * @offset: address of the (first) register to read
 271 * @buffer: buffer to store the register values
 272 * @size: number of bytes in @buffer
 273 *
 274 * Returns the number of bytes transferred on success, or a negative error
 275 * code on failure. -EIO is returned if the request was NAKed by the sink or
 276 * if the retry count was exceeded. If not all bytes were transferred, this
 277 * function returns -EPROTO. Errors from the underlying AUX channel transfer
 278 * function, with the exception of -EBUSY (which causes the transaction to
 279 * be retried), are propagated to the caller.
 280 */
 281ssize_t drm_dp_dpcd_read(struct drm_dp_aux *aux, unsigned int offset,
 282                         void *buffer, size_t size)
 283{
 284        int ret;
 285
 286        /*
 287         * HP ZR24w corrupts the first DPCD access after entering power save
 288         * mode. Eg. on a read, the entire buffer will be filled with the same
 289         * byte. Do a throw away read to avoid corrupting anything we care
 290         * about. Afterwards things will work correctly until the monitor
 291         * gets woken up and subsequently re-enters power save mode.
 292         *
 293         * The user pressing any button on the monitor is enough to wake it
 294         * up, so there is no particularly good place to do the workaround.
 295         * We just have to do it before any DPCD access and hope that the
 296         * monitor doesn't power down exactly after the throw away read.
 297         */
 298        ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_READ, DP_DPCD_REV, buffer,
 299                                 1);
 300        if (ret != 1)
 301                goto out;
 302
 303        ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_READ, offset, buffer,
 304                                 size);
 305
 306out:
 307        drm_dp_dump_access(aux, DP_AUX_NATIVE_READ, offset, buffer, ret);
 308        return ret;
 309}
 310EXPORT_SYMBOL(drm_dp_dpcd_read);
 311
 312/**
 313 * drm_dp_dpcd_write() - write a series of bytes to the DPCD
 314 * @aux: DisplayPort AUX channel
 315 * @offset: address of the (first) register to write
 316 * @buffer: buffer containing the values to write
 317 * @size: number of bytes in @buffer
 318 *
 319 * Returns the number of bytes transferred on success, or a negative error
 320 * code on failure. -EIO is returned if the request was NAKed by the sink or
 321 * if the retry count was exceeded. If not all bytes were transferred, this
 322 * function returns -EPROTO. Errors from the underlying AUX channel transfer
 323 * function, with the exception of -EBUSY (which causes the transaction to
 324 * be retried), are propagated to the caller.
 325 */
 326ssize_t drm_dp_dpcd_write(struct drm_dp_aux *aux, unsigned int offset,
 327                          void *buffer, size_t size)
 328{
 329        int ret;
 330
 331        ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_WRITE, offset, buffer,
 332                                 size);
 333        drm_dp_dump_access(aux, DP_AUX_NATIVE_WRITE, offset, buffer, ret);
 334        return ret;
 335}
 336EXPORT_SYMBOL(drm_dp_dpcd_write);
 337
 338/**
 339 * drm_dp_dpcd_read_link_status() - read DPCD link status (bytes 0x202-0x207)
 340 * @aux: DisplayPort AUX channel
 341 * @status: buffer to store the link status in (must be at least 6 bytes)
 342 *
 343 * Returns the number of bytes transferred on success or a negative error
 344 * code on failure.
 345 */
 346int drm_dp_dpcd_read_link_status(struct drm_dp_aux *aux,
 347                                 u8 status[DP_LINK_STATUS_SIZE])
 348{
 349        return drm_dp_dpcd_read(aux, DP_LANE0_1_STATUS, status,
 350                                DP_LINK_STATUS_SIZE);
 351}
 352EXPORT_SYMBOL(drm_dp_dpcd_read_link_status);
 353
 354/**
 355 * drm_dp_downstream_max_clock() - extract branch device max
 356 *                                 pixel rate for legacy VGA
 357 *                                 converter or max TMDS clock
 358 *                                 rate for others
 359 * @dpcd: DisplayPort configuration data
 360 * @port_cap: port capabilities
 361 *
 362 * Returns max clock in kHz on success or 0 if max clock not defined
 363 */
 364int drm_dp_downstream_max_clock(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
 365                                const u8 port_cap[4])
 366{
 367        int type = port_cap[0] & DP_DS_PORT_TYPE_MASK;
 368        bool detailed_cap_info = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
 369                DP_DETAILED_CAP_INFO_AVAILABLE;
 370
 371        if (!detailed_cap_info)
 372                return 0;
 373
 374        switch (type) {
 375        case DP_DS_PORT_TYPE_VGA:
 376                return port_cap[1] * 8 * 1000;
 377        case DP_DS_PORT_TYPE_DVI:
 378        case DP_DS_PORT_TYPE_HDMI:
 379        case DP_DS_PORT_TYPE_DP_DUALMODE:
 380                return port_cap[1] * 2500;
 381        default:
 382                return 0;
 383        }
 384}
 385EXPORT_SYMBOL(drm_dp_downstream_max_clock);
 386
 387/**
 388 * drm_dp_downstream_max_bpc() - extract branch device max
 389 *                               bits per component
 390 * @dpcd: DisplayPort configuration data
 391 * @port_cap: port capabilities
 392 *
 393 * Returns max bpc on success or 0 if max bpc not defined
 394 */
 395int drm_dp_downstream_max_bpc(const u8 dpcd[DP_RECEIVER_CAP_SIZE],
 396                              const u8 port_cap[4])
 397{
 398        int type = port_cap[0] & DP_DS_PORT_TYPE_MASK;
 399        bool detailed_cap_info = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
 400                DP_DETAILED_CAP_INFO_AVAILABLE;
 401        int bpc;
 402
 403        if (!detailed_cap_info)
 404                return 0;
 405
 406        switch (type) {
 407        case DP_DS_PORT_TYPE_VGA:
 408        case DP_DS_PORT_TYPE_DVI:
 409        case DP_DS_PORT_TYPE_HDMI:
 410        case DP_DS_PORT_TYPE_DP_DUALMODE:
 411                bpc = port_cap[2] & DP_DS_MAX_BPC_MASK;
 412
 413                switch (bpc) {
 414                case DP_DS_8BPC:
 415                        return 8;
 416                case DP_DS_10BPC:
 417                        return 10;
 418                case DP_DS_12BPC:
 419                        return 12;
 420                case DP_DS_16BPC:
 421                        return 16;
 422                }
 423                /* fall through */
 424        default:
 425                return 0;
 426        }
 427}
 428EXPORT_SYMBOL(drm_dp_downstream_max_bpc);
 429
 430/**
 431 * drm_dp_downstream_id() - identify branch device
 432 * @aux: DisplayPort AUX channel
 433 * @id: DisplayPort branch device id
 434 *
 435 * Returns branch device id on success or NULL on failure
 436 */
 437int drm_dp_downstream_id(struct drm_dp_aux *aux, char id[6])
 438{
 439        return drm_dp_dpcd_read(aux, DP_BRANCH_ID, id, 6);
 440}
 441EXPORT_SYMBOL(drm_dp_downstream_id);
 442
 443/**
 444 * drm_dp_downstream_debug() - debug DP branch devices
 445 * @m: pointer for debugfs file
 446 * @dpcd: DisplayPort configuration data
 447 * @port_cap: port capabilities
 448 * @aux: DisplayPort AUX channel
 449 *
 450 */
 451void drm_dp_downstream_debug(struct seq_file *m,
 452                             const u8 dpcd[DP_RECEIVER_CAP_SIZE],
 453                             const u8 port_cap[4], struct drm_dp_aux *aux)
 454{
 455        bool detailed_cap_info = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
 456                                 DP_DETAILED_CAP_INFO_AVAILABLE;
 457        int clk;
 458        int bpc;
 459        char id[7];
 460        int len;
 461        uint8_t rev[2];
 462        int type = port_cap[0] & DP_DS_PORT_TYPE_MASK;
 463        bool branch_device = dpcd[DP_DOWNSTREAMPORT_PRESENT] &
 464                             DP_DWN_STRM_PORT_PRESENT;
 465
 466        seq_printf(m, "\tDP branch device present: %s\n",
 467                   branch_device ? "yes" : "no");
 468
 469        if (!branch_device)
 470                return;
 471
 472        switch (type) {
 473        case DP_DS_PORT_TYPE_DP:
 474                seq_puts(m, "\t\tType: DisplayPort\n");
 475                break;
 476        case DP_DS_PORT_TYPE_VGA:
 477                seq_puts(m, "\t\tType: VGA\n");
 478                break;
 479        case DP_DS_PORT_TYPE_DVI:
 480                seq_puts(m, "\t\tType: DVI\n");
 481                break;
 482        case DP_DS_PORT_TYPE_HDMI:
 483                seq_puts(m, "\t\tType: HDMI\n");
 484                break;
 485        case DP_DS_PORT_TYPE_NON_EDID:
 486                seq_puts(m, "\t\tType: others without EDID support\n");
 487                break;
 488        case DP_DS_PORT_TYPE_DP_DUALMODE:
 489                seq_puts(m, "\t\tType: DP++\n");
 490                break;
 491        case DP_DS_PORT_TYPE_WIRELESS:
 492                seq_puts(m, "\t\tType: Wireless\n");
 493                break;
 494        default:
 495                seq_puts(m, "\t\tType: N/A\n");
 496        }
 497
 498        memset(id, 0, sizeof(id));
 499        drm_dp_downstream_id(aux, id);
 500        seq_printf(m, "\t\tID: %s\n", id);
 501
 502        len = drm_dp_dpcd_read(aux, DP_BRANCH_HW_REV, &rev[0], 1);
 503        if (len > 0)
 504                seq_printf(m, "\t\tHW: %d.%d\n",
 505                           (rev[0] & 0xf0) >> 4, rev[0] & 0xf);
 506
 507        len = drm_dp_dpcd_read(aux, DP_BRANCH_SW_REV, rev, 2);
 508        if (len > 0)
 509                seq_printf(m, "\t\tSW: %d.%d\n", rev[0], rev[1]);
 510
 511        if (detailed_cap_info) {
 512                clk = drm_dp_downstream_max_clock(dpcd, port_cap);
 513
 514                if (clk > 0) {
 515                        if (type == DP_DS_PORT_TYPE_VGA)
 516                                seq_printf(m, "\t\tMax dot clock: %d kHz\n", clk);
 517                        else
 518                                seq_printf(m, "\t\tMax TMDS clock: %d kHz\n", clk);
 519                }
 520
 521                bpc = drm_dp_downstream_max_bpc(dpcd, port_cap);
 522
 523                if (bpc > 0)
 524                        seq_printf(m, "\t\tMax bpc: %d\n", bpc);
 525        }
 526}
 527EXPORT_SYMBOL(drm_dp_downstream_debug);
 528
 529/*
 530 * I2C-over-AUX implementation
 531 */
 532
 533static u32 drm_dp_i2c_functionality(struct i2c_adapter *adapter)
 534{
 535        return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
 536               I2C_FUNC_SMBUS_READ_BLOCK_DATA |
 537               I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
 538               I2C_FUNC_10BIT_ADDR;
 539}
 540
 541static void drm_dp_i2c_msg_write_status_update(struct drm_dp_aux_msg *msg)
 542{
 543        /*
 544         * In case of i2c defer or short i2c ack reply to a write,
 545         * we need to switch to WRITE_STATUS_UPDATE to drain the
 546         * rest of the message
 547         */
 548        if ((msg->request & ~DP_AUX_I2C_MOT) == DP_AUX_I2C_WRITE) {
 549                msg->request &= DP_AUX_I2C_MOT;
 550                msg->request |= DP_AUX_I2C_WRITE_STATUS_UPDATE;
 551        }
 552}
 553
 554#define AUX_PRECHARGE_LEN 10 /* 10 to 16 */
 555#define AUX_SYNC_LEN (16 + 4) /* preamble + AUX_SYNC_END */
 556#define AUX_STOP_LEN 4
 557#define AUX_CMD_LEN 4
 558#define AUX_ADDRESS_LEN 20
 559#define AUX_REPLY_PAD_LEN 4
 560#define AUX_LENGTH_LEN 8
 561
 562/*
 563 * Calculate the duration of the AUX request/reply in usec. Gives the
 564 * "best" case estimate, ie. successful while as short as possible.
 565 */
 566static int drm_dp_aux_req_duration(const struct drm_dp_aux_msg *msg)
 567{
 568        int len = AUX_PRECHARGE_LEN + AUX_SYNC_LEN + AUX_STOP_LEN +
 569                AUX_CMD_LEN + AUX_ADDRESS_LEN + AUX_LENGTH_LEN;
 570
 571        if ((msg->request & DP_AUX_I2C_READ) == 0)
 572                len += msg->size * 8;
 573
 574        return len;
 575}
 576
 577static int drm_dp_aux_reply_duration(const struct drm_dp_aux_msg *msg)
 578{
 579        int len = AUX_PRECHARGE_LEN + AUX_SYNC_LEN + AUX_STOP_LEN +
 580                AUX_CMD_LEN + AUX_REPLY_PAD_LEN;
 581
 582        /*
 583         * For read we expect what was asked. For writes there will
 584         * be 0 or 1 data bytes. Assume 0 for the "best" case.
 585         */
 586        if (msg->request & DP_AUX_I2C_READ)
 587                len += msg->size * 8;
 588
 589        return len;
 590}
 591
 592#define I2C_START_LEN 1
 593#define I2C_STOP_LEN 1
 594#define I2C_ADDR_LEN 9 /* ADDRESS + R/W + ACK/NACK */
 595#define I2C_DATA_LEN 9 /* DATA + ACK/NACK */
 596
 597/*
 598 * Calculate the length of the i2c transfer in usec, assuming
 599 * the i2c bus speed is as specified. Gives the the "worst"
 600 * case estimate, ie. successful while as long as possible.
 601 * Doesn't account the the "MOT" bit, and instead assumes each
 602 * message includes a START, ADDRESS and STOP. Neither does it
 603 * account for additional random variables such as clock stretching.
 604 */
 605static int drm_dp_i2c_msg_duration(const struct drm_dp_aux_msg *msg,
 606                                   int i2c_speed_khz)
 607{
 608        /* AUX bitrate is 1MHz, i2c bitrate as specified */
 609        return DIV_ROUND_UP((I2C_START_LEN + I2C_ADDR_LEN +
 610                             msg->size * I2C_DATA_LEN +
 611                             I2C_STOP_LEN) * 1000, i2c_speed_khz);
 612}
 613
 614/*
 615 * Deterine how many retries should be attempted to successfully transfer
 616 * the specified message, based on the estimated durations of the
 617 * i2c and AUX transfers.
 618 */
 619static int drm_dp_i2c_retry_count(const struct drm_dp_aux_msg *msg,
 620                              int i2c_speed_khz)
 621{
 622        int aux_time_us = drm_dp_aux_req_duration(msg) +
 623                drm_dp_aux_reply_duration(msg);
 624        int i2c_time_us = drm_dp_i2c_msg_duration(msg, i2c_speed_khz);
 625
 626        return DIV_ROUND_UP(i2c_time_us, aux_time_us + AUX_RETRY_INTERVAL);
 627}
 628
 629/*
 630 * FIXME currently assumes 10 kHz as some real world devices seem
 631 * to require it. We should query/set the speed via DPCD if supported.
 632 */
 633static int dp_aux_i2c_speed_khz __read_mostly = 10;
 634module_param_unsafe(dp_aux_i2c_speed_khz, int, 0644);
 635MODULE_PARM_DESC(dp_aux_i2c_speed_khz,
 636                 "Assumed speed of the i2c bus in kHz, (1-400, default 10)");
 637
 638/*
 639 * Transfer a single I2C-over-AUX message and handle various error conditions,
 640 * retrying the transaction as appropriate.  It is assumed that the
 641 * &drm_dp_aux.transfer function does not modify anything in the msg other than the
 642 * reply field.
 643 *
 644 * Returns bytes transferred on success, or a negative error code on failure.
 645 */
 646static int drm_dp_i2c_do_msg(struct drm_dp_aux *aux, struct drm_dp_aux_msg *msg)
 647{
 648        unsigned int retry, defer_i2c;
 649        int ret;
 650        /*
 651         * DP1.2 sections 2.7.7.1.5.6.1 and 2.7.7.1.6.6.1: A DP Source device
 652         * is required to retry at least seven times upon receiving AUX_DEFER
 653         * before giving up the AUX transaction.
 654         *
 655         * We also try to account for the i2c bus speed.
 656         */
 657        int max_retries = max(7, drm_dp_i2c_retry_count(msg, dp_aux_i2c_speed_khz));
 658
 659        for (retry = 0, defer_i2c = 0; retry < (max_retries + defer_i2c); retry++) {
 660                ret = aux->transfer(aux, msg);
 661                if (ret < 0) {
 662                        if (ret == -EBUSY)
 663                                continue;
 664
 665                        /*
 666                         * While timeouts can be errors, they're usually normal
 667                         * behavior (for instance, when a driver tries to
 668                         * communicate with a non-existant DisplayPort device).
 669                         * Avoid spamming the kernel log with timeout errors.
 670                         */
 671                        if (ret == -ETIMEDOUT)
 672                                DRM_DEBUG_KMS_RATELIMITED("transaction timed out\n");
 673                        else
 674                                DRM_DEBUG_KMS("transaction failed: %d\n", ret);
 675
 676                        return ret;
 677                }
 678
 679
 680                switch (msg->reply & DP_AUX_NATIVE_REPLY_MASK) {
 681                case DP_AUX_NATIVE_REPLY_ACK:
 682                        /*
 683                         * For I2C-over-AUX transactions this isn't enough, we
 684                         * need to check for the I2C ACK reply.
 685                         */
 686                        break;
 687
 688                case DP_AUX_NATIVE_REPLY_NACK:
 689                        DRM_DEBUG_KMS("native nack (result=%d, size=%zu)\n", ret, msg->size);
 690                        return -EREMOTEIO;
 691
 692                case DP_AUX_NATIVE_REPLY_DEFER:
 693                        DRM_DEBUG_KMS("native defer\n");
 694                        /*
 695                         * We could check for I2C bit rate capabilities and if
 696                         * available adjust this interval. We could also be
 697                         * more careful with DP-to-legacy adapters where a
 698                         * long legacy cable may force very low I2C bit rates.
 699                         *
 700                         * For now just defer for long enough to hopefully be
 701                         * safe for all use-cases.
 702                         */
 703                        usleep_range(AUX_RETRY_INTERVAL, AUX_RETRY_INTERVAL + 100);
 704                        continue;
 705
 706                default:
 707                        DRM_ERROR("invalid native reply %#04x\n", msg->reply);
 708                        return -EREMOTEIO;
 709                }
 710
 711                switch (msg->reply & DP_AUX_I2C_REPLY_MASK) {
 712                case DP_AUX_I2C_REPLY_ACK:
 713                        /*
 714                         * Both native ACK and I2C ACK replies received. We
 715                         * can assume the transfer was successful.
 716                         */
 717                        if (ret != msg->size)
 718                                drm_dp_i2c_msg_write_status_update(msg);
 719                        return ret;
 720
 721                case DP_AUX_I2C_REPLY_NACK:
 722                        DRM_DEBUG_KMS("I2C nack (result=%d, size=%zu)\n",
 723                                      ret, msg->size);
 724                        aux->i2c_nack_count++;
 725                        return -EREMOTEIO;
 726
 727                case DP_AUX_I2C_REPLY_DEFER:
 728                        DRM_DEBUG_KMS("I2C defer\n");
 729                        /* DP Compliance Test 4.2.2.5 Requirement:
 730                         * Must have at least 7 retries for I2C defers on the
 731                         * transaction to pass this test
 732                         */
 733                        aux->i2c_defer_count++;
 734                        if (defer_i2c < 7)
 735                                defer_i2c++;
 736                        usleep_range(AUX_RETRY_INTERVAL, AUX_RETRY_INTERVAL + 100);
 737                        drm_dp_i2c_msg_write_status_update(msg);
 738
 739                        continue;
 740
 741                default:
 742                        DRM_ERROR("invalid I2C reply %#04x\n", msg->reply);
 743                        return -EREMOTEIO;
 744                }
 745        }
 746
 747        DRM_DEBUG_KMS("too many retries, giving up\n");
 748        return -EREMOTEIO;
 749}
 750
 751static void drm_dp_i2c_msg_set_request(struct drm_dp_aux_msg *msg,
 752                                       const struct i2c_msg *i2c_msg)
 753{
 754        msg->request = (i2c_msg->flags & I2C_M_RD) ?
 755                DP_AUX_I2C_READ : DP_AUX_I2C_WRITE;
 756        if (!(i2c_msg->flags & I2C_M_STOP))
 757                msg->request |= DP_AUX_I2C_MOT;
 758}
 759
 760/*
 761 * Keep retrying drm_dp_i2c_do_msg until all data has been transferred.
 762 *
 763 * Returns an error code on failure, or a recommended transfer size on success.
 764 */
 765static int drm_dp_i2c_drain_msg(struct drm_dp_aux *aux, struct drm_dp_aux_msg *orig_msg)
 766{
 767        int err, ret = orig_msg->size;
 768        struct drm_dp_aux_msg msg = *orig_msg;
 769
 770        while (msg.size > 0) {
 771                err = drm_dp_i2c_do_msg(aux, &msg);
 772                if (err <= 0)
 773                        return err == 0 ? -EPROTO : err;
 774
 775                if (err < msg.size && err < ret) {
 776                        DRM_DEBUG_KMS("Partial I2C reply: requested %zu bytes got %d bytes\n",
 777                                      msg.size, err);
 778                        ret = err;
 779                }
 780
 781                msg.size -= err;
 782                msg.buffer += err;
 783        }
 784
 785        return ret;
 786}
 787
 788/*
 789 * Bizlink designed DP->DVI-D Dual Link adapters require the I2C over AUX
 790 * packets to be as large as possible. If not, the I2C transactions never
 791 * succeed. Hence the default is maximum.
 792 */
 793static int dp_aux_i2c_transfer_size __read_mostly = DP_AUX_MAX_PAYLOAD_BYTES;
 794module_param_unsafe(dp_aux_i2c_transfer_size, int, 0644);
 795MODULE_PARM_DESC(dp_aux_i2c_transfer_size,
 796                 "Number of bytes to transfer in a single I2C over DP AUX CH message, (1-16, default 16)");
 797
 798static int drm_dp_i2c_xfer(struct i2c_adapter *adapter, struct i2c_msg *msgs,
 799                           int num)
 800{
 801        struct drm_dp_aux *aux = adapter->algo_data;
 802        unsigned int i, j;
 803        unsigned transfer_size;
 804        struct drm_dp_aux_msg msg;
 805        int err = 0;
 806
 807        dp_aux_i2c_transfer_size = clamp(dp_aux_i2c_transfer_size, 1, DP_AUX_MAX_PAYLOAD_BYTES);
 808
 809        memset(&msg, 0, sizeof(msg));
 810
 811        for (i = 0; i < num; i++) {
 812                msg.address = msgs[i].addr;
 813                drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
 814                /* Send a bare address packet to start the transaction.
 815                 * Zero sized messages specify an address only (bare
 816                 * address) transaction.
 817                 */
 818                msg.buffer = NULL;
 819                msg.size = 0;
 820                err = drm_dp_i2c_do_msg(aux, &msg);
 821
 822                /*
 823                 * Reset msg.request in case in case it got
 824                 * changed into a WRITE_STATUS_UPDATE.
 825                 */
 826                drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
 827
 828                if (err < 0)
 829                        break;
 830                /* We want each transaction to be as large as possible, but
 831                 * we'll go to smaller sizes if the hardware gives us a
 832                 * short reply.
 833                 */
 834                transfer_size = dp_aux_i2c_transfer_size;
 835                for (j = 0; j < msgs[i].len; j += msg.size) {
 836                        msg.buffer = msgs[i].buf + j;
 837                        msg.size = min(transfer_size, msgs[i].len - j);
 838
 839                        err = drm_dp_i2c_drain_msg(aux, &msg);
 840
 841                        /*
 842                         * Reset msg.request in case in case it got
 843                         * changed into a WRITE_STATUS_UPDATE.
 844                         */
 845                        drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
 846
 847                        if (err < 0)
 848                                break;
 849                        transfer_size = err;
 850                }
 851                if (err < 0)
 852                        break;
 853        }
 854        if (err >= 0)
 855                err = num;
 856        /* Send a bare address packet to close out the transaction.
 857         * Zero sized messages specify an address only (bare
 858         * address) transaction.
 859         */
 860        msg.request &= ~DP_AUX_I2C_MOT;
 861        msg.buffer = NULL;
 862        msg.size = 0;
 863        (void)drm_dp_i2c_do_msg(aux, &msg);
 864
 865        return err;
 866}
 867
 868static const struct i2c_algorithm drm_dp_i2c_algo = {
 869        .functionality = drm_dp_i2c_functionality,
 870        .master_xfer = drm_dp_i2c_xfer,
 871};
 872
 873static struct drm_dp_aux *i2c_to_aux(struct i2c_adapter *i2c)
 874{
 875        return container_of(i2c, struct drm_dp_aux, ddc);
 876}
 877
 878static void lock_bus(struct i2c_adapter *i2c, unsigned int flags)
 879{
 880        mutex_lock(&i2c_to_aux(i2c)->hw_mutex);
 881}
 882
 883static int trylock_bus(struct i2c_adapter *i2c, unsigned int flags)
 884{
 885        return mutex_trylock(&i2c_to_aux(i2c)->hw_mutex);
 886}
 887
 888static void unlock_bus(struct i2c_adapter *i2c, unsigned int flags)
 889{
 890        mutex_unlock(&i2c_to_aux(i2c)->hw_mutex);
 891}
 892
 893static const struct i2c_lock_operations drm_dp_i2c_lock_ops = {
 894        .lock_bus = lock_bus,
 895        .trylock_bus = trylock_bus,
 896        .unlock_bus = unlock_bus,
 897};
 898
 899static int drm_dp_aux_get_crc(struct drm_dp_aux *aux, u8 *crc)
 900{
 901        u8 buf, count;
 902        int ret;
 903
 904        ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
 905        if (ret < 0)
 906                return ret;
 907
 908        WARN_ON(!(buf & DP_TEST_SINK_START));
 909
 910        ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK_MISC, &buf);
 911        if (ret < 0)
 912                return ret;
 913
 914        count = buf & DP_TEST_COUNT_MASK;
 915        if (count == aux->crc_count)
 916                return -EAGAIN; /* No CRC yet */
 917
 918        aux->crc_count = count;
 919
 920        /*
 921         * At DP_TEST_CRC_R_CR, there's 6 bytes containing CRC data, 2 bytes
 922         * per component (RGB or CrYCb).
 923         */
 924        ret = drm_dp_dpcd_read(aux, DP_TEST_CRC_R_CR, crc, 6);
 925        if (ret < 0)
 926                return ret;
 927
 928        return 0;
 929}
 930
 931static void drm_dp_aux_crc_work(struct work_struct *work)
 932{
 933        struct drm_dp_aux *aux = container_of(work, struct drm_dp_aux,
 934                                              crc_work);
 935        struct drm_crtc *crtc;
 936        u8 crc_bytes[6];
 937        uint32_t crcs[3];
 938        int ret;
 939
 940        if (WARN_ON(!aux->crtc))
 941                return;
 942
 943        crtc = aux->crtc;
 944        while (crtc->crc.opened) {
 945                drm_crtc_wait_one_vblank(crtc);
 946                if (!crtc->crc.opened)
 947                        break;
 948
 949                ret = drm_dp_aux_get_crc(aux, crc_bytes);
 950                if (ret == -EAGAIN) {
 951                        usleep_range(1000, 2000);
 952                        ret = drm_dp_aux_get_crc(aux, crc_bytes);
 953                }
 954
 955                if (ret == -EAGAIN) {
 956                        DRM_DEBUG_KMS("Get CRC failed after retrying: %d\n",
 957                                      ret);
 958                        continue;
 959                } else if (ret) {
 960                        DRM_DEBUG_KMS("Failed to get a CRC: %d\n", ret);
 961                        continue;
 962                }
 963
 964                crcs[0] = crc_bytes[0] | crc_bytes[1] << 8;
 965                crcs[1] = crc_bytes[2] | crc_bytes[3] << 8;
 966                crcs[2] = crc_bytes[4] | crc_bytes[5] << 8;
 967                drm_crtc_add_crc_entry(crtc, false, 0, crcs);
 968        }
 969}
 970
 971/**
 972 * drm_dp_aux_init() - minimally initialise an aux channel
 973 * @aux: DisplayPort AUX channel
 974 *
 975 * If you need to use the drm_dp_aux's i2c adapter prior to registering it
 976 * with the outside world, call drm_dp_aux_init() first. You must still
 977 * call drm_dp_aux_register() once the connector has been registered to
 978 * allow userspace access to the auxiliary DP channel.
 979 */
 980void drm_dp_aux_init(struct drm_dp_aux *aux)
 981{
 982        mutex_init(&aux->hw_mutex);
 983        mutex_init(&aux->cec.lock);
 984        INIT_WORK(&aux->crc_work, drm_dp_aux_crc_work);
 985
 986        aux->ddc.algo = &drm_dp_i2c_algo;
 987        aux->ddc.algo_data = aux;
 988        aux->ddc.retries = 3;
 989
 990        aux->ddc.lock_ops = &drm_dp_i2c_lock_ops;
 991}
 992EXPORT_SYMBOL(drm_dp_aux_init);
 993
 994/**
 995 * drm_dp_aux_register() - initialise and register aux channel
 996 * @aux: DisplayPort AUX channel
 997 *
 998 * Automatically calls drm_dp_aux_init() if this hasn't been done yet.
 999 * This should only be called when the underlying &struct drm_connector is
1000 * initialiazed already. Therefore the best place to call this is from
1001 * &drm_connector_funcs.late_register. Not that drivers which don't follow this
1002 * will Oops when CONFIG_DRM_DP_AUX_CHARDEV is enabled.
1003 *
1004 * Drivers which need to use the aux channel before that point (e.g. at driver
1005 * load time, before drm_dev_register() has been called) need to call
1006 * drm_dp_aux_init().
1007 *
1008 * Returns 0 on success or a negative error code on failure.
1009 */
1010int drm_dp_aux_register(struct drm_dp_aux *aux)
1011{
1012        int ret;
1013
1014        if (!aux->ddc.algo)
1015                drm_dp_aux_init(aux);
1016
1017        aux->ddc.class = I2C_CLASS_DDC;
1018        aux->ddc.owner = THIS_MODULE;
1019        aux->ddc.dev.parent = aux->dev;
1020
1021        strlcpy(aux->ddc.name, aux->name ? aux->name : dev_name(aux->dev),
1022                sizeof(aux->ddc.name));
1023
1024        ret = drm_dp_aux_register_devnode(aux);
1025        if (ret)
1026                return ret;
1027
1028        ret = i2c_add_adapter(&aux->ddc);
1029        if (ret) {
1030                drm_dp_aux_unregister_devnode(aux);
1031                return ret;
1032        }
1033
1034        return 0;
1035}
1036EXPORT_SYMBOL(drm_dp_aux_register);
1037
1038/**
1039 * drm_dp_aux_unregister() - unregister an AUX adapter
1040 * @aux: DisplayPort AUX channel
1041 */
1042void drm_dp_aux_unregister(struct drm_dp_aux *aux)
1043{
1044        drm_dp_aux_unregister_devnode(aux);
1045        i2c_del_adapter(&aux->ddc);
1046}
1047EXPORT_SYMBOL(drm_dp_aux_unregister);
1048
1049#define PSR_SETUP_TIME(x) [DP_PSR_SETUP_TIME_ ## x >> DP_PSR_SETUP_TIME_SHIFT] = (x)
1050
1051/**
1052 * drm_dp_psr_setup_time() - PSR setup in time usec
1053 * @psr_cap: PSR capabilities from DPCD
1054 *
1055 * Returns:
1056 * PSR setup time for the panel in microseconds,  negative
1057 * error code on failure.
1058 */
1059int drm_dp_psr_setup_time(const u8 psr_cap[EDP_PSR_RECEIVER_CAP_SIZE])
1060{
1061        static const u16 psr_setup_time_us[] = {
1062                PSR_SETUP_TIME(330),
1063                PSR_SETUP_TIME(275),
1064                PSR_SETUP_TIME(220),
1065                PSR_SETUP_TIME(165),
1066                PSR_SETUP_TIME(110),
1067                PSR_SETUP_TIME(55),
1068                PSR_SETUP_TIME(0),
1069        };
1070        int i;
1071
1072        i = (psr_cap[1] & DP_PSR_SETUP_TIME_MASK) >> DP_PSR_SETUP_TIME_SHIFT;
1073        if (i >= ARRAY_SIZE(psr_setup_time_us))
1074                return -EINVAL;
1075
1076        return psr_setup_time_us[i];
1077}
1078EXPORT_SYMBOL(drm_dp_psr_setup_time);
1079
1080#undef PSR_SETUP_TIME
1081
1082/**
1083 * drm_dp_start_crc() - start capture of frame CRCs
1084 * @aux: DisplayPort AUX channel
1085 * @crtc: CRTC displaying the frames whose CRCs are to be captured
1086 *
1087 * Returns 0 on success or a negative error code on failure.
1088 */
1089int drm_dp_start_crc(struct drm_dp_aux *aux, struct drm_crtc *crtc)
1090{
1091        u8 buf;
1092        int ret;
1093
1094        ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
1095        if (ret < 0)
1096                return ret;
1097
1098        ret = drm_dp_dpcd_writeb(aux, DP_TEST_SINK, buf | DP_TEST_SINK_START);
1099        if (ret < 0)
1100                return ret;
1101
1102        aux->crc_count = 0;
1103        aux->crtc = crtc;
1104        schedule_work(&aux->crc_work);
1105
1106        return 0;
1107}
1108EXPORT_SYMBOL(drm_dp_start_crc);
1109
1110/**
1111 * drm_dp_stop_crc() - stop capture of frame CRCs
1112 * @aux: DisplayPort AUX channel
1113 *
1114 * Returns 0 on success or a negative error code on failure.
1115 */
1116int drm_dp_stop_crc(struct drm_dp_aux *aux)
1117{
1118        u8 buf;
1119        int ret;
1120
1121        ret = drm_dp_dpcd_readb(aux, DP_TEST_SINK, &buf);
1122        if (ret < 0)
1123                return ret;
1124
1125        ret = drm_dp_dpcd_writeb(aux, DP_TEST_SINK, buf & ~DP_TEST_SINK_START);
1126        if (ret < 0)
1127                return ret;
1128
1129        flush_work(&aux->crc_work);
1130        aux->crtc = NULL;
1131
1132        return 0;
1133}
1134EXPORT_SYMBOL(drm_dp_stop_crc);
1135
1136struct dpcd_quirk {
1137        u8 oui[3];
1138        u8 device_id[6];
1139        bool is_branch;
1140        u32 quirks;
1141};
1142
1143#define OUI(first, second, third) { (first), (second), (third) }
1144#define DEVICE_ID(first, second, third, fourth, fifth, sixth) \
1145        { (first), (second), (third), (fourth), (fifth), (sixth) }
1146
1147#define DEVICE_ID_ANY   DEVICE_ID(0, 0, 0, 0, 0, 0)
1148
1149static const struct dpcd_quirk dpcd_quirk_list[] = {
1150        /* Analogix 7737 needs reduced M and N at HBR2 link rates */
1151        { OUI(0x00, 0x22, 0xb9), DEVICE_ID_ANY, true, BIT(DP_DPCD_QUIRK_CONSTANT_N) },
1152        /* LG LP140WF6-SPM1 eDP panel */
1153        { OUI(0x00, 0x22, 0xb9), DEVICE_ID('s', 'i', 'v', 'a', 'r', 'T'), false, BIT(DP_DPCD_QUIRK_CONSTANT_N) },
1154        /* Apple panels need some additional handling to support PSR */
1155        { OUI(0x00, 0x10, 0xfa), DEVICE_ID_ANY, false, BIT(DP_DPCD_QUIRK_NO_PSR) },
1156        /* CH7511 seems to leave SINK_COUNT zeroed */
1157        { OUI(0x00, 0x00, 0x00), DEVICE_ID('C', 'H', '7', '5', '1', '1'), false, BIT(DP_DPCD_QUIRK_NO_SINK_COUNT) },
1158};
1159
1160#undef OUI
1161
1162/*
1163 * Get a bit mask of DPCD quirks for the sink/branch device identified by
1164 * ident. The quirk data is shared but it's up to the drivers to act on the
1165 * data.
1166 *
1167 * For now, only the OUI (first three bytes) is used, but this may be extended
1168 * to device identification string and hardware/firmware revisions later.
1169 */
1170static u32
1171drm_dp_get_quirks(const struct drm_dp_dpcd_ident *ident, bool is_branch)
1172{
1173        const struct dpcd_quirk *quirk;
1174        u32 quirks = 0;
1175        int i;
1176        u8 any_device[] = DEVICE_ID_ANY;
1177
1178        for (i = 0; i < ARRAY_SIZE(dpcd_quirk_list); i++) {
1179                quirk = &dpcd_quirk_list[i];
1180
1181                if (quirk->is_branch != is_branch)
1182                        continue;
1183
1184                if (memcmp(quirk->oui, ident->oui, sizeof(ident->oui)) != 0)
1185                        continue;
1186
1187                if (memcmp(quirk->device_id, any_device, sizeof(any_device)) != 0 &&
1188                    memcmp(quirk->device_id, ident->device_id, sizeof(ident->device_id)) != 0)
1189                        continue;
1190
1191                quirks |= quirk->quirks;
1192        }
1193
1194        return quirks;
1195}
1196
1197#undef DEVICE_ID_ANY
1198#undef DEVICE_ID
1199
1200/**
1201 * drm_dp_read_desc - read sink/branch descriptor from DPCD
1202 * @aux: DisplayPort AUX channel
1203 * @desc: Device decriptor to fill from DPCD
1204 * @is_branch: true for branch devices, false for sink devices
1205 *
1206 * Read DPCD 0x400 (sink) or 0x500 (branch) into @desc. Also debug log the
1207 * identification.
1208 *
1209 * Returns 0 on success or a negative error code on failure.
1210 */
1211int drm_dp_read_desc(struct drm_dp_aux *aux, struct drm_dp_desc *desc,
1212                     bool is_branch)
1213{
1214        struct drm_dp_dpcd_ident *ident = &desc->ident;
1215        unsigned int offset = is_branch ? DP_BRANCH_OUI : DP_SINK_OUI;
1216        int ret, dev_id_len;
1217
1218        ret = drm_dp_dpcd_read(aux, offset, ident, sizeof(*ident));
1219        if (ret < 0)
1220                return ret;
1221
1222        desc->quirks = drm_dp_get_quirks(ident, is_branch);
1223
1224        dev_id_len = strnlen(ident->device_id, sizeof(ident->device_id));
1225
1226        DRM_DEBUG_KMS("DP %s: OUI %*phD dev-ID %*pE HW-rev %d.%d SW-rev %d.%d quirks 0x%04x\n",
1227                      is_branch ? "branch" : "sink",
1228                      (int)sizeof(ident->oui), ident->oui,
1229                      dev_id_len, ident->device_id,
1230                      ident->hw_rev >> 4, ident->hw_rev & 0xf,
1231                      ident->sw_major_rev, ident->sw_minor_rev,
1232                      desc->quirks);
1233
1234        return 0;
1235}
1236EXPORT_SYMBOL(drm_dp_read_desc);
1237
1238/**
1239 * drm_dp_dsc_sink_max_slice_count() - Get the max slice count
1240 * supported by the DSC sink.
1241 * @dsc_dpcd: DSC capabilities from DPCD
1242 * @is_edp: true if its eDP, false for DP
1243 *
1244 * Read the slice capabilities DPCD register from DSC sink to get
1245 * the maximum slice count supported. This is used to populate
1246 * the DSC parameters in the &struct drm_dsc_config by the driver.
1247 * Driver creates an infoframe using these parameters to populate
1248 * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
1249 * infoframe using the helper function drm_dsc_pps_infoframe_pack()
1250 *
1251 * Returns:
1252 * Maximum slice count supported by DSC sink or 0 its invalid
1253 */
1254u8 drm_dp_dsc_sink_max_slice_count(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE],
1255                                   bool is_edp)
1256{
1257        u8 slice_cap1 = dsc_dpcd[DP_DSC_SLICE_CAP_1 - DP_DSC_SUPPORT];
1258
1259        if (is_edp) {
1260                /* For eDP, register DSC_SLICE_CAPABILITIES_1 gives slice count */
1261                if (slice_cap1 & DP_DSC_4_PER_DP_DSC_SINK)
1262                        return 4;
1263                if (slice_cap1 & DP_DSC_2_PER_DP_DSC_SINK)
1264                        return 2;
1265                if (slice_cap1 & DP_DSC_1_PER_DP_DSC_SINK)
1266                        return 1;
1267        } else {
1268                /* For DP, use values from DSC_SLICE_CAP_1 and DSC_SLICE_CAP2 */
1269                u8 slice_cap2 = dsc_dpcd[DP_DSC_SLICE_CAP_2 - DP_DSC_SUPPORT];
1270
1271                if (slice_cap2 & DP_DSC_24_PER_DP_DSC_SINK)
1272                        return 24;
1273                if (slice_cap2 & DP_DSC_20_PER_DP_DSC_SINK)
1274                        return 20;
1275                if (slice_cap2 & DP_DSC_16_PER_DP_DSC_SINK)
1276                        return 16;
1277                if (slice_cap1 & DP_DSC_12_PER_DP_DSC_SINK)
1278                        return 12;
1279                if (slice_cap1 & DP_DSC_10_PER_DP_DSC_SINK)
1280                        return 10;
1281                if (slice_cap1 & DP_DSC_8_PER_DP_DSC_SINK)
1282                        return 8;
1283                if (slice_cap1 & DP_DSC_6_PER_DP_DSC_SINK)
1284                        return 6;
1285                if (slice_cap1 & DP_DSC_4_PER_DP_DSC_SINK)
1286                        return 4;
1287                if (slice_cap1 & DP_DSC_2_PER_DP_DSC_SINK)
1288                        return 2;
1289                if (slice_cap1 & DP_DSC_1_PER_DP_DSC_SINK)
1290                        return 1;
1291        }
1292
1293        return 0;
1294}
1295EXPORT_SYMBOL(drm_dp_dsc_sink_max_slice_count);
1296
1297/**
1298 * drm_dp_dsc_sink_line_buf_depth() - Get the line buffer depth in bits
1299 * @dsc_dpcd: DSC capabilities from DPCD
1300 *
1301 * Read the DSC DPCD register to parse the line buffer depth in bits which is
1302 * number of bits of precision within the decoder line buffer supported by
1303 * the DSC sink. This is used to populate the DSC parameters in the
1304 * &struct drm_dsc_config by the driver.
1305 * Driver creates an infoframe using these parameters to populate
1306 * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
1307 * infoframe using the helper function drm_dsc_pps_infoframe_pack()
1308 *
1309 * Returns:
1310 * Line buffer depth supported by DSC panel or 0 its invalid
1311 */
1312u8 drm_dp_dsc_sink_line_buf_depth(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE])
1313{
1314        u8 line_buf_depth = dsc_dpcd[DP_DSC_LINE_BUF_BIT_DEPTH - DP_DSC_SUPPORT];
1315
1316        switch (line_buf_depth & DP_DSC_LINE_BUF_BIT_DEPTH_MASK) {
1317        case DP_DSC_LINE_BUF_BIT_DEPTH_9:
1318                return 9;
1319        case DP_DSC_LINE_BUF_BIT_DEPTH_10:
1320                return 10;
1321        case DP_DSC_LINE_BUF_BIT_DEPTH_11:
1322                return 11;
1323        case DP_DSC_LINE_BUF_BIT_DEPTH_12:
1324                return 12;
1325        case DP_DSC_LINE_BUF_BIT_DEPTH_13:
1326                return 13;
1327        case DP_DSC_LINE_BUF_BIT_DEPTH_14:
1328                return 14;
1329        case DP_DSC_LINE_BUF_BIT_DEPTH_15:
1330                return 15;
1331        case DP_DSC_LINE_BUF_BIT_DEPTH_16:
1332                return 16;
1333        case DP_DSC_LINE_BUF_BIT_DEPTH_8:
1334                return 8;
1335        }
1336
1337        return 0;
1338}
1339EXPORT_SYMBOL(drm_dp_dsc_sink_line_buf_depth);
1340
1341/**
1342 * drm_dp_dsc_sink_supported_input_bpcs() - Get all the input bits per component
1343 * values supported by the DSC sink.
1344 * @dsc_dpcd: DSC capabilities from DPCD
1345 * @dsc_bpc: An array to be filled by this helper with supported
1346 *           input bpcs.
1347 *
1348 * Read the DSC DPCD from the sink device to parse the supported bits per
1349 * component values. This is used to populate the DSC parameters
1350 * in the &struct drm_dsc_config by the driver.
1351 * Driver creates an infoframe using these parameters to populate
1352 * &struct drm_dsc_pps_infoframe. These are sent to the sink using DSC
1353 * infoframe using the helper function drm_dsc_pps_infoframe_pack()
1354 *
1355 * Returns:
1356 * Number of input BPC values parsed from the DPCD
1357 */
1358int drm_dp_dsc_sink_supported_input_bpcs(const u8 dsc_dpcd[DP_DSC_RECEIVER_CAP_SIZE],
1359                                         u8 dsc_bpc[3])
1360{
1361        int num_bpc = 0;
1362        u8 color_depth = dsc_dpcd[DP_DSC_DEC_COLOR_DEPTH_CAP - DP_DSC_SUPPORT];
1363
1364        if (color_depth & DP_DSC_12_BPC)
1365                dsc_bpc[num_bpc++] = 12;
1366        if (color_depth & DP_DSC_10_BPC)
1367                dsc_bpc[num_bpc++] = 10;
1368        if (color_depth & DP_DSC_8_BPC)
1369                dsc_bpc[num_bpc++] = 8;
1370
1371        return num_bpc;
1372}
1373EXPORT_SYMBOL(drm_dp_dsc_sink_supported_input_bpcs);
1374