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