• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright © 2014 Red Hat
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/bitfield.h>
24 #include <linux/delay.h>
25 #include <linux/errno.h>
26 #include <linux/i2c.h>
27 #include <linux/init.h>
28 #include <linux/kernel.h>
29 #include <linux/random.h>
30 #include <linux/sched.h>
31 #include <linux/seq_file.h>
32 #include <linux/iopoll.h>
33 
34 #if IS_ENABLED(CONFIG_DRM_DEBUG_DP_MST_TOPOLOGY_REFS)
35 #include <linux/stacktrace.h>
36 #include <linux/sort.h>
37 #include <linux/timekeeping.h>
38 #include <linux/math64.h>
39 #endif
40 
41 #include <drm/drm_atomic.h>
42 #include <drm/drm_atomic_helper.h>
43 #include <drm/drm_dp_mst_helper.h>
44 #include <drm/drm_drv.h>
45 #include <drm/drm_print.h>
46 #include <drm/drm_probe_helper.h>
47 
48 #include "drm_crtc_helper_internal.h"
49 #include "drm_dp_mst_topology_internal.h"
50 
51 /**
52  * DOC: dp mst helper
53  *
54  * These functions contain parts of the DisplayPort 1.2a MultiStream Transport
55  * protocol. The helpers contain a topology manager and bandwidth manager.
56  * The helpers encapsulate the sending and received of sideband msgs.
57  */
58 struct drm_dp_pending_up_req {
59 	struct drm_dp_sideband_msg_hdr hdr;
60 	struct drm_dp_sideband_msg_req_body msg;
61 	struct list_head next;
62 };
63 
64 static bool dump_dp_payload_table(struct drm_dp_mst_topology_mgr *mgr,
65 				  char *buf);
66 
67 static void drm_dp_mst_topology_put_port(struct drm_dp_mst_port *port);
68 
69 static int drm_dp_dpcd_write_payload(struct drm_dp_mst_topology_mgr *mgr,
70 				     int id,
71 				     struct drm_dp_payload *payload);
72 
73 static int drm_dp_send_dpcd_read(struct drm_dp_mst_topology_mgr *mgr,
74 				 struct drm_dp_mst_port *port,
75 				 int offset, int size, u8 *bytes);
76 static int drm_dp_send_dpcd_write(struct drm_dp_mst_topology_mgr *mgr,
77 				  struct drm_dp_mst_port *port,
78 				  int offset, int size, u8 *bytes);
79 
80 static int drm_dp_send_link_address(struct drm_dp_mst_topology_mgr *mgr,
81 				    struct drm_dp_mst_branch *mstb);
82 
83 static void
84 drm_dp_send_clear_payload_id_table(struct drm_dp_mst_topology_mgr *mgr,
85 				   struct drm_dp_mst_branch *mstb);
86 
87 static int drm_dp_send_enum_path_resources(struct drm_dp_mst_topology_mgr *mgr,
88 					   struct drm_dp_mst_branch *mstb,
89 					   struct drm_dp_mst_port *port);
90 static bool drm_dp_validate_guid(struct drm_dp_mst_topology_mgr *mgr,
91 				 u8 *guid);
92 
93 static int drm_dp_mst_register_i2c_bus(struct drm_dp_mst_port *port);
94 static void drm_dp_mst_unregister_i2c_bus(struct drm_dp_mst_port *port);
95 static void drm_dp_mst_kick_tx(struct drm_dp_mst_topology_mgr *mgr);
96 
97 static bool drm_dp_mst_port_downstream_of_branch(struct drm_dp_mst_port *port,
98 						 struct drm_dp_mst_branch *branch);
99 
100 #define DBG_PREFIX "[dp_mst]"
101 
102 #define DP_STR(x) [DP_ ## x] = #x
103 
drm_dp_mst_req_type_str(u8 req_type)104 static const char *drm_dp_mst_req_type_str(u8 req_type)
105 {
106 	static const char * const req_type_str[] = {
107 		DP_STR(GET_MSG_TRANSACTION_VERSION),
108 		DP_STR(LINK_ADDRESS),
109 		DP_STR(CONNECTION_STATUS_NOTIFY),
110 		DP_STR(ENUM_PATH_RESOURCES),
111 		DP_STR(ALLOCATE_PAYLOAD),
112 		DP_STR(QUERY_PAYLOAD),
113 		DP_STR(RESOURCE_STATUS_NOTIFY),
114 		DP_STR(CLEAR_PAYLOAD_ID_TABLE),
115 		DP_STR(REMOTE_DPCD_READ),
116 		DP_STR(REMOTE_DPCD_WRITE),
117 		DP_STR(REMOTE_I2C_READ),
118 		DP_STR(REMOTE_I2C_WRITE),
119 		DP_STR(POWER_UP_PHY),
120 		DP_STR(POWER_DOWN_PHY),
121 		DP_STR(SINK_EVENT_NOTIFY),
122 		DP_STR(QUERY_STREAM_ENC_STATUS),
123 	};
124 
125 	if (req_type >= ARRAY_SIZE(req_type_str) ||
126 	    !req_type_str[req_type])
127 		return "unknown";
128 
129 	return req_type_str[req_type];
130 }
131 
132 #undef DP_STR
133 #define DP_STR(x) [DP_NAK_ ## x] = #x
134 
drm_dp_mst_nak_reason_str(u8 nak_reason)135 static const char *drm_dp_mst_nak_reason_str(u8 nak_reason)
136 {
137 	static const char * const nak_reason_str[] = {
138 		DP_STR(WRITE_FAILURE),
139 		DP_STR(INVALID_READ),
140 		DP_STR(CRC_FAILURE),
141 		DP_STR(BAD_PARAM),
142 		DP_STR(DEFER),
143 		DP_STR(LINK_FAILURE),
144 		DP_STR(NO_RESOURCES),
145 		DP_STR(DPCD_FAIL),
146 		DP_STR(I2C_NAK),
147 		DP_STR(ALLOCATE_FAIL),
148 	};
149 
150 	if (nak_reason >= ARRAY_SIZE(nak_reason_str) ||
151 	    !nak_reason_str[nak_reason])
152 		return "unknown";
153 
154 	return nak_reason_str[nak_reason];
155 }
156 
157 #undef DP_STR
158 #define DP_STR(x) [DRM_DP_SIDEBAND_TX_ ## x] = #x
159 
drm_dp_mst_sideband_tx_state_str(int state)160 static const char *drm_dp_mst_sideband_tx_state_str(int state)
161 {
162 	static const char * const sideband_reason_str[] = {
163 		DP_STR(QUEUED),
164 		DP_STR(START_SEND),
165 		DP_STR(SENT),
166 		DP_STR(RX),
167 		DP_STR(TIMEOUT),
168 	};
169 
170 	if (state >= ARRAY_SIZE(sideband_reason_str) ||
171 	    !sideband_reason_str[state])
172 		return "unknown";
173 
174 	return sideband_reason_str[state];
175 }
176 
177 static int
drm_dp_mst_rad_to_str(const u8 rad[8],u8 lct,char * out,size_t len)178 drm_dp_mst_rad_to_str(const u8 rad[8], u8 lct, char *out, size_t len)
179 {
180 	int i;
181 	u8 unpacked_rad[16];
182 
183 	for (i = 0; i < lct; i++) {
184 		if (i % 2)
185 			unpacked_rad[i] = rad[i / 2] >> 4;
186 		else
187 			unpacked_rad[i] = rad[i / 2] & BIT_MASK(4);
188 	}
189 
190 	/* TODO: Eventually add something to printk so we can format the rad
191 	 * like this: 1.2.3
192 	 */
193 	return snprintf(out, len, "%*phC", lct, unpacked_rad);
194 }
195 
196 /* sideband msg handling */
drm_dp_msg_header_crc4(const uint8_t * data,size_t num_nibbles)197 static u8 drm_dp_msg_header_crc4(const uint8_t *data, size_t num_nibbles)
198 {
199 	u8 bitmask = 0x80;
200 	u8 bitshift = 7;
201 	u8 array_index = 0;
202 	int number_of_bits = num_nibbles * 4;
203 	u8 remainder = 0;
204 
205 	while (number_of_bits != 0) {
206 		number_of_bits--;
207 		remainder <<= 1;
208 		remainder |= (data[array_index] & bitmask) >> bitshift;
209 		bitmask >>= 1;
210 		bitshift--;
211 		if (bitmask == 0) {
212 			bitmask = 0x80;
213 			bitshift = 7;
214 			array_index++;
215 		}
216 		if ((remainder & 0x10) == 0x10)
217 			remainder ^= 0x13;
218 	}
219 
220 	number_of_bits = 4;
221 	while (number_of_bits != 0) {
222 		number_of_bits--;
223 		remainder <<= 1;
224 		if ((remainder & 0x10) != 0)
225 			remainder ^= 0x13;
226 	}
227 
228 	return remainder;
229 }
230 
drm_dp_msg_data_crc4(const uint8_t * data,u8 number_of_bytes)231 static u8 drm_dp_msg_data_crc4(const uint8_t *data, u8 number_of_bytes)
232 {
233 	u8 bitmask = 0x80;
234 	u8 bitshift = 7;
235 	u8 array_index = 0;
236 	int number_of_bits = number_of_bytes * 8;
237 	u16 remainder = 0;
238 
239 	while (number_of_bits != 0) {
240 		number_of_bits--;
241 		remainder <<= 1;
242 		remainder |= (data[array_index] & bitmask) >> bitshift;
243 		bitmask >>= 1;
244 		bitshift--;
245 		if (bitmask == 0) {
246 			bitmask = 0x80;
247 			bitshift = 7;
248 			array_index++;
249 		}
250 		if ((remainder & 0x100) == 0x100)
251 			remainder ^= 0xd5;
252 	}
253 
254 	number_of_bits = 8;
255 	while (number_of_bits != 0) {
256 		number_of_bits--;
257 		remainder <<= 1;
258 		if ((remainder & 0x100) != 0)
259 			remainder ^= 0xd5;
260 	}
261 
262 	return remainder & 0xff;
263 }
drm_dp_calc_sb_hdr_size(struct drm_dp_sideband_msg_hdr * hdr)264 static inline u8 drm_dp_calc_sb_hdr_size(struct drm_dp_sideband_msg_hdr *hdr)
265 {
266 	u8 size = 3;
267 
268 	size += (hdr->lct / 2);
269 	return size;
270 }
271 
drm_dp_encode_sideband_msg_hdr(struct drm_dp_sideband_msg_hdr * hdr,u8 * buf,int * len)272 static void drm_dp_encode_sideband_msg_hdr(struct drm_dp_sideband_msg_hdr *hdr,
273 					   u8 *buf, int *len)
274 {
275 	int idx = 0;
276 	int i;
277 	u8 crc4;
278 
279 	buf[idx++] = ((hdr->lct & 0xf) << 4) | (hdr->lcr & 0xf);
280 	for (i = 0; i < (hdr->lct / 2); i++)
281 		buf[idx++] = hdr->rad[i];
282 	buf[idx++] = (hdr->broadcast << 7) | (hdr->path_msg << 6) |
283 		(hdr->msg_len & 0x3f);
284 	buf[idx++] = (hdr->somt << 7) | (hdr->eomt << 6) | (hdr->seqno << 4);
285 
286 	crc4 = drm_dp_msg_header_crc4(buf, (idx * 2) - 1);
287 	buf[idx - 1] |= (crc4 & 0xf);
288 
289 	*len = idx;
290 }
291 
drm_dp_decode_sideband_msg_hdr(struct drm_dp_sideband_msg_hdr * hdr,u8 * buf,int buflen,u8 * hdrlen)292 static bool drm_dp_decode_sideband_msg_hdr(struct drm_dp_sideband_msg_hdr *hdr,
293 					   u8 *buf, int buflen, u8 *hdrlen)
294 {
295 	u8 crc4;
296 	u8 len;
297 	int i;
298 	u8 idx;
299 
300 	if (buf[0] == 0)
301 		return false;
302 	len = 3;
303 	len += ((buf[0] & 0xf0) >> 4) / 2;
304 	if (len > buflen)
305 		return false;
306 	crc4 = drm_dp_msg_header_crc4(buf, (len * 2) - 1);
307 
308 	if ((crc4 & 0xf) != (buf[len - 1] & 0xf)) {
309 		DRM_DEBUG_KMS("crc4 mismatch 0x%x 0x%x\n", crc4, buf[len - 1]);
310 		return false;
311 	}
312 
313 	hdr->lct = (buf[0] & 0xf0) >> 4;
314 	hdr->lcr = (buf[0] & 0xf);
315 	idx = 1;
316 	for (i = 0; i < (hdr->lct / 2); i++)
317 		hdr->rad[i] = buf[idx++];
318 	hdr->broadcast = (buf[idx] >> 7) & 0x1;
319 	hdr->path_msg = (buf[idx] >> 6) & 0x1;
320 	hdr->msg_len = buf[idx] & 0x3f;
321 	if (hdr->msg_len < 1)		/* min space for body CRC */
322 		return false;
323 
324 	idx++;
325 	hdr->somt = (buf[idx] >> 7) & 0x1;
326 	hdr->eomt = (buf[idx] >> 6) & 0x1;
327 	hdr->seqno = (buf[idx] >> 4) & 0x1;
328 	idx++;
329 	*hdrlen = idx;
330 	return true;
331 }
332 
333 void
drm_dp_encode_sideband_req(const struct drm_dp_sideband_msg_req_body * req,struct drm_dp_sideband_msg_tx * raw)334 drm_dp_encode_sideband_req(const struct drm_dp_sideband_msg_req_body *req,
335 			   struct drm_dp_sideband_msg_tx *raw)
336 {
337 	int idx = 0;
338 	int i;
339 	u8 *buf = raw->msg;
340 
341 	buf[idx++] = req->req_type & 0x7f;
342 
343 	switch (req->req_type) {
344 	case DP_ENUM_PATH_RESOURCES:
345 	case DP_POWER_DOWN_PHY:
346 	case DP_POWER_UP_PHY:
347 		buf[idx] = (req->u.port_num.port_number & 0xf) << 4;
348 		idx++;
349 		break;
350 	case DP_ALLOCATE_PAYLOAD:
351 		buf[idx] = (req->u.allocate_payload.port_number & 0xf) << 4 |
352 			(req->u.allocate_payload.number_sdp_streams & 0xf);
353 		idx++;
354 		buf[idx] = (req->u.allocate_payload.vcpi & 0x7f);
355 		idx++;
356 		buf[idx] = (req->u.allocate_payload.pbn >> 8);
357 		idx++;
358 		buf[idx] = (req->u.allocate_payload.pbn & 0xff);
359 		idx++;
360 		for (i = 0; i < req->u.allocate_payload.number_sdp_streams / 2; i++) {
361 			buf[idx] = ((req->u.allocate_payload.sdp_stream_sink[i * 2] & 0xf) << 4) |
362 				(req->u.allocate_payload.sdp_stream_sink[i * 2 + 1] & 0xf);
363 			idx++;
364 		}
365 		if (req->u.allocate_payload.number_sdp_streams & 1) {
366 			i = req->u.allocate_payload.number_sdp_streams - 1;
367 			buf[idx] = (req->u.allocate_payload.sdp_stream_sink[i] & 0xf) << 4;
368 			idx++;
369 		}
370 		break;
371 	case DP_QUERY_PAYLOAD:
372 		buf[idx] = (req->u.query_payload.port_number & 0xf) << 4;
373 		idx++;
374 		buf[idx] = (req->u.query_payload.vcpi & 0x7f);
375 		idx++;
376 		break;
377 	case DP_REMOTE_DPCD_READ:
378 		buf[idx] = (req->u.dpcd_read.port_number & 0xf) << 4;
379 		buf[idx] |= ((req->u.dpcd_read.dpcd_address & 0xf0000) >> 16) & 0xf;
380 		idx++;
381 		buf[idx] = (req->u.dpcd_read.dpcd_address & 0xff00) >> 8;
382 		idx++;
383 		buf[idx] = (req->u.dpcd_read.dpcd_address & 0xff);
384 		idx++;
385 		buf[idx] = (req->u.dpcd_read.num_bytes);
386 		idx++;
387 		break;
388 
389 	case DP_REMOTE_DPCD_WRITE:
390 		buf[idx] = (req->u.dpcd_write.port_number & 0xf) << 4;
391 		buf[idx] |= ((req->u.dpcd_write.dpcd_address & 0xf0000) >> 16) & 0xf;
392 		idx++;
393 		buf[idx] = (req->u.dpcd_write.dpcd_address & 0xff00) >> 8;
394 		idx++;
395 		buf[idx] = (req->u.dpcd_write.dpcd_address & 0xff);
396 		idx++;
397 		buf[idx] = (req->u.dpcd_write.num_bytes);
398 		idx++;
399 		memcpy(&buf[idx], req->u.dpcd_write.bytes, req->u.dpcd_write.num_bytes);
400 		idx += req->u.dpcd_write.num_bytes;
401 		break;
402 	case DP_REMOTE_I2C_READ:
403 		buf[idx] = (req->u.i2c_read.port_number & 0xf) << 4;
404 		buf[idx] |= (req->u.i2c_read.num_transactions & 0x3);
405 		idx++;
406 		for (i = 0; i < (req->u.i2c_read.num_transactions & 0x3); i++) {
407 			buf[idx] = req->u.i2c_read.transactions[i].i2c_dev_id & 0x7f;
408 			idx++;
409 			buf[idx] = req->u.i2c_read.transactions[i].num_bytes;
410 			idx++;
411 			memcpy(&buf[idx], req->u.i2c_read.transactions[i].bytes, req->u.i2c_read.transactions[i].num_bytes);
412 			idx += req->u.i2c_read.transactions[i].num_bytes;
413 
414 			buf[idx] = (req->u.i2c_read.transactions[i].no_stop_bit & 0x1) << 4;
415 			buf[idx] |= (req->u.i2c_read.transactions[i].i2c_transaction_delay & 0xf);
416 			idx++;
417 		}
418 		buf[idx] = (req->u.i2c_read.read_i2c_device_id) & 0x7f;
419 		idx++;
420 		buf[idx] = (req->u.i2c_read.num_bytes_read);
421 		idx++;
422 		break;
423 
424 	case DP_REMOTE_I2C_WRITE:
425 		buf[idx] = (req->u.i2c_write.port_number & 0xf) << 4;
426 		idx++;
427 		buf[idx] = (req->u.i2c_write.write_i2c_device_id) & 0x7f;
428 		idx++;
429 		buf[idx] = (req->u.i2c_write.num_bytes);
430 		idx++;
431 		memcpy(&buf[idx], req->u.i2c_write.bytes, req->u.i2c_write.num_bytes);
432 		idx += req->u.i2c_write.num_bytes;
433 		break;
434 	case DP_QUERY_STREAM_ENC_STATUS: {
435 		const struct drm_dp_query_stream_enc_status *msg;
436 
437 		msg = &req->u.enc_status;
438 		buf[idx] = msg->stream_id;
439 		idx++;
440 		memcpy(&buf[idx], msg->client_id, sizeof(msg->client_id));
441 		idx += sizeof(msg->client_id);
442 		buf[idx] = 0;
443 		buf[idx] |= FIELD_PREP(GENMASK(1, 0), msg->stream_event);
444 		buf[idx] |= msg->valid_stream_event ? BIT(2) : 0;
445 		buf[idx] |= FIELD_PREP(GENMASK(4, 3), msg->stream_behavior);
446 		buf[idx] |= msg->valid_stream_behavior ? BIT(5) : 0;
447 		idx++;
448 		}
449 		break;
450 	}
451 	raw->cur_len = idx;
452 }
453 EXPORT_SYMBOL_FOR_TESTS_ONLY(drm_dp_encode_sideband_req);
454 
455 /* Decode a sideband request we've encoded, mainly used for debugging */
456 int
drm_dp_decode_sideband_req(const struct drm_dp_sideband_msg_tx * raw,struct drm_dp_sideband_msg_req_body * req)457 drm_dp_decode_sideband_req(const struct drm_dp_sideband_msg_tx *raw,
458 			   struct drm_dp_sideband_msg_req_body *req)
459 {
460 	const u8 *buf = raw->msg;
461 	int i, idx = 0;
462 
463 	req->req_type = buf[idx++] & 0x7f;
464 	switch (req->req_type) {
465 	case DP_ENUM_PATH_RESOURCES:
466 	case DP_POWER_DOWN_PHY:
467 	case DP_POWER_UP_PHY:
468 		req->u.port_num.port_number = (buf[idx] >> 4) & 0xf;
469 		break;
470 	case DP_ALLOCATE_PAYLOAD:
471 		{
472 			struct drm_dp_allocate_payload *a =
473 				&req->u.allocate_payload;
474 
475 			a->number_sdp_streams = buf[idx] & 0xf;
476 			a->port_number = (buf[idx] >> 4) & 0xf;
477 
478 			WARN_ON(buf[++idx] & 0x80);
479 			a->vcpi = buf[idx] & 0x7f;
480 
481 			a->pbn = buf[++idx] << 8;
482 			a->pbn |= buf[++idx];
483 
484 			idx++;
485 			for (i = 0; i < a->number_sdp_streams; i++) {
486 				a->sdp_stream_sink[i] =
487 					(buf[idx + (i / 2)] >> ((i % 2) ? 0 : 4)) & 0xf;
488 			}
489 		}
490 		break;
491 	case DP_QUERY_PAYLOAD:
492 		req->u.query_payload.port_number = (buf[idx] >> 4) & 0xf;
493 		WARN_ON(buf[++idx] & 0x80);
494 		req->u.query_payload.vcpi = buf[idx] & 0x7f;
495 		break;
496 	case DP_REMOTE_DPCD_READ:
497 		{
498 			struct drm_dp_remote_dpcd_read *r = &req->u.dpcd_read;
499 
500 			r->port_number = (buf[idx] >> 4) & 0xf;
501 
502 			r->dpcd_address = (buf[idx] << 16) & 0xf0000;
503 			r->dpcd_address |= (buf[++idx] << 8) & 0xff00;
504 			r->dpcd_address |= buf[++idx] & 0xff;
505 
506 			r->num_bytes = buf[++idx];
507 		}
508 		break;
509 	case DP_REMOTE_DPCD_WRITE:
510 		{
511 			struct drm_dp_remote_dpcd_write *w =
512 				&req->u.dpcd_write;
513 
514 			w->port_number = (buf[idx] >> 4) & 0xf;
515 
516 			w->dpcd_address = (buf[idx] << 16) & 0xf0000;
517 			w->dpcd_address |= (buf[++idx] << 8) & 0xff00;
518 			w->dpcd_address |= buf[++idx] & 0xff;
519 
520 			w->num_bytes = buf[++idx];
521 
522 			w->bytes = kmemdup(&buf[++idx], w->num_bytes,
523 					   GFP_KERNEL);
524 			if (!w->bytes)
525 				return -ENOMEM;
526 		}
527 		break;
528 	case DP_REMOTE_I2C_READ:
529 		{
530 			struct drm_dp_remote_i2c_read *r = &req->u.i2c_read;
531 			struct drm_dp_remote_i2c_read_tx *tx;
532 			bool failed = false;
533 
534 			r->num_transactions = buf[idx] & 0x3;
535 			r->port_number = (buf[idx] >> 4) & 0xf;
536 			for (i = 0; i < r->num_transactions; i++) {
537 				tx = &r->transactions[i];
538 
539 				tx->i2c_dev_id = buf[++idx] & 0x7f;
540 				tx->num_bytes = buf[++idx];
541 				tx->bytes = kmemdup(&buf[++idx],
542 						    tx->num_bytes,
543 						    GFP_KERNEL);
544 				if (!tx->bytes) {
545 					failed = true;
546 					break;
547 				}
548 				idx += tx->num_bytes;
549 				tx->no_stop_bit = (buf[idx] >> 5) & 0x1;
550 				tx->i2c_transaction_delay = buf[idx] & 0xf;
551 			}
552 
553 			if (failed) {
554 				for (i = 0; i < r->num_transactions; i++) {
555 					tx = &r->transactions[i];
556 					kfree(tx->bytes);
557 				}
558 				return -ENOMEM;
559 			}
560 
561 			r->read_i2c_device_id = buf[++idx] & 0x7f;
562 			r->num_bytes_read = buf[++idx];
563 		}
564 		break;
565 	case DP_REMOTE_I2C_WRITE:
566 		{
567 			struct drm_dp_remote_i2c_write *w = &req->u.i2c_write;
568 
569 			w->port_number = (buf[idx] >> 4) & 0xf;
570 			w->write_i2c_device_id = buf[++idx] & 0x7f;
571 			w->num_bytes = buf[++idx];
572 			w->bytes = kmemdup(&buf[++idx], w->num_bytes,
573 					   GFP_KERNEL);
574 			if (!w->bytes)
575 				return -ENOMEM;
576 		}
577 		break;
578 	case DP_QUERY_STREAM_ENC_STATUS:
579 		req->u.enc_status.stream_id = buf[idx++];
580 		for (i = 0; i < sizeof(req->u.enc_status.client_id); i++)
581 			req->u.enc_status.client_id[i] = buf[idx++];
582 
583 		req->u.enc_status.stream_event = FIELD_GET(GENMASK(1, 0),
584 							   buf[idx]);
585 		req->u.enc_status.valid_stream_event = FIELD_GET(BIT(2),
586 								 buf[idx]);
587 		req->u.enc_status.stream_behavior = FIELD_GET(GENMASK(4, 3),
588 							      buf[idx]);
589 		req->u.enc_status.valid_stream_behavior = FIELD_GET(BIT(5),
590 								    buf[idx]);
591 		break;
592 	}
593 
594 	return 0;
595 }
596 EXPORT_SYMBOL_FOR_TESTS_ONLY(drm_dp_decode_sideband_req);
597 
598 void
drm_dp_dump_sideband_msg_req_body(const struct drm_dp_sideband_msg_req_body * req,int indent,struct drm_printer * printer)599 drm_dp_dump_sideband_msg_req_body(const struct drm_dp_sideband_msg_req_body *req,
600 				  int indent, struct drm_printer *printer)
601 {
602 	int i;
603 
604 #define P(f, ...) drm_printf_indent(printer, indent, f, ##__VA_ARGS__)
605 	if (req->req_type == DP_LINK_ADDRESS) {
606 		/* No contents to print */
607 		P("type=%s\n", drm_dp_mst_req_type_str(req->req_type));
608 		return;
609 	}
610 
611 	P("type=%s contents:\n", drm_dp_mst_req_type_str(req->req_type));
612 	indent++;
613 
614 	switch (req->req_type) {
615 	case DP_ENUM_PATH_RESOURCES:
616 	case DP_POWER_DOWN_PHY:
617 	case DP_POWER_UP_PHY:
618 		P("port=%d\n", req->u.port_num.port_number);
619 		break;
620 	case DP_ALLOCATE_PAYLOAD:
621 		P("port=%d vcpi=%d pbn=%d sdp_streams=%d %*ph\n",
622 		  req->u.allocate_payload.port_number,
623 		  req->u.allocate_payload.vcpi, req->u.allocate_payload.pbn,
624 		  req->u.allocate_payload.number_sdp_streams,
625 		  req->u.allocate_payload.number_sdp_streams,
626 		  req->u.allocate_payload.sdp_stream_sink);
627 		break;
628 	case DP_QUERY_PAYLOAD:
629 		P("port=%d vcpi=%d\n",
630 		  req->u.query_payload.port_number,
631 		  req->u.query_payload.vcpi);
632 		break;
633 	case DP_REMOTE_DPCD_READ:
634 		P("port=%d dpcd_addr=%05x len=%d\n",
635 		  req->u.dpcd_read.port_number, req->u.dpcd_read.dpcd_address,
636 		  req->u.dpcd_read.num_bytes);
637 		break;
638 	case DP_REMOTE_DPCD_WRITE:
639 		P("port=%d addr=%05x len=%d: %*ph\n",
640 		  req->u.dpcd_write.port_number,
641 		  req->u.dpcd_write.dpcd_address,
642 		  req->u.dpcd_write.num_bytes, req->u.dpcd_write.num_bytes,
643 		  req->u.dpcd_write.bytes);
644 		break;
645 	case DP_REMOTE_I2C_READ:
646 		P("port=%d num_tx=%d id=%d size=%d:\n",
647 		  req->u.i2c_read.port_number,
648 		  req->u.i2c_read.num_transactions,
649 		  req->u.i2c_read.read_i2c_device_id,
650 		  req->u.i2c_read.num_bytes_read);
651 
652 		indent++;
653 		for (i = 0; i < req->u.i2c_read.num_transactions; i++) {
654 			const struct drm_dp_remote_i2c_read_tx *rtx =
655 				&req->u.i2c_read.transactions[i];
656 
657 			P("%d: id=%03d size=%03d no_stop_bit=%d tx_delay=%03d: %*ph\n",
658 			  i, rtx->i2c_dev_id, rtx->num_bytes,
659 			  rtx->no_stop_bit, rtx->i2c_transaction_delay,
660 			  rtx->num_bytes, rtx->bytes);
661 		}
662 		break;
663 	case DP_REMOTE_I2C_WRITE:
664 		P("port=%d id=%d size=%d: %*ph\n",
665 		  req->u.i2c_write.port_number,
666 		  req->u.i2c_write.write_i2c_device_id,
667 		  req->u.i2c_write.num_bytes, req->u.i2c_write.num_bytes,
668 		  req->u.i2c_write.bytes);
669 		break;
670 	case DP_QUERY_STREAM_ENC_STATUS:
671 		P("stream_id=%u client_id=%*ph stream_event=%x "
672 		  "valid_event=%d stream_behavior=%x valid_behavior=%d",
673 		  req->u.enc_status.stream_id,
674 		  (int)ARRAY_SIZE(req->u.enc_status.client_id),
675 		  req->u.enc_status.client_id, req->u.enc_status.stream_event,
676 		  req->u.enc_status.valid_stream_event,
677 		  req->u.enc_status.stream_behavior,
678 		  req->u.enc_status.valid_stream_behavior);
679 		break;
680 	default:
681 		P("???\n");
682 		break;
683 	}
684 #undef P
685 }
686 EXPORT_SYMBOL_FOR_TESTS_ONLY(drm_dp_dump_sideband_msg_req_body);
687 
688 static inline void
drm_dp_mst_dump_sideband_msg_tx(struct drm_printer * p,const struct drm_dp_sideband_msg_tx * txmsg)689 drm_dp_mst_dump_sideband_msg_tx(struct drm_printer *p,
690 				const struct drm_dp_sideband_msg_tx *txmsg)
691 {
692 	struct drm_dp_sideband_msg_req_body req;
693 	char buf[64];
694 	int ret;
695 	int i;
696 
697 	drm_dp_mst_rad_to_str(txmsg->dst->rad, txmsg->dst->lct, buf,
698 			      sizeof(buf));
699 	drm_printf(p, "txmsg cur_offset=%x cur_len=%x seqno=%x state=%s path_msg=%d dst=%s\n",
700 		   txmsg->cur_offset, txmsg->cur_len, txmsg->seqno,
701 		   drm_dp_mst_sideband_tx_state_str(txmsg->state),
702 		   txmsg->path_msg, buf);
703 
704 	ret = drm_dp_decode_sideband_req(txmsg, &req);
705 	if (ret) {
706 		drm_printf(p, "<failed to decode sideband req: %d>\n", ret);
707 		return;
708 	}
709 	drm_dp_dump_sideband_msg_req_body(&req, 1, p);
710 
711 	switch (req.req_type) {
712 	case DP_REMOTE_DPCD_WRITE:
713 		kfree(req.u.dpcd_write.bytes);
714 		break;
715 	case DP_REMOTE_I2C_READ:
716 		for (i = 0; i < req.u.i2c_read.num_transactions; i++)
717 			kfree(req.u.i2c_read.transactions[i].bytes);
718 		break;
719 	case DP_REMOTE_I2C_WRITE:
720 		kfree(req.u.i2c_write.bytes);
721 		break;
722 	}
723 }
724 
drm_dp_crc_sideband_chunk_req(u8 * msg,u8 len)725 static void drm_dp_crc_sideband_chunk_req(u8 *msg, u8 len)
726 {
727 	u8 crc4;
728 
729 	crc4 = drm_dp_msg_data_crc4(msg, len);
730 	msg[len] = crc4;
731 }
732 
drm_dp_encode_sideband_reply(struct drm_dp_sideband_msg_reply_body * rep,struct drm_dp_sideband_msg_tx * raw)733 static void drm_dp_encode_sideband_reply(struct drm_dp_sideband_msg_reply_body *rep,
734 					 struct drm_dp_sideband_msg_tx *raw)
735 {
736 	int idx = 0;
737 	u8 *buf = raw->msg;
738 
739 	buf[idx++] = (rep->reply_type & 0x1) << 7 | (rep->req_type & 0x7f);
740 
741 	raw->cur_len = idx;
742 }
743 
drm_dp_sideband_msg_set_header(struct drm_dp_sideband_msg_rx * msg,struct drm_dp_sideband_msg_hdr * hdr,u8 hdrlen)744 static int drm_dp_sideband_msg_set_header(struct drm_dp_sideband_msg_rx *msg,
745 					  struct drm_dp_sideband_msg_hdr *hdr,
746 					  u8 hdrlen)
747 {
748 	/*
749 	 * ignore out-of-order messages or messages that are part of a
750 	 * failed transaction
751 	 */
752 	if (!hdr->somt && !msg->have_somt)
753 		return false;
754 
755 	/* get length contained in this portion */
756 	msg->curchunk_idx = 0;
757 	msg->curchunk_len = hdr->msg_len;
758 	msg->curchunk_hdrlen = hdrlen;
759 
760 	/* we have already gotten an somt - don't bother parsing */
761 	if (hdr->somt && msg->have_somt)
762 		return false;
763 
764 	if (hdr->somt) {
765 		memcpy(&msg->initial_hdr, hdr,
766 		       sizeof(struct drm_dp_sideband_msg_hdr));
767 		msg->have_somt = true;
768 	}
769 	if (hdr->eomt)
770 		msg->have_eomt = true;
771 
772 	return true;
773 }
774 
775 /* this adds a chunk of msg to the builder to get the final msg */
drm_dp_sideband_append_payload(struct drm_dp_sideband_msg_rx * msg,u8 * replybuf,u8 replybuflen)776 static bool drm_dp_sideband_append_payload(struct drm_dp_sideband_msg_rx *msg,
777 					   u8 *replybuf, u8 replybuflen)
778 {
779 	u8 crc4;
780 
781 	memcpy(&msg->chunk[msg->curchunk_idx], replybuf, replybuflen);
782 	msg->curchunk_idx += replybuflen;
783 
784 	if (msg->curchunk_idx >= msg->curchunk_len) {
785 		/* do CRC */
786 		crc4 = drm_dp_msg_data_crc4(msg->chunk, msg->curchunk_len - 1);
787 		if (crc4 != msg->chunk[msg->curchunk_len - 1])
788 			print_hex_dump(KERN_DEBUG, "wrong crc",
789 				       DUMP_PREFIX_NONE, 16, 1,
790 				       msg->chunk,  msg->curchunk_len, false);
791 		/* copy chunk into bigger msg */
792 		memcpy(&msg->msg[msg->curlen], msg->chunk, msg->curchunk_len - 1);
793 		msg->curlen += msg->curchunk_len - 1;
794 	}
795 	return true;
796 }
797 
drm_dp_sideband_parse_link_address(struct drm_dp_sideband_msg_rx * raw,struct drm_dp_sideband_msg_reply_body * repmsg)798 static bool drm_dp_sideband_parse_link_address(struct drm_dp_sideband_msg_rx *raw,
799 					       struct drm_dp_sideband_msg_reply_body *repmsg)
800 {
801 	int idx = 1;
802 	int i;
803 
804 	memcpy(repmsg->u.link_addr.guid, &raw->msg[idx], 16);
805 	idx += 16;
806 	repmsg->u.link_addr.nports = raw->msg[idx] & 0xf;
807 	idx++;
808 	if (idx > raw->curlen)
809 		goto fail_len;
810 	for (i = 0; i < repmsg->u.link_addr.nports; i++) {
811 		if (raw->msg[idx] & 0x80)
812 			repmsg->u.link_addr.ports[i].input_port = 1;
813 
814 		repmsg->u.link_addr.ports[i].peer_device_type = (raw->msg[idx] >> 4) & 0x7;
815 		repmsg->u.link_addr.ports[i].port_number = (raw->msg[idx] & 0xf);
816 
817 		idx++;
818 		if (idx > raw->curlen)
819 			goto fail_len;
820 		repmsg->u.link_addr.ports[i].mcs = (raw->msg[idx] >> 7) & 0x1;
821 		repmsg->u.link_addr.ports[i].ddps = (raw->msg[idx] >> 6) & 0x1;
822 		if (repmsg->u.link_addr.ports[i].input_port == 0)
823 			repmsg->u.link_addr.ports[i].legacy_device_plug_status = (raw->msg[idx] >> 5) & 0x1;
824 		idx++;
825 		if (idx > raw->curlen)
826 			goto fail_len;
827 		if (repmsg->u.link_addr.ports[i].input_port == 0) {
828 			repmsg->u.link_addr.ports[i].dpcd_revision = (raw->msg[idx]);
829 			idx++;
830 			if (idx > raw->curlen)
831 				goto fail_len;
832 			memcpy(repmsg->u.link_addr.ports[i].peer_guid, &raw->msg[idx], 16);
833 			idx += 16;
834 			if (idx > raw->curlen)
835 				goto fail_len;
836 			repmsg->u.link_addr.ports[i].num_sdp_streams = (raw->msg[idx] >> 4) & 0xf;
837 			repmsg->u.link_addr.ports[i].num_sdp_stream_sinks = (raw->msg[idx] & 0xf);
838 			idx++;
839 
840 		}
841 		if (idx > raw->curlen)
842 			goto fail_len;
843 	}
844 
845 	return true;
846 fail_len:
847 	DRM_DEBUG_KMS("link address reply parse length fail %d %d\n", idx, raw->curlen);
848 	return false;
849 }
850 
drm_dp_sideband_parse_remote_dpcd_read(struct drm_dp_sideband_msg_rx * raw,struct drm_dp_sideband_msg_reply_body * repmsg)851 static bool drm_dp_sideband_parse_remote_dpcd_read(struct drm_dp_sideband_msg_rx *raw,
852 						   struct drm_dp_sideband_msg_reply_body *repmsg)
853 {
854 	int idx = 1;
855 
856 	repmsg->u.remote_dpcd_read_ack.port_number = raw->msg[idx] & 0xf;
857 	idx++;
858 	if (idx > raw->curlen)
859 		goto fail_len;
860 	repmsg->u.remote_dpcd_read_ack.num_bytes = raw->msg[idx];
861 	idx++;
862 	if (idx > raw->curlen)
863 		goto fail_len;
864 
865 	memcpy(repmsg->u.remote_dpcd_read_ack.bytes, &raw->msg[idx], repmsg->u.remote_dpcd_read_ack.num_bytes);
866 	return true;
867 fail_len:
868 	DRM_DEBUG_KMS("link address reply parse length fail %d %d\n", idx, raw->curlen);
869 	return false;
870 }
871 
drm_dp_sideband_parse_remote_dpcd_write(struct drm_dp_sideband_msg_rx * raw,struct drm_dp_sideband_msg_reply_body * repmsg)872 static bool drm_dp_sideband_parse_remote_dpcd_write(struct drm_dp_sideband_msg_rx *raw,
873 						      struct drm_dp_sideband_msg_reply_body *repmsg)
874 {
875 	int idx = 1;
876 
877 	repmsg->u.remote_dpcd_write_ack.port_number = raw->msg[idx] & 0xf;
878 	idx++;
879 	if (idx > raw->curlen)
880 		goto fail_len;
881 	return true;
882 fail_len:
883 	DRM_DEBUG_KMS("parse length fail %d %d\n", idx, raw->curlen);
884 	return false;
885 }
886 
drm_dp_sideband_parse_remote_i2c_read_ack(struct drm_dp_sideband_msg_rx * raw,struct drm_dp_sideband_msg_reply_body * repmsg)887 static bool drm_dp_sideband_parse_remote_i2c_read_ack(struct drm_dp_sideband_msg_rx *raw,
888 						      struct drm_dp_sideband_msg_reply_body *repmsg)
889 {
890 	int idx = 1;
891 
892 	repmsg->u.remote_i2c_read_ack.port_number = (raw->msg[idx] & 0xf);
893 	idx++;
894 	if (idx > raw->curlen)
895 		goto fail_len;
896 	repmsg->u.remote_i2c_read_ack.num_bytes = raw->msg[idx];
897 	idx++;
898 	/* TODO check */
899 	memcpy(repmsg->u.remote_i2c_read_ack.bytes, &raw->msg[idx], repmsg->u.remote_i2c_read_ack.num_bytes);
900 	return true;
901 fail_len:
902 	DRM_DEBUG_KMS("remote i2c reply parse length fail %d %d\n", idx, raw->curlen);
903 	return false;
904 }
905 
drm_dp_sideband_parse_enum_path_resources_ack(struct drm_dp_sideband_msg_rx * raw,struct drm_dp_sideband_msg_reply_body * repmsg)906 static bool drm_dp_sideband_parse_enum_path_resources_ack(struct drm_dp_sideband_msg_rx *raw,
907 							  struct drm_dp_sideband_msg_reply_body *repmsg)
908 {
909 	int idx = 1;
910 
911 	repmsg->u.path_resources.port_number = (raw->msg[idx] >> 4) & 0xf;
912 	repmsg->u.path_resources.fec_capable = raw->msg[idx] & 0x1;
913 	idx++;
914 	if (idx > raw->curlen)
915 		goto fail_len;
916 	repmsg->u.path_resources.full_payload_bw_number = (raw->msg[idx] << 8) | (raw->msg[idx+1]);
917 	idx += 2;
918 	if (idx > raw->curlen)
919 		goto fail_len;
920 	repmsg->u.path_resources.avail_payload_bw_number = (raw->msg[idx] << 8) | (raw->msg[idx+1]);
921 	idx += 2;
922 	if (idx > raw->curlen)
923 		goto fail_len;
924 	return true;
925 fail_len:
926 	DRM_DEBUG_KMS("enum resource parse length fail %d %d\n", idx, raw->curlen);
927 	return false;
928 }
929 
drm_dp_sideband_parse_allocate_payload_ack(struct drm_dp_sideband_msg_rx * raw,struct drm_dp_sideband_msg_reply_body * repmsg)930 static bool drm_dp_sideband_parse_allocate_payload_ack(struct drm_dp_sideband_msg_rx *raw,
931 							  struct drm_dp_sideband_msg_reply_body *repmsg)
932 {
933 	int idx = 1;
934 
935 	repmsg->u.allocate_payload.port_number = (raw->msg[idx] >> 4) & 0xf;
936 	idx++;
937 	if (idx > raw->curlen)
938 		goto fail_len;
939 	repmsg->u.allocate_payload.vcpi = raw->msg[idx];
940 	idx++;
941 	if (idx > raw->curlen)
942 		goto fail_len;
943 	repmsg->u.allocate_payload.allocated_pbn = (raw->msg[idx] << 8) | (raw->msg[idx+1]);
944 	idx += 2;
945 	if (idx > raw->curlen)
946 		goto fail_len;
947 	return true;
948 fail_len:
949 	DRM_DEBUG_KMS("allocate payload parse length fail %d %d\n", idx, raw->curlen);
950 	return false;
951 }
952 
drm_dp_sideband_parse_query_payload_ack(struct drm_dp_sideband_msg_rx * raw,struct drm_dp_sideband_msg_reply_body * repmsg)953 static bool drm_dp_sideband_parse_query_payload_ack(struct drm_dp_sideband_msg_rx *raw,
954 						    struct drm_dp_sideband_msg_reply_body *repmsg)
955 {
956 	int idx = 1;
957 
958 	repmsg->u.query_payload.port_number = (raw->msg[idx] >> 4) & 0xf;
959 	idx++;
960 	if (idx > raw->curlen)
961 		goto fail_len;
962 	repmsg->u.query_payload.allocated_pbn = (raw->msg[idx] << 8) | (raw->msg[idx + 1]);
963 	idx += 2;
964 	if (idx > raw->curlen)
965 		goto fail_len;
966 	return true;
967 fail_len:
968 	DRM_DEBUG_KMS("query payload parse length fail %d %d\n", idx, raw->curlen);
969 	return false;
970 }
971 
drm_dp_sideband_parse_power_updown_phy_ack(struct drm_dp_sideband_msg_rx * raw,struct drm_dp_sideband_msg_reply_body * repmsg)972 static bool drm_dp_sideband_parse_power_updown_phy_ack(struct drm_dp_sideband_msg_rx *raw,
973 						       struct drm_dp_sideband_msg_reply_body *repmsg)
974 {
975 	int idx = 1;
976 
977 	repmsg->u.port_number.port_number = (raw->msg[idx] >> 4) & 0xf;
978 	idx++;
979 	if (idx > raw->curlen) {
980 		DRM_DEBUG_KMS("power up/down phy parse length fail %d %d\n",
981 			      idx, raw->curlen);
982 		return false;
983 	}
984 	return true;
985 }
986 
987 static bool
drm_dp_sideband_parse_query_stream_enc_status(struct drm_dp_sideband_msg_rx * raw,struct drm_dp_sideband_msg_reply_body * repmsg)988 drm_dp_sideband_parse_query_stream_enc_status(
989 				struct drm_dp_sideband_msg_rx *raw,
990 				struct drm_dp_sideband_msg_reply_body *repmsg)
991 {
992 	struct drm_dp_query_stream_enc_status_ack_reply *reply;
993 
994 	reply = &repmsg->u.enc_status;
995 
996 	reply->stream_id = raw->msg[3];
997 
998 	reply->reply_signed = raw->msg[2] & BIT(0);
999 
1000 	/*
1001 	 * NOTE: It's my impression from reading the spec that the below parsing
1002 	 * is correct. However I noticed while testing with an HDCP 1.4 display
1003 	 * through an HDCP 2.2 hub that only bit 3 was set. In that case, I
1004 	 * would expect both bits to be set. So keep the parsing following the
1005 	 * spec, but beware reality might not match the spec (at least for some
1006 	 * configurations).
1007 	 */
1008 	reply->hdcp_1x_device_present = raw->msg[2] & BIT(4);
1009 	reply->hdcp_2x_device_present = raw->msg[2] & BIT(3);
1010 
1011 	reply->query_capable_device_present = raw->msg[2] & BIT(5);
1012 	reply->legacy_device_present = raw->msg[2] & BIT(6);
1013 	reply->unauthorizable_device_present = raw->msg[2] & BIT(7);
1014 
1015 	reply->auth_completed = !!(raw->msg[1] & BIT(3));
1016 	reply->encryption_enabled = !!(raw->msg[1] & BIT(4));
1017 	reply->repeater_present = !!(raw->msg[1] & BIT(5));
1018 	reply->state = (raw->msg[1] & GENMASK(7, 6)) >> 6;
1019 
1020 	return true;
1021 }
1022 
drm_dp_sideband_parse_reply(struct drm_dp_sideband_msg_rx * raw,struct drm_dp_sideband_msg_reply_body * msg)1023 static bool drm_dp_sideband_parse_reply(struct drm_dp_sideband_msg_rx *raw,
1024 					struct drm_dp_sideband_msg_reply_body *msg)
1025 {
1026 	memset(msg, 0, sizeof(*msg));
1027 	msg->reply_type = (raw->msg[0] & 0x80) >> 7;
1028 	msg->req_type = (raw->msg[0] & 0x7f);
1029 
1030 	if (msg->reply_type == DP_SIDEBAND_REPLY_NAK) {
1031 		memcpy(msg->u.nak.guid, &raw->msg[1], 16);
1032 		msg->u.nak.reason = raw->msg[17];
1033 		msg->u.nak.nak_data = raw->msg[18];
1034 		return false;
1035 	}
1036 
1037 	switch (msg->req_type) {
1038 	case DP_LINK_ADDRESS:
1039 		return drm_dp_sideband_parse_link_address(raw, msg);
1040 	case DP_QUERY_PAYLOAD:
1041 		return drm_dp_sideband_parse_query_payload_ack(raw, msg);
1042 	case DP_REMOTE_DPCD_READ:
1043 		return drm_dp_sideband_parse_remote_dpcd_read(raw, msg);
1044 	case DP_REMOTE_DPCD_WRITE:
1045 		return drm_dp_sideband_parse_remote_dpcd_write(raw, msg);
1046 	case DP_REMOTE_I2C_READ:
1047 		return drm_dp_sideband_parse_remote_i2c_read_ack(raw, msg);
1048 	case DP_REMOTE_I2C_WRITE:
1049 		return true; /* since there's nothing to parse */
1050 	case DP_ENUM_PATH_RESOURCES:
1051 		return drm_dp_sideband_parse_enum_path_resources_ack(raw, msg);
1052 	case DP_ALLOCATE_PAYLOAD:
1053 		return drm_dp_sideband_parse_allocate_payload_ack(raw, msg);
1054 	case DP_POWER_DOWN_PHY:
1055 	case DP_POWER_UP_PHY:
1056 		return drm_dp_sideband_parse_power_updown_phy_ack(raw, msg);
1057 	case DP_CLEAR_PAYLOAD_ID_TABLE:
1058 		return true; /* since there's nothing to parse */
1059 	case DP_QUERY_STREAM_ENC_STATUS:
1060 		return drm_dp_sideband_parse_query_stream_enc_status(raw, msg);
1061 	default:
1062 		DRM_ERROR("Got unknown reply 0x%02x (%s)\n", msg->req_type,
1063 			  drm_dp_mst_req_type_str(msg->req_type));
1064 		return false;
1065 	}
1066 }
1067 
drm_dp_sideband_parse_connection_status_notify(struct drm_dp_sideband_msg_rx * raw,struct drm_dp_sideband_msg_req_body * msg)1068 static bool drm_dp_sideband_parse_connection_status_notify(struct drm_dp_sideband_msg_rx *raw,
1069 							   struct drm_dp_sideband_msg_req_body *msg)
1070 {
1071 	int idx = 1;
1072 
1073 	msg->u.conn_stat.port_number = (raw->msg[idx] & 0xf0) >> 4;
1074 	idx++;
1075 	if (idx > raw->curlen)
1076 		goto fail_len;
1077 
1078 	memcpy(msg->u.conn_stat.guid, &raw->msg[idx], 16);
1079 	idx += 16;
1080 	if (idx > raw->curlen)
1081 		goto fail_len;
1082 
1083 	msg->u.conn_stat.legacy_device_plug_status = (raw->msg[idx] >> 6) & 0x1;
1084 	msg->u.conn_stat.displayport_device_plug_status = (raw->msg[idx] >> 5) & 0x1;
1085 	msg->u.conn_stat.message_capability_status = (raw->msg[idx] >> 4) & 0x1;
1086 	msg->u.conn_stat.input_port = (raw->msg[idx] >> 3) & 0x1;
1087 	msg->u.conn_stat.peer_device_type = (raw->msg[idx] & 0x7);
1088 	idx++;
1089 	return true;
1090 fail_len:
1091 	DRM_DEBUG_KMS("connection status reply parse length fail %d %d\n", idx, raw->curlen);
1092 	return false;
1093 }
1094 
drm_dp_sideband_parse_resource_status_notify(struct drm_dp_sideband_msg_rx * raw,struct drm_dp_sideband_msg_req_body * msg)1095 static bool drm_dp_sideband_parse_resource_status_notify(struct drm_dp_sideband_msg_rx *raw,
1096 							   struct drm_dp_sideband_msg_req_body *msg)
1097 {
1098 	int idx = 1;
1099 
1100 	msg->u.resource_stat.port_number = (raw->msg[idx] & 0xf0) >> 4;
1101 	idx++;
1102 	if (idx > raw->curlen)
1103 		goto fail_len;
1104 
1105 	memcpy(msg->u.resource_stat.guid, &raw->msg[idx], 16);
1106 	idx += 16;
1107 	if (idx > raw->curlen)
1108 		goto fail_len;
1109 
1110 	msg->u.resource_stat.available_pbn = (raw->msg[idx] << 8) | (raw->msg[idx + 1]);
1111 	idx++;
1112 	return true;
1113 fail_len:
1114 	DRM_DEBUG_KMS("resource status reply parse length fail %d %d\n", idx, raw->curlen);
1115 	return false;
1116 }
1117 
drm_dp_sideband_parse_req(struct drm_dp_sideband_msg_rx * raw,struct drm_dp_sideband_msg_req_body * msg)1118 static bool drm_dp_sideband_parse_req(struct drm_dp_sideband_msg_rx *raw,
1119 				      struct drm_dp_sideband_msg_req_body *msg)
1120 {
1121 	memset(msg, 0, sizeof(*msg));
1122 	msg->req_type = (raw->msg[0] & 0x7f);
1123 
1124 	switch (msg->req_type) {
1125 	case DP_CONNECTION_STATUS_NOTIFY:
1126 		return drm_dp_sideband_parse_connection_status_notify(raw, msg);
1127 	case DP_RESOURCE_STATUS_NOTIFY:
1128 		return drm_dp_sideband_parse_resource_status_notify(raw, msg);
1129 	default:
1130 		DRM_ERROR("Got unknown request 0x%02x (%s)\n", msg->req_type,
1131 			  drm_dp_mst_req_type_str(msg->req_type));
1132 		return false;
1133 	}
1134 }
1135 
build_dpcd_write(struct drm_dp_sideband_msg_tx * msg,u8 port_num,u32 offset,u8 num_bytes,u8 * bytes)1136 static void build_dpcd_write(struct drm_dp_sideband_msg_tx *msg,
1137 			     u8 port_num, u32 offset, u8 num_bytes, u8 *bytes)
1138 {
1139 	struct drm_dp_sideband_msg_req_body req;
1140 
1141 	req.req_type = DP_REMOTE_DPCD_WRITE;
1142 	req.u.dpcd_write.port_number = port_num;
1143 	req.u.dpcd_write.dpcd_address = offset;
1144 	req.u.dpcd_write.num_bytes = num_bytes;
1145 	req.u.dpcd_write.bytes = bytes;
1146 	drm_dp_encode_sideband_req(&req, msg);
1147 }
1148 
build_link_address(struct drm_dp_sideband_msg_tx * msg)1149 static void build_link_address(struct drm_dp_sideband_msg_tx *msg)
1150 {
1151 	struct drm_dp_sideband_msg_req_body req;
1152 
1153 	req.req_type = DP_LINK_ADDRESS;
1154 	drm_dp_encode_sideband_req(&req, msg);
1155 }
1156 
build_clear_payload_id_table(struct drm_dp_sideband_msg_tx * msg)1157 static void build_clear_payload_id_table(struct drm_dp_sideband_msg_tx *msg)
1158 {
1159 	struct drm_dp_sideband_msg_req_body req;
1160 
1161 	req.req_type = DP_CLEAR_PAYLOAD_ID_TABLE;
1162 	drm_dp_encode_sideband_req(&req, msg);
1163 	msg->path_msg = true;
1164 }
1165 
build_enum_path_resources(struct drm_dp_sideband_msg_tx * msg,int port_num)1166 static int build_enum_path_resources(struct drm_dp_sideband_msg_tx *msg,
1167 				     int port_num)
1168 {
1169 	struct drm_dp_sideband_msg_req_body req;
1170 
1171 	req.req_type = DP_ENUM_PATH_RESOURCES;
1172 	req.u.port_num.port_number = port_num;
1173 	drm_dp_encode_sideband_req(&req, msg);
1174 	msg->path_msg = true;
1175 	return 0;
1176 }
1177 
build_allocate_payload(struct drm_dp_sideband_msg_tx * msg,int port_num,u8 vcpi,uint16_t pbn,u8 number_sdp_streams,u8 * sdp_stream_sink)1178 static void build_allocate_payload(struct drm_dp_sideband_msg_tx *msg,
1179 				   int port_num,
1180 				   u8 vcpi, uint16_t pbn,
1181 				   u8 number_sdp_streams,
1182 				   u8 *sdp_stream_sink)
1183 {
1184 	struct drm_dp_sideband_msg_req_body req;
1185 
1186 	memset(&req, 0, sizeof(req));
1187 	req.req_type = DP_ALLOCATE_PAYLOAD;
1188 	req.u.allocate_payload.port_number = port_num;
1189 	req.u.allocate_payload.vcpi = vcpi;
1190 	req.u.allocate_payload.pbn = pbn;
1191 	req.u.allocate_payload.number_sdp_streams = number_sdp_streams;
1192 	memcpy(req.u.allocate_payload.sdp_stream_sink, sdp_stream_sink,
1193 		   number_sdp_streams);
1194 	drm_dp_encode_sideband_req(&req, msg);
1195 	msg->path_msg = true;
1196 }
1197 
build_power_updown_phy(struct drm_dp_sideband_msg_tx * msg,int port_num,bool power_up)1198 static void build_power_updown_phy(struct drm_dp_sideband_msg_tx *msg,
1199 				   int port_num, bool power_up)
1200 {
1201 	struct drm_dp_sideband_msg_req_body req;
1202 
1203 	if (power_up)
1204 		req.req_type = DP_POWER_UP_PHY;
1205 	else
1206 		req.req_type = DP_POWER_DOWN_PHY;
1207 
1208 	req.u.port_num.port_number = port_num;
1209 	drm_dp_encode_sideband_req(&req, msg);
1210 	msg->path_msg = true;
1211 }
1212 
1213 static int
build_query_stream_enc_status(struct drm_dp_sideband_msg_tx * msg,u8 stream_id,u8 * q_id)1214 build_query_stream_enc_status(struct drm_dp_sideband_msg_tx *msg, u8 stream_id,
1215 			      u8 *q_id)
1216 {
1217 	struct drm_dp_sideband_msg_req_body req;
1218 
1219 	req.req_type = DP_QUERY_STREAM_ENC_STATUS;
1220 	req.u.enc_status.stream_id = stream_id;
1221 	memcpy(req.u.enc_status.client_id, q_id,
1222 	       sizeof(req.u.enc_status.client_id));
1223 	req.u.enc_status.stream_event = 0;
1224 	req.u.enc_status.valid_stream_event = false;
1225 	req.u.enc_status.stream_behavior = 0;
1226 	req.u.enc_status.valid_stream_behavior = false;
1227 
1228 	drm_dp_encode_sideband_req(&req, msg);
1229 	return 0;
1230 }
1231 
drm_dp_mst_assign_payload_id(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_vcpi * vcpi)1232 static int drm_dp_mst_assign_payload_id(struct drm_dp_mst_topology_mgr *mgr,
1233 					struct drm_dp_vcpi *vcpi)
1234 {
1235 	int ret, vcpi_ret;
1236 
1237 	mutex_lock(&mgr->payload_lock);
1238 	ret = find_first_zero_bit(&mgr->payload_mask, mgr->max_payloads + 1);
1239 	if (ret > mgr->max_payloads) {
1240 		ret = -EINVAL;
1241 		DRM_DEBUG_KMS("out of payload ids %d\n", ret);
1242 		goto out_unlock;
1243 	}
1244 
1245 	vcpi_ret = find_first_zero_bit(&mgr->vcpi_mask, mgr->max_payloads + 1);
1246 	if (vcpi_ret > mgr->max_payloads) {
1247 		ret = -EINVAL;
1248 		DRM_DEBUG_KMS("out of vcpi ids %d\n", ret);
1249 		goto out_unlock;
1250 	}
1251 
1252 	set_bit(ret, &mgr->payload_mask);
1253 	set_bit(vcpi_ret, &mgr->vcpi_mask);
1254 	vcpi->vcpi = vcpi_ret + 1;
1255 	mgr->proposed_vcpis[ret - 1] = vcpi;
1256 out_unlock:
1257 	mutex_unlock(&mgr->payload_lock);
1258 	return ret;
1259 }
1260 
drm_dp_mst_put_payload_id(struct drm_dp_mst_topology_mgr * mgr,int vcpi)1261 static void drm_dp_mst_put_payload_id(struct drm_dp_mst_topology_mgr *mgr,
1262 				      int vcpi)
1263 {
1264 	int i;
1265 
1266 	if (vcpi == 0)
1267 		return;
1268 
1269 	mutex_lock(&mgr->payload_lock);
1270 	DRM_DEBUG_KMS("putting payload %d\n", vcpi);
1271 	clear_bit(vcpi - 1, &mgr->vcpi_mask);
1272 
1273 	for (i = 0; i < mgr->max_payloads; i++) {
1274 		if (mgr->proposed_vcpis[i] &&
1275 		    mgr->proposed_vcpis[i]->vcpi == vcpi) {
1276 			mgr->proposed_vcpis[i] = NULL;
1277 			clear_bit(i + 1, &mgr->payload_mask);
1278 		}
1279 	}
1280 	mutex_unlock(&mgr->payload_lock);
1281 }
1282 
check_txmsg_state(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_sideband_msg_tx * txmsg)1283 static bool check_txmsg_state(struct drm_dp_mst_topology_mgr *mgr,
1284 			      struct drm_dp_sideband_msg_tx *txmsg)
1285 {
1286 	unsigned int state;
1287 
1288 	/*
1289 	 * All updates to txmsg->state are protected by mgr->qlock, and the two
1290 	 * cases we check here are terminal states. For those the barriers
1291 	 * provided by the wake_up/wait_event pair are enough.
1292 	 */
1293 	state = READ_ONCE(txmsg->state);
1294 	return (state == DRM_DP_SIDEBAND_TX_RX ||
1295 		state == DRM_DP_SIDEBAND_TX_TIMEOUT);
1296 }
1297 
drm_dp_mst_wait_tx_reply(struct drm_dp_mst_branch * mstb,struct drm_dp_sideband_msg_tx * txmsg)1298 static int drm_dp_mst_wait_tx_reply(struct drm_dp_mst_branch *mstb,
1299 				    struct drm_dp_sideband_msg_tx *txmsg)
1300 {
1301 	struct drm_dp_mst_topology_mgr *mgr = mstb->mgr;
1302 	unsigned long wait_timeout = msecs_to_jiffies(4000);
1303 	unsigned long wait_expires = jiffies + wait_timeout;
1304 	int ret;
1305 
1306 	for (;;) {
1307 		/*
1308 		 * If the driver provides a way for this, change to
1309 		 * poll-waiting for the MST reply interrupt if we didn't receive
1310 		 * it for 50 msec. This would cater for cases where the HPD
1311 		 * pulse signal got lost somewhere, even though the sink raised
1312 		 * the corresponding MST interrupt correctly. One example is the
1313 		 * Club 3D CAC-1557 TypeC -> DP adapter which for some reason
1314 		 * filters out short pulses with a duration less than ~540 usec.
1315 		 *
1316 		 * The poll period is 50 msec to avoid missing an interrupt
1317 		 * after the sink has cleared it (after a 110msec timeout
1318 		 * since it raised the interrupt).
1319 		 */
1320 		ret = wait_event_timeout(mgr->tx_waitq,
1321 					 check_txmsg_state(mgr, txmsg),
1322 					 mgr->cbs->poll_hpd_irq ?
1323 						msecs_to_jiffies(50) :
1324 						wait_timeout);
1325 
1326 		if (ret || !mgr->cbs->poll_hpd_irq ||
1327 		    time_after(jiffies, wait_expires))
1328 			break;
1329 
1330 		mgr->cbs->poll_hpd_irq(mgr);
1331 	}
1332 
1333 	mutex_lock(&mgr->qlock);
1334 	if (ret > 0) {
1335 		if (txmsg->state == DRM_DP_SIDEBAND_TX_TIMEOUT) {
1336 			ret = -EIO;
1337 			goto out;
1338 		}
1339 	} else {
1340 		DRM_DEBUG_KMS("timedout msg send %p %d %d\n", txmsg, txmsg->state, txmsg->seqno);
1341 
1342 		/* dump some state */
1343 		ret = -EIO;
1344 
1345 		/* remove from q */
1346 		if (txmsg->state == DRM_DP_SIDEBAND_TX_QUEUED ||
1347 		    txmsg->state == DRM_DP_SIDEBAND_TX_START_SEND ||
1348 		    txmsg->state == DRM_DP_SIDEBAND_TX_SENT)
1349 			list_del(&txmsg->next);
1350 	}
1351 out:
1352 	if (unlikely(ret == -EIO) && drm_debug_enabled(DRM_UT_DP)) {
1353 		struct drm_printer p = drm_debug_printer(DBG_PREFIX);
1354 
1355 		drm_dp_mst_dump_sideband_msg_tx(&p, txmsg);
1356 	}
1357 	mutex_unlock(&mgr->qlock);
1358 
1359 	drm_dp_mst_kick_tx(mgr);
1360 	return ret;
1361 }
1362 
drm_dp_add_mst_branch_device(u8 lct,u8 * rad)1363 static struct drm_dp_mst_branch *drm_dp_add_mst_branch_device(u8 lct, u8 *rad)
1364 {
1365 	struct drm_dp_mst_branch *mstb;
1366 
1367 	mstb = kzalloc(sizeof(*mstb), GFP_KERNEL);
1368 	if (!mstb)
1369 		return NULL;
1370 
1371 	mstb->lct = lct;
1372 	if (lct > 1)
1373 		memcpy(mstb->rad, rad, lct / 2);
1374 	INIT_LIST_HEAD(&mstb->ports);
1375 	kref_init(&mstb->topology_kref);
1376 	kref_init(&mstb->malloc_kref);
1377 	return mstb;
1378 }
1379 
drm_dp_free_mst_branch_device(struct kref * kref)1380 static void drm_dp_free_mst_branch_device(struct kref *kref)
1381 {
1382 	struct drm_dp_mst_branch *mstb =
1383 		container_of(kref, struct drm_dp_mst_branch, malloc_kref);
1384 
1385 	if (mstb->port_parent)
1386 		drm_dp_mst_put_port_malloc(mstb->port_parent);
1387 
1388 	kfree(mstb);
1389 }
1390 
1391 /**
1392  * DOC: Branch device and port refcounting
1393  *
1394  * Topology refcount overview
1395  * ~~~~~~~~~~~~~~~~~~~~~~~~~~
1396  *
1397  * The refcounting schemes for &struct drm_dp_mst_branch and &struct
1398  * drm_dp_mst_port are somewhat unusual. Both ports and branch devices have
1399  * two different kinds of refcounts: topology refcounts, and malloc refcounts.
1400  *
1401  * Topology refcounts are not exposed to drivers, and are handled internally
1402  * by the DP MST helpers. The helpers use them in order to prevent the
1403  * in-memory topology state from being changed in the middle of critical
1404  * operations like changing the internal state of payload allocations. This
1405  * means each branch and port will be considered to be connected to the rest
1406  * of the topology until its topology refcount reaches zero. Additionally,
1407  * for ports this means that their associated &struct drm_connector will stay
1408  * registered with userspace until the port's refcount reaches 0.
1409  *
1410  * Malloc refcount overview
1411  * ~~~~~~~~~~~~~~~~~~~~~~~~
1412  *
1413  * Malloc references are used to keep a &struct drm_dp_mst_port or &struct
1414  * drm_dp_mst_branch allocated even after all of its topology references have
1415  * been dropped, so that the driver or MST helpers can safely access each
1416  * branch's last known state before it was disconnected from the topology.
1417  * When the malloc refcount of a port or branch reaches 0, the memory
1418  * allocation containing the &struct drm_dp_mst_branch or &struct
1419  * drm_dp_mst_port respectively will be freed.
1420  *
1421  * For &struct drm_dp_mst_branch, malloc refcounts are not currently exposed
1422  * to drivers. As of writing this documentation, there are no drivers that
1423  * have a usecase for accessing &struct drm_dp_mst_branch outside of the MST
1424  * helpers. Exposing this API to drivers in a race-free manner would take more
1425  * tweaking of the refcounting scheme, however patches are welcome provided
1426  * there is a legitimate driver usecase for this.
1427  *
1428  * Refcount relationships in a topology
1429  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1430  *
1431  * Let's take a look at why the relationship between topology and malloc
1432  * refcounts is designed the way it is.
1433  *
1434  * .. kernel-figure:: dp-mst/topology-figure-1.dot
1435  *
1436  *    An example of topology and malloc refs in a DP MST topology with two
1437  *    active payloads. Topology refcount increments are indicated by solid
1438  *    lines, and malloc refcount increments are indicated by dashed lines.
1439  *    Each starts from the branch which incremented the refcount, and ends at
1440  *    the branch to which the refcount belongs to, i.e. the arrow points the
1441  *    same way as the C pointers used to reference a structure.
1442  *
1443  * As you can see in the above figure, every branch increments the topology
1444  * refcount of its children, and increments the malloc refcount of its
1445  * parent. Additionally, every payload increments the malloc refcount of its
1446  * assigned port by 1.
1447  *
1448  * So, what would happen if MSTB #3 from the above figure was unplugged from
1449  * the system, but the driver hadn't yet removed payload #2 from port #3? The
1450  * topology would start to look like the figure below.
1451  *
1452  * .. kernel-figure:: dp-mst/topology-figure-2.dot
1453  *
1454  *    Ports and branch devices which have been released from memory are
1455  *    colored grey, and references which have been removed are colored red.
1456  *
1457  * Whenever a port or branch device's topology refcount reaches zero, it will
1458  * decrement the topology refcounts of all its children, the malloc refcount
1459  * of its parent, and finally its own malloc refcount. For MSTB #4 and port
1460  * #4, this means they both have been disconnected from the topology and freed
1461  * from memory. But, because payload #2 is still holding a reference to port
1462  * #3, port #3 is removed from the topology but its &struct drm_dp_mst_port
1463  * is still accessible from memory. This also means port #3 has not yet
1464  * decremented the malloc refcount of MSTB #3, so its &struct
1465  * drm_dp_mst_branch will also stay allocated in memory until port #3's
1466  * malloc refcount reaches 0.
1467  *
1468  * This relationship is necessary because in order to release payload #2, we
1469  * need to be able to figure out the last relative of port #3 that's still
1470  * connected to the topology. In this case, we would travel up the topology as
1471  * shown below.
1472  *
1473  * .. kernel-figure:: dp-mst/topology-figure-3.dot
1474  *
1475  * And finally, remove payload #2 by communicating with port #2 through
1476  * sideband transactions.
1477  */
1478 
1479 /**
1480  * drm_dp_mst_get_mstb_malloc() - Increment the malloc refcount of a branch
1481  * device
1482  * @mstb: The &struct drm_dp_mst_branch to increment the malloc refcount of
1483  *
1484  * Increments &drm_dp_mst_branch.malloc_kref. When
1485  * &drm_dp_mst_branch.malloc_kref reaches 0, the memory allocation for @mstb
1486  * will be released and @mstb may no longer be used.
1487  *
1488  * See also: drm_dp_mst_put_mstb_malloc()
1489  */
1490 static void
drm_dp_mst_get_mstb_malloc(struct drm_dp_mst_branch * mstb)1491 drm_dp_mst_get_mstb_malloc(struct drm_dp_mst_branch *mstb)
1492 {
1493 	kref_get(&mstb->malloc_kref);
1494 	DRM_DEBUG("mstb %p (%d)\n", mstb, kref_read(&mstb->malloc_kref));
1495 }
1496 
1497 /**
1498  * drm_dp_mst_put_mstb_malloc() - Decrement the malloc refcount of a branch
1499  * device
1500  * @mstb: The &struct drm_dp_mst_branch to decrement the malloc refcount of
1501  *
1502  * Decrements &drm_dp_mst_branch.malloc_kref. When
1503  * &drm_dp_mst_branch.malloc_kref reaches 0, the memory allocation for @mstb
1504  * will be released and @mstb may no longer be used.
1505  *
1506  * See also: drm_dp_mst_get_mstb_malloc()
1507  */
1508 static void
drm_dp_mst_put_mstb_malloc(struct drm_dp_mst_branch * mstb)1509 drm_dp_mst_put_mstb_malloc(struct drm_dp_mst_branch *mstb)
1510 {
1511 	DRM_DEBUG("mstb %p (%d)\n", mstb, kref_read(&mstb->malloc_kref) - 1);
1512 	kref_put(&mstb->malloc_kref, drm_dp_free_mst_branch_device);
1513 }
1514 
drm_dp_free_mst_port(struct kref * kref)1515 static void drm_dp_free_mst_port(struct kref *kref)
1516 {
1517 	struct drm_dp_mst_port *port =
1518 		container_of(kref, struct drm_dp_mst_port, malloc_kref);
1519 
1520 	drm_dp_mst_put_mstb_malloc(port->parent);
1521 	kfree(port);
1522 }
1523 
1524 /**
1525  * drm_dp_mst_get_port_malloc() - Increment the malloc refcount of an MST port
1526  * @port: The &struct drm_dp_mst_port to increment the malloc refcount of
1527  *
1528  * Increments &drm_dp_mst_port.malloc_kref. When &drm_dp_mst_port.malloc_kref
1529  * reaches 0, the memory allocation for @port will be released and @port may
1530  * no longer be used.
1531  *
1532  * Because @port could potentially be freed at any time by the DP MST helpers
1533  * if &drm_dp_mst_port.malloc_kref reaches 0, including during a call to this
1534  * function, drivers that which to make use of &struct drm_dp_mst_port should
1535  * ensure that they grab at least one main malloc reference to their MST ports
1536  * in &drm_dp_mst_topology_cbs.add_connector. This callback is called before
1537  * there is any chance for &drm_dp_mst_port.malloc_kref to reach 0.
1538  *
1539  * See also: drm_dp_mst_put_port_malloc()
1540  */
1541 void
drm_dp_mst_get_port_malloc(struct drm_dp_mst_port * port)1542 drm_dp_mst_get_port_malloc(struct drm_dp_mst_port *port)
1543 {
1544 	kref_get(&port->malloc_kref);
1545 	DRM_DEBUG("port %p (%d)\n", port, kref_read(&port->malloc_kref));
1546 }
1547 EXPORT_SYMBOL(drm_dp_mst_get_port_malloc);
1548 
1549 /**
1550  * drm_dp_mst_put_port_malloc() - Decrement the malloc refcount of an MST port
1551  * @port: The &struct drm_dp_mst_port to decrement the malloc refcount of
1552  *
1553  * Decrements &drm_dp_mst_port.malloc_kref. When &drm_dp_mst_port.malloc_kref
1554  * reaches 0, the memory allocation for @port will be released and @port may
1555  * no longer be used.
1556  *
1557  * See also: drm_dp_mst_get_port_malloc()
1558  */
1559 void
drm_dp_mst_put_port_malloc(struct drm_dp_mst_port * port)1560 drm_dp_mst_put_port_malloc(struct drm_dp_mst_port *port)
1561 {
1562 	DRM_DEBUG("port %p (%d)\n", port, kref_read(&port->malloc_kref) - 1);
1563 	kref_put(&port->malloc_kref, drm_dp_free_mst_port);
1564 }
1565 EXPORT_SYMBOL(drm_dp_mst_put_port_malloc);
1566 
1567 #if IS_ENABLED(CONFIG_DRM_DEBUG_DP_MST_TOPOLOGY_REFS)
1568 
1569 #define STACK_DEPTH 8
1570 
1571 static noinline void
__topology_ref_save(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_topology_ref_history * history,enum drm_dp_mst_topology_ref_type type)1572 __topology_ref_save(struct drm_dp_mst_topology_mgr *mgr,
1573 		    struct drm_dp_mst_topology_ref_history *history,
1574 		    enum drm_dp_mst_topology_ref_type type)
1575 {
1576 	struct drm_dp_mst_topology_ref_entry *entry = NULL;
1577 	depot_stack_handle_t backtrace;
1578 	ulong stack_entries[STACK_DEPTH];
1579 	uint n;
1580 	int i;
1581 
1582 	n = stack_trace_save(stack_entries, ARRAY_SIZE(stack_entries), 1);
1583 	backtrace = stack_depot_save(stack_entries, n, GFP_KERNEL);
1584 	if (!backtrace)
1585 		return;
1586 
1587 	/* Try to find an existing entry for this backtrace */
1588 	for (i = 0; i < history->len; i++) {
1589 		if (history->entries[i].backtrace == backtrace) {
1590 			entry = &history->entries[i];
1591 			break;
1592 		}
1593 	}
1594 
1595 	/* Otherwise add one */
1596 	if (!entry) {
1597 		struct drm_dp_mst_topology_ref_entry *new;
1598 		int new_len = history->len + 1;
1599 
1600 		new = krealloc(history->entries, sizeof(*new) * new_len,
1601 			       GFP_KERNEL);
1602 		if (!new)
1603 			return;
1604 
1605 		entry = &new[history->len];
1606 		history->len = new_len;
1607 		history->entries = new;
1608 
1609 		entry->backtrace = backtrace;
1610 		entry->type = type;
1611 		entry->count = 0;
1612 	}
1613 	entry->count++;
1614 	entry->ts_nsec = ktime_get_ns();
1615 }
1616 
1617 static int
topology_ref_history_cmp(const void * a,const void * b)1618 topology_ref_history_cmp(const void *a, const void *b)
1619 {
1620 	const struct drm_dp_mst_topology_ref_entry *entry_a = a, *entry_b = b;
1621 
1622 	if (entry_a->ts_nsec > entry_b->ts_nsec)
1623 		return 1;
1624 	else if (entry_a->ts_nsec < entry_b->ts_nsec)
1625 		return -1;
1626 	else
1627 		return 0;
1628 }
1629 
1630 static inline const char *
topology_ref_type_to_str(enum drm_dp_mst_topology_ref_type type)1631 topology_ref_type_to_str(enum drm_dp_mst_topology_ref_type type)
1632 {
1633 	if (type == DRM_DP_MST_TOPOLOGY_REF_GET)
1634 		return "get";
1635 	else
1636 		return "put";
1637 }
1638 
1639 static void
__dump_topology_ref_history(struct drm_dp_mst_topology_ref_history * history,void * ptr,const char * type_str)1640 __dump_topology_ref_history(struct drm_dp_mst_topology_ref_history *history,
1641 			    void *ptr, const char *type_str)
1642 {
1643 	struct drm_printer p = drm_debug_printer(DBG_PREFIX);
1644 	char *buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
1645 	int i;
1646 
1647 	if (!buf)
1648 		return;
1649 
1650 	if (!history->len)
1651 		goto out;
1652 
1653 	/* First, sort the list so that it goes from oldest to newest
1654 	 * reference entry
1655 	 */
1656 	sort(history->entries, history->len, sizeof(*history->entries),
1657 	     topology_ref_history_cmp, NULL);
1658 
1659 	drm_printf(&p, "%s (%p) topology count reached 0, dumping history:\n",
1660 		   type_str, ptr);
1661 
1662 	for (i = 0; i < history->len; i++) {
1663 		const struct drm_dp_mst_topology_ref_entry *entry =
1664 			&history->entries[i];
1665 		ulong *entries;
1666 		uint nr_entries;
1667 		u64 ts_nsec = entry->ts_nsec;
1668 		u32 rem_nsec = do_div(ts_nsec, 1000000000);
1669 
1670 		nr_entries = stack_depot_fetch(entry->backtrace, &entries);
1671 		stack_trace_snprint(buf, PAGE_SIZE, entries, nr_entries, 4);
1672 
1673 		drm_printf(&p, "  %d %ss (last at %5llu.%06u):\n%s",
1674 			   entry->count,
1675 			   topology_ref_type_to_str(entry->type),
1676 			   ts_nsec, rem_nsec / 1000, buf);
1677 	}
1678 
1679 	/* Now free the history, since this is the only time we expose it */
1680 	kfree(history->entries);
1681 out:
1682 	kfree(buf);
1683 }
1684 
1685 static __always_inline void
drm_dp_mst_dump_mstb_topology_history(struct drm_dp_mst_branch * mstb)1686 drm_dp_mst_dump_mstb_topology_history(struct drm_dp_mst_branch *mstb)
1687 {
1688 	__dump_topology_ref_history(&mstb->topology_ref_history, mstb,
1689 				    "MSTB");
1690 }
1691 
1692 static __always_inline void
drm_dp_mst_dump_port_topology_history(struct drm_dp_mst_port * port)1693 drm_dp_mst_dump_port_topology_history(struct drm_dp_mst_port *port)
1694 {
1695 	__dump_topology_ref_history(&port->topology_ref_history, port,
1696 				    "Port");
1697 }
1698 
1699 static __always_inline void
save_mstb_topology_ref(struct drm_dp_mst_branch * mstb,enum drm_dp_mst_topology_ref_type type)1700 save_mstb_topology_ref(struct drm_dp_mst_branch *mstb,
1701 		       enum drm_dp_mst_topology_ref_type type)
1702 {
1703 	__topology_ref_save(mstb->mgr, &mstb->topology_ref_history, type);
1704 }
1705 
1706 static __always_inline void
save_port_topology_ref(struct drm_dp_mst_port * port,enum drm_dp_mst_topology_ref_type type)1707 save_port_topology_ref(struct drm_dp_mst_port *port,
1708 		       enum drm_dp_mst_topology_ref_type type)
1709 {
1710 	__topology_ref_save(port->mgr, &port->topology_ref_history, type);
1711 }
1712 
1713 static inline void
topology_ref_history_lock(struct drm_dp_mst_topology_mgr * mgr)1714 topology_ref_history_lock(struct drm_dp_mst_topology_mgr *mgr)
1715 {
1716 	mutex_lock(&mgr->topology_ref_history_lock);
1717 }
1718 
1719 static inline void
topology_ref_history_unlock(struct drm_dp_mst_topology_mgr * mgr)1720 topology_ref_history_unlock(struct drm_dp_mst_topology_mgr *mgr)
1721 {
1722 	mutex_unlock(&mgr->topology_ref_history_lock);
1723 }
1724 #else
1725 static inline void
topology_ref_history_lock(struct drm_dp_mst_topology_mgr * mgr)1726 topology_ref_history_lock(struct drm_dp_mst_topology_mgr *mgr) {}
1727 static inline void
topology_ref_history_unlock(struct drm_dp_mst_topology_mgr * mgr)1728 topology_ref_history_unlock(struct drm_dp_mst_topology_mgr *mgr) {}
1729 static inline void
drm_dp_mst_dump_mstb_topology_history(struct drm_dp_mst_branch * mstb)1730 drm_dp_mst_dump_mstb_topology_history(struct drm_dp_mst_branch *mstb) {}
1731 static inline void
drm_dp_mst_dump_port_topology_history(struct drm_dp_mst_port * port)1732 drm_dp_mst_dump_port_topology_history(struct drm_dp_mst_port *port) {}
1733 #define save_mstb_topology_ref(mstb, type)
1734 #define save_port_topology_ref(port, type)
1735 #endif
1736 
drm_dp_destroy_mst_branch_device(struct kref * kref)1737 static void drm_dp_destroy_mst_branch_device(struct kref *kref)
1738 {
1739 	struct drm_dp_mst_branch *mstb =
1740 		container_of(kref, struct drm_dp_mst_branch, topology_kref);
1741 	struct drm_dp_mst_topology_mgr *mgr = mstb->mgr;
1742 
1743 	drm_dp_mst_dump_mstb_topology_history(mstb);
1744 
1745 	INIT_LIST_HEAD(&mstb->destroy_next);
1746 
1747 	/*
1748 	 * This can get called under mgr->mutex, so we need to perform the
1749 	 * actual destruction of the mstb in another worker
1750 	 */
1751 	mutex_lock(&mgr->delayed_destroy_lock);
1752 	list_add(&mstb->destroy_next, &mgr->destroy_branch_device_list);
1753 	mutex_unlock(&mgr->delayed_destroy_lock);
1754 	queue_work(mgr->delayed_destroy_wq, &mgr->delayed_destroy_work);
1755 }
1756 
1757 /**
1758  * drm_dp_mst_topology_try_get_mstb() - Increment the topology refcount of a
1759  * branch device unless it's zero
1760  * @mstb: &struct drm_dp_mst_branch to increment the topology refcount of
1761  *
1762  * Attempts to grab a topology reference to @mstb, if it hasn't yet been
1763  * removed from the topology (e.g. &drm_dp_mst_branch.topology_kref has
1764  * reached 0). Holding a topology reference implies that a malloc reference
1765  * will be held to @mstb as long as the user holds the topology reference.
1766  *
1767  * Care should be taken to ensure that the user has at least one malloc
1768  * reference to @mstb. If you already have a topology reference to @mstb, you
1769  * should use drm_dp_mst_topology_get_mstb() instead.
1770  *
1771  * See also:
1772  * drm_dp_mst_topology_get_mstb()
1773  * drm_dp_mst_topology_put_mstb()
1774  *
1775  * Returns:
1776  * * 1: A topology reference was grabbed successfully
1777  * * 0: @port is no longer in the topology, no reference was grabbed
1778  */
1779 static int __must_check
drm_dp_mst_topology_try_get_mstb(struct drm_dp_mst_branch * mstb)1780 drm_dp_mst_topology_try_get_mstb(struct drm_dp_mst_branch *mstb)
1781 {
1782 	int ret;
1783 
1784 	topology_ref_history_lock(mstb->mgr);
1785 	ret = kref_get_unless_zero(&mstb->topology_kref);
1786 	if (ret) {
1787 		DRM_DEBUG("mstb %p (%d)\n",
1788 			  mstb, kref_read(&mstb->topology_kref));
1789 		save_mstb_topology_ref(mstb, DRM_DP_MST_TOPOLOGY_REF_GET);
1790 	}
1791 
1792 	topology_ref_history_unlock(mstb->mgr);
1793 
1794 	return ret;
1795 }
1796 
1797 /**
1798  * drm_dp_mst_topology_get_mstb() - Increment the topology refcount of a
1799  * branch device
1800  * @mstb: The &struct drm_dp_mst_branch to increment the topology refcount of
1801  *
1802  * Increments &drm_dp_mst_branch.topology_refcount without checking whether or
1803  * not it's already reached 0. This is only valid to use in scenarios where
1804  * you are already guaranteed to have at least one active topology reference
1805  * to @mstb. Otherwise, drm_dp_mst_topology_try_get_mstb() must be used.
1806  *
1807  * See also:
1808  * drm_dp_mst_topology_try_get_mstb()
1809  * drm_dp_mst_topology_put_mstb()
1810  */
drm_dp_mst_topology_get_mstb(struct drm_dp_mst_branch * mstb)1811 static void drm_dp_mst_topology_get_mstb(struct drm_dp_mst_branch *mstb)
1812 {
1813 	topology_ref_history_lock(mstb->mgr);
1814 
1815 	save_mstb_topology_ref(mstb, DRM_DP_MST_TOPOLOGY_REF_GET);
1816 	WARN_ON(kref_read(&mstb->topology_kref) == 0);
1817 	kref_get(&mstb->topology_kref);
1818 	DRM_DEBUG("mstb %p (%d)\n", mstb, kref_read(&mstb->topology_kref));
1819 
1820 	topology_ref_history_unlock(mstb->mgr);
1821 }
1822 
1823 /**
1824  * drm_dp_mst_topology_put_mstb() - release a topology reference to a branch
1825  * device
1826  * @mstb: The &struct drm_dp_mst_branch to release the topology reference from
1827  *
1828  * Releases a topology reference from @mstb by decrementing
1829  * &drm_dp_mst_branch.topology_kref.
1830  *
1831  * See also:
1832  * drm_dp_mst_topology_try_get_mstb()
1833  * drm_dp_mst_topology_get_mstb()
1834  */
1835 static void
drm_dp_mst_topology_put_mstb(struct drm_dp_mst_branch * mstb)1836 drm_dp_mst_topology_put_mstb(struct drm_dp_mst_branch *mstb)
1837 {
1838 	topology_ref_history_lock(mstb->mgr);
1839 
1840 	DRM_DEBUG("mstb %p (%d)\n",
1841 		  mstb, kref_read(&mstb->topology_kref) - 1);
1842 	save_mstb_topology_ref(mstb, DRM_DP_MST_TOPOLOGY_REF_PUT);
1843 
1844 	topology_ref_history_unlock(mstb->mgr);
1845 	kref_put(&mstb->topology_kref, drm_dp_destroy_mst_branch_device);
1846 }
1847 
drm_dp_destroy_port(struct kref * kref)1848 static void drm_dp_destroy_port(struct kref *kref)
1849 {
1850 	struct drm_dp_mst_port *port =
1851 		container_of(kref, struct drm_dp_mst_port, topology_kref);
1852 	struct drm_dp_mst_topology_mgr *mgr = port->mgr;
1853 
1854 	drm_dp_mst_dump_port_topology_history(port);
1855 
1856 	/* There's nothing that needs locking to destroy an input port yet */
1857 	if (port->input) {
1858 		drm_dp_mst_put_port_malloc(port);
1859 		return;
1860 	}
1861 
1862 	kfree(port->cached_edid);
1863 
1864 	/*
1865 	 * we can't destroy the connector here, as we might be holding the
1866 	 * mode_config.mutex from an EDID retrieval
1867 	 */
1868 	mutex_lock(&mgr->delayed_destroy_lock);
1869 	list_add(&port->next, &mgr->destroy_port_list);
1870 	mutex_unlock(&mgr->delayed_destroy_lock);
1871 	queue_work(mgr->delayed_destroy_wq, &mgr->delayed_destroy_work);
1872 }
1873 
1874 /**
1875  * drm_dp_mst_topology_try_get_port() - Increment the topology refcount of a
1876  * port unless it's zero
1877  * @port: &struct drm_dp_mst_port to increment the topology refcount of
1878  *
1879  * Attempts to grab a topology reference to @port, if it hasn't yet been
1880  * removed from the topology (e.g. &drm_dp_mst_port.topology_kref has reached
1881  * 0). Holding a topology reference implies that a malloc reference will be
1882  * held to @port as long as the user holds the topology reference.
1883  *
1884  * Care should be taken to ensure that the user has at least one malloc
1885  * reference to @port. If you already have a topology reference to @port, you
1886  * should use drm_dp_mst_topology_get_port() instead.
1887  *
1888  * See also:
1889  * drm_dp_mst_topology_get_port()
1890  * drm_dp_mst_topology_put_port()
1891  *
1892  * Returns:
1893  * * 1: A topology reference was grabbed successfully
1894  * * 0: @port is no longer in the topology, no reference was grabbed
1895  */
1896 static int __must_check
drm_dp_mst_topology_try_get_port(struct drm_dp_mst_port * port)1897 drm_dp_mst_topology_try_get_port(struct drm_dp_mst_port *port)
1898 {
1899 	int ret;
1900 
1901 	topology_ref_history_lock(port->mgr);
1902 	ret = kref_get_unless_zero(&port->topology_kref);
1903 	if (ret) {
1904 		DRM_DEBUG("port %p (%d)\n",
1905 			  port, kref_read(&port->topology_kref));
1906 		save_port_topology_ref(port, DRM_DP_MST_TOPOLOGY_REF_GET);
1907 	}
1908 
1909 	topology_ref_history_unlock(port->mgr);
1910 	return ret;
1911 }
1912 
1913 /**
1914  * drm_dp_mst_topology_get_port() - Increment the topology refcount of a port
1915  * @port: The &struct drm_dp_mst_port to increment the topology refcount of
1916  *
1917  * Increments &drm_dp_mst_port.topology_refcount without checking whether or
1918  * not it's already reached 0. This is only valid to use in scenarios where
1919  * you are already guaranteed to have at least one active topology reference
1920  * to @port. Otherwise, drm_dp_mst_topology_try_get_port() must be used.
1921  *
1922  * See also:
1923  * drm_dp_mst_topology_try_get_port()
1924  * drm_dp_mst_topology_put_port()
1925  */
drm_dp_mst_topology_get_port(struct drm_dp_mst_port * port)1926 static void drm_dp_mst_topology_get_port(struct drm_dp_mst_port *port)
1927 {
1928 	topology_ref_history_lock(port->mgr);
1929 
1930 	WARN_ON(kref_read(&port->topology_kref) == 0);
1931 	kref_get(&port->topology_kref);
1932 	DRM_DEBUG("port %p (%d)\n", port, kref_read(&port->topology_kref));
1933 	save_port_topology_ref(port, DRM_DP_MST_TOPOLOGY_REF_GET);
1934 
1935 	topology_ref_history_unlock(port->mgr);
1936 }
1937 
1938 /**
1939  * drm_dp_mst_topology_put_port() - release a topology reference to a port
1940  * @port: The &struct drm_dp_mst_port to release the topology reference from
1941  *
1942  * Releases a topology reference from @port by decrementing
1943  * &drm_dp_mst_port.topology_kref.
1944  *
1945  * See also:
1946  * drm_dp_mst_topology_try_get_port()
1947  * drm_dp_mst_topology_get_port()
1948  */
drm_dp_mst_topology_put_port(struct drm_dp_mst_port * port)1949 static void drm_dp_mst_topology_put_port(struct drm_dp_mst_port *port)
1950 {
1951 	topology_ref_history_lock(port->mgr);
1952 
1953 	DRM_DEBUG("port %p (%d)\n",
1954 		  port, kref_read(&port->topology_kref) - 1);
1955 	save_port_topology_ref(port, DRM_DP_MST_TOPOLOGY_REF_PUT);
1956 
1957 	topology_ref_history_unlock(port->mgr);
1958 	kref_put(&port->topology_kref, drm_dp_destroy_port);
1959 }
1960 
1961 static struct drm_dp_mst_branch *
drm_dp_mst_topology_get_mstb_validated_locked(struct drm_dp_mst_branch * mstb,struct drm_dp_mst_branch * to_find)1962 drm_dp_mst_topology_get_mstb_validated_locked(struct drm_dp_mst_branch *mstb,
1963 					      struct drm_dp_mst_branch *to_find)
1964 {
1965 	struct drm_dp_mst_port *port;
1966 	struct drm_dp_mst_branch *rmstb;
1967 
1968 	if (to_find == mstb)
1969 		return mstb;
1970 
1971 	list_for_each_entry(port, &mstb->ports, next) {
1972 		if (port->mstb) {
1973 			rmstb = drm_dp_mst_topology_get_mstb_validated_locked(
1974 			    port->mstb, to_find);
1975 			if (rmstb)
1976 				return rmstb;
1977 		}
1978 	}
1979 	return NULL;
1980 }
1981 
1982 static struct drm_dp_mst_branch *
drm_dp_mst_topology_get_mstb_validated(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_branch * mstb)1983 drm_dp_mst_topology_get_mstb_validated(struct drm_dp_mst_topology_mgr *mgr,
1984 				       struct drm_dp_mst_branch *mstb)
1985 {
1986 	struct drm_dp_mst_branch *rmstb = NULL;
1987 
1988 	mutex_lock(&mgr->lock);
1989 	if (mgr->mst_primary) {
1990 		rmstb = drm_dp_mst_topology_get_mstb_validated_locked(
1991 		    mgr->mst_primary, mstb);
1992 
1993 		if (rmstb && !drm_dp_mst_topology_try_get_mstb(rmstb))
1994 			rmstb = NULL;
1995 	}
1996 	mutex_unlock(&mgr->lock);
1997 	return rmstb;
1998 }
1999 
2000 static struct drm_dp_mst_port *
drm_dp_mst_topology_get_port_validated_locked(struct drm_dp_mst_branch * mstb,struct drm_dp_mst_port * to_find)2001 drm_dp_mst_topology_get_port_validated_locked(struct drm_dp_mst_branch *mstb,
2002 					      struct drm_dp_mst_port *to_find)
2003 {
2004 	struct drm_dp_mst_port *port, *mport;
2005 
2006 	list_for_each_entry(port, &mstb->ports, next) {
2007 		if (port == to_find)
2008 			return port;
2009 
2010 		if (port->mstb) {
2011 			mport = drm_dp_mst_topology_get_port_validated_locked(
2012 			    port->mstb, to_find);
2013 			if (mport)
2014 				return mport;
2015 		}
2016 	}
2017 	return NULL;
2018 }
2019 
2020 static struct drm_dp_mst_port *
drm_dp_mst_topology_get_port_validated(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port)2021 drm_dp_mst_topology_get_port_validated(struct drm_dp_mst_topology_mgr *mgr,
2022 				       struct drm_dp_mst_port *port)
2023 {
2024 	struct drm_dp_mst_port *rport = NULL;
2025 
2026 	mutex_lock(&mgr->lock);
2027 	if (mgr->mst_primary) {
2028 		rport = drm_dp_mst_topology_get_port_validated_locked(
2029 		    mgr->mst_primary, port);
2030 
2031 		if (rport && !drm_dp_mst_topology_try_get_port(rport))
2032 			rport = NULL;
2033 	}
2034 	mutex_unlock(&mgr->lock);
2035 	return rport;
2036 }
2037 
drm_dp_get_port(struct drm_dp_mst_branch * mstb,u8 port_num)2038 static struct drm_dp_mst_port *drm_dp_get_port(struct drm_dp_mst_branch *mstb, u8 port_num)
2039 {
2040 	struct drm_dp_mst_port *port;
2041 	int ret;
2042 
2043 	list_for_each_entry(port, &mstb->ports, next) {
2044 		if (port->port_num == port_num) {
2045 			ret = drm_dp_mst_topology_try_get_port(port);
2046 			return ret ? port : NULL;
2047 		}
2048 	}
2049 
2050 	return NULL;
2051 }
2052 
2053 /*
2054  * calculate a new RAD for this MST branch device
2055  * if parent has an LCT of 2 then it has 1 nibble of RAD,
2056  * if parent has an LCT of 3 then it has 2 nibbles of RAD,
2057  */
drm_dp_calculate_rad(struct drm_dp_mst_port * port,u8 * rad)2058 static u8 drm_dp_calculate_rad(struct drm_dp_mst_port *port,
2059 				 u8 *rad)
2060 {
2061 	int parent_lct = port->parent->lct;
2062 	int shift = 4;
2063 	int idx = (parent_lct - 1) / 2;
2064 
2065 	if (parent_lct > 1) {
2066 		memcpy(rad, port->parent->rad, idx + 1);
2067 		shift = (parent_lct % 2) ? 4 : 0;
2068 	} else
2069 		rad[0] = 0;
2070 
2071 	rad[idx] |= port->port_num << shift;
2072 	return parent_lct + 1;
2073 }
2074 
drm_dp_mst_is_end_device(u8 pdt,bool mcs)2075 static bool drm_dp_mst_is_end_device(u8 pdt, bool mcs)
2076 {
2077 	switch (pdt) {
2078 	case DP_PEER_DEVICE_DP_LEGACY_CONV:
2079 	case DP_PEER_DEVICE_SST_SINK:
2080 		return true;
2081 	case DP_PEER_DEVICE_MST_BRANCHING:
2082 		/* For sst branch device */
2083 		if (!mcs)
2084 			return true;
2085 
2086 		return false;
2087 	}
2088 	return true;
2089 }
2090 
2091 static int
drm_dp_port_set_pdt(struct drm_dp_mst_port * port,u8 new_pdt,bool new_mcs)2092 drm_dp_port_set_pdt(struct drm_dp_mst_port *port, u8 new_pdt,
2093 		    bool new_mcs)
2094 {
2095 	struct drm_dp_mst_topology_mgr *mgr = port->mgr;
2096 	struct drm_dp_mst_branch *mstb;
2097 	u8 rad[8], lct;
2098 	int ret = 0;
2099 
2100 	if (port->pdt == new_pdt && port->mcs == new_mcs)
2101 		return 0;
2102 
2103 	/* Teardown the old pdt, if there is one */
2104 	if (port->pdt != DP_PEER_DEVICE_NONE) {
2105 		if (drm_dp_mst_is_end_device(port->pdt, port->mcs)) {
2106 			/*
2107 			 * If the new PDT would also have an i2c bus,
2108 			 * don't bother with reregistering it
2109 			 */
2110 			if (new_pdt != DP_PEER_DEVICE_NONE &&
2111 			    drm_dp_mst_is_end_device(new_pdt, new_mcs)) {
2112 				port->pdt = new_pdt;
2113 				port->mcs = new_mcs;
2114 				return 0;
2115 			}
2116 
2117 			/* remove i2c over sideband */
2118 			drm_dp_mst_unregister_i2c_bus(port);
2119 		} else {
2120 			mutex_lock(&mgr->lock);
2121 			drm_dp_mst_topology_put_mstb(port->mstb);
2122 			port->mstb = NULL;
2123 			mutex_unlock(&mgr->lock);
2124 		}
2125 	}
2126 
2127 	port->pdt = new_pdt;
2128 	port->mcs = new_mcs;
2129 
2130 	if (port->pdt != DP_PEER_DEVICE_NONE) {
2131 		if (drm_dp_mst_is_end_device(port->pdt, port->mcs)) {
2132 			/* add i2c over sideband */
2133 			ret = drm_dp_mst_register_i2c_bus(port);
2134 		} else {
2135 			lct = drm_dp_calculate_rad(port, rad);
2136 			mstb = drm_dp_add_mst_branch_device(lct, rad);
2137 			if (!mstb) {
2138 				ret = -ENOMEM;
2139 				DRM_ERROR("Failed to create MSTB for port %p",
2140 					  port);
2141 				goto out;
2142 			}
2143 
2144 			mutex_lock(&mgr->lock);
2145 			port->mstb = mstb;
2146 			mstb->mgr = port->mgr;
2147 			mstb->port_parent = port;
2148 
2149 			/*
2150 			 * Make sure this port's memory allocation stays
2151 			 * around until its child MSTB releases it
2152 			 */
2153 			drm_dp_mst_get_port_malloc(port);
2154 			mutex_unlock(&mgr->lock);
2155 
2156 			/* And make sure we send a link address for this */
2157 			ret = 1;
2158 		}
2159 	}
2160 
2161 out:
2162 	if (ret < 0)
2163 		port->pdt = DP_PEER_DEVICE_NONE;
2164 	return ret;
2165 }
2166 
2167 /**
2168  * drm_dp_mst_dpcd_read() - read a series of bytes from the DPCD via sideband
2169  * @aux: Fake sideband AUX CH
2170  * @offset: address of the (first) register to read
2171  * @buffer: buffer to store the register values
2172  * @size: number of bytes in @buffer
2173  *
2174  * Performs the same functionality for remote devices via
2175  * sideband messaging as drm_dp_dpcd_read() does for local
2176  * devices via actual AUX CH.
2177  *
2178  * Return: Number of bytes read, or negative error code on failure.
2179  */
drm_dp_mst_dpcd_read(struct drm_dp_aux * aux,unsigned int offset,void * buffer,size_t size)2180 ssize_t drm_dp_mst_dpcd_read(struct drm_dp_aux *aux,
2181 			     unsigned int offset, void *buffer, size_t size)
2182 {
2183 	struct drm_dp_mst_port *port = container_of(aux, struct drm_dp_mst_port,
2184 						    aux);
2185 
2186 	return drm_dp_send_dpcd_read(port->mgr, port,
2187 				     offset, size, buffer);
2188 }
2189 
2190 /**
2191  * drm_dp_mst_dpcd_write() - write a series of bytes to the DPCD via sideband
2192  * @aux: Fake sideband AUX CH
2193  * @offset: address of the (first) register to write
2194  * @buffer: buffer containing the values to write
2195  * @size: number of bytes in @buffer
2196  *
2197  * Performs the same functionality for remote devices via
2198  * sideband messaging as drm_dp_dpcd_write() does for local
2199  * devices via actual AUX CH.
2200  *
2201  * Return: number of bytes written on success, negative error code on failure.
2202  */
drm_dp_mst_dpcd_write(struct drm_dp_aux * aux,unsigned int offset,void * buffer,size_t size)2203 ssize_t drm_dp_mst_dpcd_write(struct drm_dp_aux *aux,
2204 			      unsigned int offset, void *buffer, size_t size)
2205 {
2206 	struct drm_dp_mst_port *port = container_of(aux, struct drm_dp_mst_port,
2207 						    aux);
2208 
2209 	return drm_dp_send_dpcd_write(port->mgr, port,
2210 				      offset, size, buffer);
2211 }
2212 
drm_dp_check_mstb_guid(struct drm_dp_mst_branch * mstb,u8 * guid)2213 static int drm_dp_check_mstb_guid(struct drm_dp_mst_branch *mstb, u8 *guid)
2214 {
2215 	int ret = 0;
2216 
2217 	memcpy(mstb->guid, guid, 16);
2218 
2219 	if (!drm_dp_validate_guid(mstb->mgr, mstb->guid)) {
2220 		if (mstb->port_parent) {
2221 			ret = drm_dp_send_dpcd_write(mstb->mgr,
2222 						     mstb->port_parent,
2223 						     DP_GUID, 16, mstb->guid);
2224 		} else {
2225 			ret = drm_dp_dpcd_write(mstb->mgr->aux,
2226 						DP_GUID, mstb->guid, 16);
2227 		}
2228 	}
2229 
2230 	if (ret < 16 && ret > 0)
2231 		return -EPROTO;
2232 
2233 	return ret == 16 ? 0 : ret;
2234 }
2235 
build_mst_prop_path(const struct drm_dp_mst_branch * mstb,int pnum,char * proppath,size_t proppath_size)2236 static void build_mst_prop_path(const struct drm_dp_mst_branch *mstb,
2237 				int pnum,
2238 				char *proppath,
2239 				size_t proppath_size)
2240 {
2241 	int i;
2242 	char temp[8];
2243 
2244 	snprintf(proppath, proppath_size, "mst:%d", mstb->mgr->conn_base_id);
2245 	for (i = 0; i < (mstb->lct - 1); i++) {
2246 		int shift = (i % 2) ? 0 : 4;
2247 		int port_num = (mstb->rad[i / 2] >> shift) & 0xf;
2248 
2249 		snprintf(temp, sizeof(temp), "-%d", port_num);
2250 		strlcat(proppath, temp, proppath_size);
2251 	}
2252 	snprintf(temp, sizeof(temp), "-%d", pnum);
2253 	strlcat(proppath, temp, proppath_size);
2254 }
2255 
2256 /**
2257  * drm_dp_mst_connector_late_register() - Late MST connector registration
2258  * @connector: The MST connector
2259  * @port: The MST port for this connector
2260  *
2261  * Helper to register the remote aux device for this MST port. Drivers should
2262  * call this from their mst connector's late_register hook to enable MST aux
2263  * devices.
2264  *
2265  * Return: 0 on success, negative error code on failure.
2266  */
drm_dp_mst_connector_late_register(struct drm_connector * connector,struct drm_dp_mst_port * port)2267 int drm_dp_mst_connector_late_register(struct drm_connector *connector,
2268 				       struct drm_dp_mst_port *port)
2269 {
2270 	DRM_DEBUG_KMS("registering %s remote bus for %s\n",
2271 		      port->aux.name, connector->kdev->kobj.name);
2272 
2273 	port->aux.dev = connector->kdev;
2274 	return drm_dp_aux_register_devnode(&port->aux);
2275 }
2276 EXPORT_SYMBOL(drm_dp_mst_connector_late_register);
2277 
2278 /**
2279  * drm_dp_mst_connector_early_unregister() - Early MST connector unregistration
2280  * @connector: The MST connector
2281  * @port: The MST port for this connector
2282  *
2283  * Helper to unregister the remote aux device for this MST port, registered by
2284  * drm_dp_mst_connector_late_register(). Drivers should call this from their mst
2285  * connector's early_unregister hook.
2286  */
drm_dp_mst_connector_early_unregister(struct drm_connector * connector,struct drm_dp_mst_port * port)2287 void drm_dp_mst_connector_early_unregister(struct drm_connector *connector,
2288 					   struct drm_dp_mst_port *port)
2289 {
2290 	DRM_DEBUG_KMS("unregistering %s remote bus for %s\n",
2291 		      port->aux.name, connector->kdev->kobj.name);
2292 	drm_dp_aux_unregister_devnode(&port->aux);
2293 }
2294 EXPORT_SYMBOL(drm_dp_mst_connector_early_unregister);
2295 
2296 static void
drm_dp_mst_port_add_connector(struct drm_dp_mst_branch * mstb,struct drm_dp_mst_port * port)2297 drm_dp_mst_port_add_connector(struct drm_dp_mst_branch *mstb,
2298 			      struct drm_dp_mst_port *port)
2299 {
2300 	struct drm_dp_mst_topology_mgr *mgr = port->mgr;
2301 	char proppath[255];
2302 	int ret;
2303 
2304 	build_mst_prop_path(mstb, port->port_num, proppath, sizeof(proppath));
2305 	port->connector = mgr->cbs->add_connector(mgr, port, proppath);
2306 	if (!port->connector) {
2307 		ret = -ENOMEM;
2308 		goto error;
2309 	}
2310 
2311 	if (port->pdt != DP_PEER_DEVICE_NONE &&
2312 	    drm_dp_mst_is_end_device(port->pdt, port->mcs) &&
2313 	    port->port_num >= DP_MST_LOGICAL_PORT_0) {
2314 		port->cached_edid = drm_get_edid(port->connector,
2315 						 &port->aux.ddc);
2316 		drm_connector_set_tile_property(port->connector);
2317 	}
2318 
2319 	drm_connector_register(port->connector);
2320 	return;
2321 
2322 error:
2323 	DRM_ERROR("Failed to create connector for port %p: %d\n", port, ret);
2324 }
2325 
2326 /*
2327  * Drop a topology reference, and unlink the port from the in-memory topology
2328  * layout
2329  */
2330 static void
drm_dp_mst_topology_unlink_port(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port)2331 drm_dp_mst_topology_unlink_port(struct drm_dp_mst_topology_mgr *mgr,
2332 				struct drm_dp_mst_port *port)
2333 {
2334 	mutex_lock(&mgr->lock);
2335 	port->parent->num_ports--;
2336 	list_del(&port->next);
2337 	mutex_unlock(&mgr->lock);
2338 	drm_dp_mst_topology_put_port(port);
2339 }
2340 
2341 static struct drm_dp_mst_port *
drm_dp_mst_add_port(struct drm_device * dev,struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_branch * mstb,u8 port_number)2342 drm_dp_mst_add_port(struct drm_device *dev,
2343 		    struct drm_dp_mst_topology_mgr *mgr,
2344 		    struct drm_dp_mst_branch *mstb, u8 port_number)
2345 {
2346 	struct drm_dp_mst_port *port = kzalloc(sizeof(*port), GFP_KERNEL);
2347 
2348 	if (!port)
2349 		return NULL;
2350 
2351 	kref_init(&port->topology_kref);
2352 	kref_init(&port->malloc_kref);
2353 	port->parent = mstb;
2354 	port->port_num = port_number;
2355 	port->mgr = mgr;
2356 	port->aux.name = "DPMST";
2357 	port->aux.dev = dev->dev;
2358 	port->aux.is_remote = true;
2359 
2360 	/* initialize the MST downstream port's AUX crc work queue */
2361 	drm_dp_remote_aux_init(&port->aux);
2362 
2363 	/*
2364 	 * Make sure the memory allocation for our parent branch stays
2365 	 * around until our own memory allocation is released
2366 	 */
2367 	drm_dp_mst_get_mstb_malloc(mstb);
2368 
2369 	return port;
2370 }
2371 
2372 static int
drm_dp_mst_handle_link_address_port(struct drm_dp_mst_branch * mstb,struct drm_device * dev,struct drm_dp_link_addr_reply_port * port_msg)2373 drm_dp_mst_handle_link_address_port(struct drm_dp_mst_branch *mstb,
2374 				    struct drm_device *dev,
2375 				    struct drm_dp_link_addr_reply_port *port_msg)
2376 {
2377 	struct drm_dp_mst_topology_mgr *mgr = mstb->mgr;
2378 	struct drm_dp_mst_port *port;
2379 	int old_ddps = 0, ret;
2380 	u8 new_pdt = DP_PEER_DEVICE_NONE;
2381 	bool new_mcs = 0;
2382 	bool created = false, send_link_addr = false, changed = false;
2383 
2384 	port = drm_dp_get_port(mstb, port_msg->port_number);
2385 	if (!port) {
2386 		port = drm_dp_mst_add_port(dev, mgr, mstb,
2387 					   port_msg->port_number);
2388 		if (!port)
2389 			return -ENOMEM;
2390 		created = true;
2391 		changed = true;
2392 	} else if (!port->input && port_msg->input_port && port->connector) {
2393 		/* Since port->connector can't be changed here, we create a
2394 		 * new port if input_port changes from 0 to 1
2395 		 */
2396 		drm_dp_mst_topology_unlink_port(mgr, port);
2397 		drm_dp_mst_topology_put_port(port);
2398 		port = drm_dp_mst_add_port(dev, mgr, mstb,
2399 					   port_msg->port_number);
2400 		if (!port)
2401 			return -ENOMEM;
2402 		changed = true;
2403 		created = true;
2404 	} else if (port->input && !port_msg->input_port) {
2405 		changed = true;
2406 	} else if (port->connector) {
2407 		/* We're updating a port that's exposed to userspace, so do it
2408 		 * under lock
2409 		 */
2410 		drm_modeset_lock(&mgr->base.lock, NULL);
2411 
2412 		old_ddps = port->ddps;
2413 		changed = port->ddps != port_msg->ddps ||
2414 			(port->ddps &&
2415 			 (port->ldps != port_msg->legacy_device_plug_status ||
2416 			  port->dpcd_rev != port_msg->dpcd_revision ||
2417 			  port->mcs != port_msg->mcs ||
2418 			  port->pdt != port_msg->peer_device_type ||
2419 			  port->num_sdp_stream_sinks !=
2420 			  port_msg->num_sdp_stream_sinks));
2421 	}
2422 
2423 	port->input = port_msg->input_port;
2424 	if (!port->input)
2425 		new_pdt = port_msg->peer_device_type;
2426 	new_mcs = port_msg->mcs;
2427 	port->ddps = port_msg->ddps;
2428 	port->ldps = port_msg->legacy_device_plug_status;
2429 	port->dpcd_rev = port_msg->dpcd_revision;
2430 	port->num_sdp_streams = port_msg->num_sdp_streams;
2431 	port->num_sdp_stream_sinks = port_msg->num_sdp_stream_sinks;
2432 
2433 	/* manage mstb port lists with mgr lock - take a reference
2434 	   for this list */
2435 	if (created) {
2436 		mutex_lock(&mgr->lock);
2437 		drm_dp_mst_topology_get_port(port);
2438 		list_add(&port->next, &mstb->ports);
2439 		mstb->num_ports++;
2440 		mutex_unlock(&mgr->lock);
2441 	}
2442 
2443 	/*
2444 	 * Reprobe PBN caps on both hotplug, and when re-probing the link
2445 	 * for our parent mstb
2446 	 */
2447 	if (old_ddps != port->ddps || !created) {
2448 		if (port->ddps && !port->input) {
2449 			ret = drm_dp_send_enum_path_resources(mgr, mstb,
2450 							      port);
2451 			if (ret == 1)
2452 				changed = true;
2453 		} else {
2454 			port->full_pbn = 0;
2455 		}
2456 	}
2457 
2458 	ret = drm_dp_port_set_pdt(port, new_pdt, new_mcs);
2459 	if (ret == 1) {
2460 		send_link_addr = true;
2461 	} else if (ret < 0) {
2462 		DRM_ERROR("Failed to change PDT on port %p: %d\n",
2463 			  port, ret);
2464 		goto fail;
2465 	}
2466 
2467 	/*
2468 	 * If this port wasn't just created, then we're reprobing because
2469 	 * we're coming out of suspend. In this case, always resend the link
2470 	 * address if there's an MSTB on this port
2471 	 */
2472 	if (!created && port->pdt == DP_PEER_DEVICE_MST_BRANCHING &&
2473 	    port->mcs)
2474 		send_link_addr = true;
2475 
2476 	if (port->connector)
2477 		drm_modeset_unlock(&mgr->base.lock);
2478 	else if (!port->input)
2479 		drm_dp_mst_port_add_connector(mstb, port);
2480 
2481 	if (send_link_addr && port->mstb) {
2482 		ret = drm_dp_send_link_address(mgr, port->mstb);
2483 		if (ret == 1) /* MSTB below us changed */
2484 			changed = true;
2485 		else if (ret < 0)
2486 			goto fail_put;
2487 	}
2488 
2489 	/* put reference to this port */
2490 	drm_dp_mst_topology_put_port(port);
2491 	return changed;
2492 
2493 fail:
2494 	drm_dp_mst_topology_unlink_port(mgr, port);
2495 	if (port->connector)
2496 		drm_modeset_unlock(&mgr->base.lock);
2497 fail_put:
2498 	drm_dp_mst_topology_put_port(port);
2499 	return ret;
2500 }
2501 
2502 static void
drm_dp_mst_handle_conn_stat(struct drm_dp_mst_branch * mstb,struct drm_dp_connection_status_notify * conn_stat)2503 drm_dp_mst_handle_conn_stat(struct drm_dp_mst_branch *mstb,
2504 			    struct drm_dp_connection_status_notify *conn_stat)
2505 {
2506 	struct drm_dp_mst_topology_mgr *mgr = mstb->mgr;
2507 	struct drm_dp_mst_port *port;
2508 	int old_ddps, ret;
2509 	u8 new_pdt;
2510 	bool new_mcs;
2511 	bool dowork = false, create_connector = false;
2512 
2513 	port = drm_dp_get_port(mstb, conn_stat->port_number);
2514 	if (!port)
2515 		return;
2516 
2517 	if (port->connector) {
2518 		if (!port->input && conn_stat->input_port) {
2519 			/*
2520 			 * We can't remove a connector from an already exposed
2521 			 * port, so just throw the port out and make sure we
2522 			 * reprobe the link address of it's parent MSTB
2523 			 */
2524 			drm_dp_mst_topology_unlink_port(mgr, port);
2525 			mstb->link_address_sent = false;
2526 			dowork = true;
2527 			goto out;
2528 		}
2529 
2530 		/* Locking is only needed if the port's exposed to userspace */
2531 		drm_modeset_lock(&mgr->base.lock, NULL);
2532 	} else if (port->input && !conn_stat->input_port) {
2533 		create_connector = true;
2534 		/* Reprobe link address so we get num_sdp_streams */
2535 		mstb->link_address_sent = false;
2536 		dowork = true;
2537 	}
2538 
2539 	old_ddps = port->ddps;
2540 	port->input = conn_stat->input_port;
2541 	port->ldps = conn_stat->legacy_device_plug_status;
2542 	port->ddps = conn_stat->displayport_device_plug_status;
2543 
2544 	if (old_ddps != port->ddps) {
2545 		if (port->ddps && !port->input)
2546 			drm_dp_send_enum_path_resources(mgr, mstb, port);
2547 		else
2548 			port->full_pbn = 0;
2549 	}
2550 
2551 	new_pdt = port->input ? DP_PEER_DEVICE_NONE : conn_stat->peer_device_type;
2552 	new_mcs = conn_stat->message_capability_status;
2553 	ret = drm_dp_port_set_pdt(port, new_pdt, new_mcs);
2554 	if (ret == 1) {
2555 		dowork = true;
2556 	} else if (ret < 0) {
2557 		DRM_ERROR("Failed to change PDT for port %p: %d\n",
2558 			  port, ret);
2559 		dowork = false;
2560 	}
2561 
2562 	if (port->connector)
2563 		drm_modeset_unlock(&mgr->base.lock);
2564 	else if (create_connector)
2565 		drm_dp_mst_port_add_connector(mstb, port);
2566 
2567 out:
2568 	drm_dp_mst_topology_put_port(port);
2569 	if (dowork)
2570 		queue_work(system_long_wq, &mstb->mgr->work);
2571 }
2572 
drm_dp_get_mst_branch_device(struct drm_dp_mst_topology_mgr * mgr,u8 lct,u8 * rad)2573 static struct drm_dp_mst_branch *drm_dp_get_mst_branch_device(struct drm_dp_mst_topology_mgr *mgr,
2574 							       u8 lct, u8 *rad)
2575 {
2576 	struct drm_dp_mst_branch *mstb;
2577 	struct drm_dp_mst_port *port;
2578 	int i, ret;
2579 	/* find the port by iterating down */
2580 
2581 	mutex_lock(&mgr->lock);
2582 	mstb = mgr->mst_primary;
2583 
2584 	if (!mstb)
2585 		goto out;
2586 
2587 	for (i = 0; i < lct - 1; i++) {
2588 		int shift = (i % 2) ? 0 : 4;
2589 		int port_num = (rad[i / 2] >> shift) & 0xf;
2590 
2591 		list_for_each_entry(port, &mstb->ports, next) {
2592 			if (port->port_num == port_num) {
2593 				mstb = port->mstb;
2594 				if (!mstb) {
2595 					DRM_ERROR("failed to lookup MSTB with lct %d, rad %02x\n", lct, rad[0]);
2596 					goto out;
2597 				}
2598 
2599 				break;
2600 			}
2601 		}
2602 	}
2603 	ret = drm_dp_mst_topology_try_get_mstb(mstb);
2604 	if (!ret)
2605 		mstb = NULL;
2606 out:
2607 	mutex_unlock(&mgr->lock);
2608 	return mstb;
2609 }
2610 
get_mst_branch_device_by_guid_helper(struct drm_dp_mst_branch * mstb,const uint8_t * guid)2611 static struct drm_dp_mst_branch *get_mst_branch_device_by_guid_helper(
2612 	struct drm_dp_mst_branch *mstb,
2613 	const uint8_t *guid)
2614 {
2615 	struct drm_dp_mst_branch *found_mstb;
2616 	struct drm_dp_mst_port *port;
2617 
2618 	if (!mstb)
2619 		return NULL;
2620 
2621 	if (memcmp(mstb->guid, guid, 16) == 0)
2622 		return mstb;
2623 
2624 
2625 	list_for_each_entry(port, &mstb->ports, next) {
2626 		found_mstb = get_mst_branch_device_by_guid_helper(port->mstb, guid);
2627 
2628 		if (found_mstb)
2629 			return found_mstb;
2630 	}
2631 
2632 	return NULL;
2633 }
2634 
2635 static struct drm_dp_mst_branch *
drm_dp_get_mst_branch_device_by_guid(struct drm_dp_mst_topology_mgr * mgr,const uint8_t * guid)2636 drm_dp_get_mst_branch_device_by_guid(struct drm_dp_mst_topology_mgr *mgr,
2637 				     const uint8_t *guid)
2638 {
2639 	struct drm_dp_mst_branch *mstb;
2640 	int ret;
2641 
2642 	/* find the port by iterating down */
2643 	mutex_lock(&mgr->lock);
2644 
2645 	mstb = get_mst_branch_device_by_guid_helper(mgr->mst_primary, guid);
2646 	if (mstb) {
2647 		ret = drm_dp_mst_topology_try_get_mstb(mstb);
2648 		if (!ret)
2649 			mstb = NULL;
2650 	}
2651 
2652 	mutex_unlock(&mgr->lock);
2653 	return mstb;
2654 }
2655 
drm_dp_check_and_send_link_address(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_branch * mstb)2656 static int drm_dp_check_and_send_link_address(struct drm_dp_mst_topology_mgr *mgr,
2657 					       struct drm_dp_mst_branch *mstb)
2658 {
2659 	struct drm_dp_mst_port *port;
2660 	int ret;
2661 	bool changed = false;
2662 
2663 	if (!mstb->link_address_sent) {
2664 		ret = drm_dp_send_link_address(mgr, mstb);
2665 		if (ret == 1)
2666 			changed = true;
2667 		else if (ret < 0)
2668 			return ret;
2669 	}
2670 
2671 	list_for_each_entry(port, &mstb->ports, next) {
2672 		struct drm_dp_mst_branch *mstb_child = NULL;
2673 
2674 		if (port->input || !port->ddps)
2675 			continue;
2676 
2677 		if (port->mstb)
2678 			mstb_child = drm_dp_mst_topology_get_mstb_validated(
2679 			    mgr, port->mstb);
2680 
2681 		if (mstb_child) {
2682 			ret = drm_dp_check_and_send_link_address(mgr,
2683 								 mstb_child);
2684 			drm_dp_mst_topology_put_mstb(mstb_child);
2685 			if (ret == 1)
2686 				changed = true;
2687 			else if (ret < 0)
2688 				return ret;
2689 		}
2690 	}
2691 
2692 	return changed;
2693 }
2694 
drm_dp_mst_link_probe_work(struct work_struct * work)2695 static void drm_dp_mst_link_probe_work(struct work_struct *work)
2696 {
2697 	struct drm_dp_mst_topology_mgr *mgr =
2698 		container_of(work, struct drm_dp_mst_topology_mgr, work);
2699 	struct drm_device *dev = mgr->dev;
2700 	struct drm_dp_mst_branch *mstb;
2701 	int ret;
2702 	bool clear_payload_id_table;
2703 
2704 	mutex_lock(&mgr->probe_lock);
2705 
2706 	mutex_lock(&mgr->lock);
2707 	clear_payload_id_table = !mgr->payload_id_table_cleared;
2708 	mgr->payload_id_table_cleared = true;
2709 
2710 	mstb = mgr->mst_primary;
2711 	if (mstb) {
2712 		ret = drm_dp_mst_topology_try_get_mstb(mstb);
2713 		if (!ret)
2714 			mstb = NULL;
2715 	}
2716 	mutex_unlock(&mgr->lock);
2717 	if (!mstb) {
2718 		mutex_unlock(&mgr->probe_lock);
2719 		return;
2720 	}
2721 
2722 	/*
2723 	 * Certain branch devices seem to incorrectly report an available_pbn
2724 	 * of 0 on downstream sinks, even after clearing the
2725 	 * DP_PAYLOAD_ALLOCATE_* registers in
2726 	 * drm_dp_mst_topology_mgr_set_mst(). Namely, the CableMatters USB-C
2727 	 * 2x DP hub. Sending a CLEAR_PAYLOAD_ID_TABLE message seems to make
2728 	 * things work again.
2729 	 */
2730 	if (clear_payload_id_table) {
2731 		DRM_DEBUG_KMS("Clearing payload ID table\n");
2732 		drm_dp_send_clear_payload_id_table(mgr, mstb);
2733 	}
2734 
2735 	ret = drm_dp_check_and_send_link_address(mgr, mstb);
2736 	drm_dp_mst_topology_put_mstb(mstb);
2737 
2738 	mutex_unlock(&mgr->probe_lock);
2739 	if (ret)
2740 		drm_kms_helper_hotplug_event(dev);
2741 }
2742 
drm_dp_validate_guid(struct drm_dp_mst_topology_mgr * mgr,u8 * guid)2743 static bool drm_dp_validate_guid(struct drm_dp_mst_topology_mgr *mgr,
2744 				 u8 *guid)
2745 {
2746 	u64 salt;
2747 
2748 	if (memchr_inv(guid, 0, 16))
2749 		return true;
2750 
2751 	salt = get_jiffies_64();
2752 
2753 	memcpy(&guid[0], &salt, sizeof(u64));
2754 	memcpy(&guid[8], &salt, sizeof(u64));
2755 
2756 	return false;
2757 }
2758 
build_dpcd_read(struct drm_dp_sideband_msg_tx * msg,u8 port_num,u32 offset,u8 num_bytes)2759 static void build_dpcd_read(struct drm_dp_sideband_msg_tx *msg,
2760 			    u8 port_num, u32 offset, u8 num_bytes)
2761 {
2762 	struct drm_dp_sideband_msg_req_body req;
2763 
2764 	req.req_type = DP_REMOTE_DPCD_READ;
2765 	req.u.dpcd_read.port_number = port_num;
2766 	req.u.dpcd_read.dpcd_address = offset;
2767 	req.u.dpcd_read.num_bytes = num_bytes;
2768 	drm_dp_encode_sideband_req(&req, msg);
2769 }
2770 
drm_dp_send_sideband_msg(struct drm_dp_mst_topology_mgr * mgr,bool up,u8 * msg,int len)2771 static int drm_dp_send_sideband_msg(struct drm_dp_mst_topology_mgr *mgr,
2772 				    bool up, u8 *msg, int len)
2773 {
2774 	int ret;
2775 	int regbase = up ? DP_SIDEBAND_MSG_UP_REP_BASE : DP_SIDEBAND_MSG_DOWN_REQ_BASE;
2776 	int tosend, total, offset;
2777 	int retries = 0;
2778 
2779 retry:
2780 	total = len;
2781 	offset = 0;
2782 	do {
2783 		tosend = min3(mgr->max_dpcd_transaction_bytes, 16, total);
2784 
2785 		ret = drm_dp_dpcd_write(mgr->aux, regbase + offset,
2786 					&msg[offset],
2787 					tosend);
2788 		if (ret != tosend) {
2789 			if (ret == -EIO && retries < 5) {
2790 				retries++;
2791 				goto retry;
2792 			}
2793 			DRM_DEBUG_KMS("failed to dpcd write %d %d\n", tosend, ret);
2794 
2795 			return -EIO;
2796 		}
2797 		offset += tosend;
2798 		total -= tosend;
2799 	} while (total > 0);
2800 	return 0;
2801 }
2802 
set_hdr_from_dst_qlock(struct drm_dp_sideband_msg_hdr * hdr,struct drm_dp_sideband_msg_tx * txmsg)2803 static int set_hdr_from_dst_qlock(struct drm_dp_sideband_msg_hdr *hdr,
2804 				  struct drm_dp_sideband_msg_tx *txmsg)
2805 {
2806 	struct drm_dp_mst_branch *mstb = txmsg->dst;
2807 	u8 req_type;
2808 
2809 	req_type = txmsg->msg[0] & 0x7f;
2810 	if (req_type == DP_CONNECTION_STATUS_NOTIFY ||
2811 		req_type == DP_RESOURCE_STATUS_NOTIFY ||
2812 		req_type == DP_CLEAR_PAYLOAD_ID_TABLE)
2813 		hdr->broadcast = 1;
2814 	else
2815 		hdr->broadcast = 0;
2816 	hdr->path_msg = txmsg->path_msg;
2817 	if (hdr->broadcast) {
2818 		hdr->lct = 1;
2819 		hdr->lcr = 6;
2820 	} else {
2821 		hdr->lct = mstb->lct;
2822 		hdr->lcr = mstb->lct - 1;
2823 	}
2824 
2825 	memcpy(hdr->rad, mstb->rad, hdr->lct / 2);
2826 
2827 	return 0;
2828 }
2829 /*
2830  * process a single block of the next message in the sideband queue
2831  */
process_single_tx_qlock(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_sideband_msg_tx * txmsg,bool up)2832 static int process_single_tx_qlock(struct drm_dp_mst_topology_mgr *mgr,
2833 				   struct drm_dp_sideband_msg_tx *txmsg,
2834 				   bool up)
2835 {
2836 	u8 chunk[48];
2837 	struct drm_dp_sideband_msg_hdr hdr;
2838 	int len, space, idx, tosend;
2839 	int ret;
2840 
2841 	if (txmsg->state == DRM_DP_SIDEBAND_TX_SENT)
2842 		return 0;
2843 
2844 	memset(&hdr, 0, sizeof(struct drm_dp_sideband_msg_hdr));
2845 
2846 	if (txmsg->state == DRM_DP_SIDEBAND_TX_QUEUED)
2847 		txmsg->state = DRM_DP_SIDEBAND_TX_START_SEND;
2848 
2849 	/* make hdr from dst mst */
2850 	ret = set_hdr_from_dst_qlock(&hdr, txmsg);
2851 	if (ret < 0)
2852 		return ret;
2853 
2854 	/* amount left to send in this message */
2855 	len = txmsg->cur_len - txmsg->cur_offset;
2856 
2857 	/* 48 - sideband msg size - 1 byte for data CRC, x header bytes */
2858 	space = 48 - 1 - drm_dp_calc_sb_hdr_size(&hdr);
2859 
2860 	tosend = min(len, space);
2861 	if (len == txmsg->cur_len)
2862 		hdr.somt = 1;
2863 	if (space >= len)
2864 		hdr.eomt = 1;
2865 
2866 
2867 	hdr.msg_len = tosend + 1;
2868 	drm_dp_encode_sideband_msg_hdr(&hdr, chunk, &idx);
2869 	memcpy(&chunk[idx], &txmsg->msg[txmsg->cur_offset], tosend);
2870 	/* add crc at end */
2871 	drm_dp_crc_sideband_chunk_req(&chunk[idx], tosend);
2872 	idx += tosend + 1;
2873 
2874 	ret = drm_dp_send_sideband_msg(mgr, up, chunk, idx);
2875 	if (ret) {
2876 		if (drm_debug_enabled(DRM_UT_DP)) {
2877 			struct drm_printer p = drm_debug_printer(DBG_PREFIX);
2878 
2879 			drm_printf(&p, "sideband msg failed to send\n");
2880 			drm_dp_mst_dump_sideband_msg_tx(&p, txmsg);
2881 		}
2882 		return ret;
2883 	}
2884 
2885 	txmsg->cur_offset += tosend;
2886 	if (txmsg->cur_offset == txmsg->cur_len) {
2887 		txmsg->state = DRM_DP_SIDEBAND_TX_SENT;
2888 		return 1;
2889 	}
2890 	return 0;
2891 }
2892 
process_single_down_tx_qlock(struct drm_dp_mst_topology_mgr * mgr)2893 static void process_single_down_tx_qlock(struct drm_dp_mst_topology_mgr *mgr)
2894 {
2895 	struct drm_dp_sideband_msg_tx *txmsg;
2896 	int ret;
2897 
2898 	WARN_ON(!mutex_is_locked(&mgr->qlock));
2899 
2900 	/* construct a chunk from the first msg in the tx_msg queue */
2901 	if (list_empty(&mgr->tx_msg_downq))
2902 		return;
2903 
2904 	txmsg = list_first_entry(&mgr->tx_msg_downq,
2905 				 struct drm_dp_sideband_msg_tx, next);
2906 	ret = process_single_tx_qlock(mgr, txmsg, false);
2907 	if (ret < 0) {
2908 		DRM_DEBUG_KMS("failed to send msg in q %d\n", ret);
2909 		list_del(&txmsg->next);
2910 		txmsg->state = DRM_DP_SIDEBAND_TX_TIMEOUT;
2911 		wake_up_all(&mgr->tx_waitq);
2912 	}
2913 }
2914 
drm_dp_queue_down_tx(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_sideband_msg_tx * txmsg)2915 static void drm_dp_queue_down_tx(struct drm_dp_mst_topology_mgr *mgr,
2916 				 struct drm_dp_sideband_msg_tx *txmsg)
2917 {
2918 	mutex_lock(&mgr->qlock);
2919 	list_add_tail(&txmsg->next, &mgr->tx_msg_downq);
2920 
2921 	if (drm_debug_enabled(DRM_UT_DP)) {
2922 		struct drm_printer p = drm_debug_printer(DBG_PREFIX);
2923 
2924 		drm_dp_mst_dump_sideband_msg_tx(&p, txmsg);
2925 	}
2926 
2927 	if (list_is_singular(&mgr->tx_msg_downq))
2928 		process_single_down_tx_qlock(mgr);
2929 	mutex_unlock(&mgr->qlock);
2930 }
2931 
2932 static void
drm_dp_dump_link_address(struct drm_dp_link_address_ack_reply * reply)2933 drm_dp_dump_link_address(struct drm_dp_link_address_ack_reply *reply)
2934 {
2935 	struct drm_dp_link_addr_reply_port *port_reply;
2936 	int i;
2937 
2938 	for (i = 0; i < reply->nports; i++) {
2939 		port_reply = &reply->ports[i];
2940 		DRM_DEBUG_KMS("port %d: input %d, pdt: %d, pn: %d, dpcd_rev: %02x, mcs: %d, ddps: %d, ldps %d, sdp %d/%d\n",
2941 			      i,
2942 			      port_reply->input_port,
2943 			      port_reply->peer_device_type,
2944 			      port_reply->port_number,
2945 			      port_reply->dpcd_revision,
2946 			      port_reply->mcs,
2947 			      port_reply->ddps,
2948 			      port_reply->legacy_device_plug_status,
2949 			      port_reply->num_sdp_streams,
2950 			      port_reply->num_sdp_stream_sinks);
2951 	}
2952 }
2953 
drm_dp_send_link_address(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_branch * mstb)2954 static int drm_dp_send_link_address(struct drm_dp_mst_topology_mgr *mgr,
2955 				     struct drm_dp_mst_branch *mstb)
2956 {
2957 	struct drm_dp_sideband_msg_tx *txmsg;
2958 	struct drm_dp_link_address_ack_reply *reply;
2959 	struct drm_dp_mst_port *port, *tmp;
2960 	int i, ret, port_mask = 0;
2961 	bool changed = false;
2962 
2963 	txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
2964 	if (!txmsg)
2965 		return -ENOMEM;
2966 
2967 	txmsg->dst = mstb;
2968 	build_link_address(txmsg);
2969 
2970 	mstb->link_address_sent = true;
2971 	drm_dp_queue_down_tx(mgr, txmsg);
2972 
2973 	/* FIXME: Actually do some real error handling here */
2974 	ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
2975 	if (ret <= 0) {
2976 		DRM_ERROR("Sending link address failed with %d\n", ret);
2977 		goto out;
2978 	}
2979 	if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK) {
2980 		DRM_ERROR("link address NAK received\n");
2981 		ret = -EIO;
2982 		goto out;
2983 	}
2984 
2985 	reply = &txmsg->reply.u.link_addr;
2986 	DRM_DEBUG_KMS("link address reply: %d\n", reply->nports);
2987 	drm_dp_dump_link_address(reply);
2988 
2989 	ret = drm_dp_check_mstb_guid(mstb, reply->guid);
2990 	if (ret) {
2991 		char buf[64];
2992 
2993 		drm_dp_mst_rad_to_str(mstb->rad, mstb->lct, buf, sizeof(buf));
2994 		DRM_ERROR("GUID check on %s failed: %d\n",
2995 			  buf, ret);
2996 		goto out;
2997 	}
2998 
2999 	for (i = 0; i < reply->nports; i++) {
3000 		port_mask |= BIT(reply->ports[i].port_number);
3001 		ret = drm_dp_mst_handle_link_address_port(mstb, mgr->dev,
3002 							  &reply->ports[i]);
3003 		if (ret == 1)
3004 			changed = true;
3005 		else if (ret < 0)
3006 			goto out;
3007 	}
3008 
3009 	/* Prune any ports that are currently a part of mstb in our in-memory
3010 	 * topology, but were not seen in this link address. Usually this
3011 	 * means that they were removed while the topology was out of sync,
3012 	 * e.g. during suspend/resume
3013 	 */
3014 	mutex_lock(&mgr->lock);
3015 	list_for_each_entry_safe(port, tmp, &mstb->ports, next) {
3016 		if (port_mask & BIT(port->port_num))
3017 			continue;
3018 
3019 		DRM_DEBUG_KMS("port %d was not in link address, removing\n",
3020 			      port->port_num);
3021 		list_del(&port->next);
3022 		drm_dp_mst_topology_put_port(port);
3023 		changed = true;
3024 	}
3025 	mutex_unlock(&mgr->lock);
3026 
3027 out:
3028 	if (ret <= 0)
3029 		mstb->link_address_sent = false;
3030 	kfree(txmsg);
3031 	return ret < 0 ? ret : changed;
3032 }
3033 
3034 static void
drm_dp_send_clear_payload_id_table(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_branch * mstb)3035 drm_dp_send_clear_payload_id_table(struct drm_dp_mst_topology_mgr *mgr,
3036 				   struct drm_dp_mst_branch *mstb)
3037 {
3038 	struct drm_dp_sideband_msg_tx *txmsg;
3039 	int ret;
3040 
3041 	txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
3042 	if (!txmsg)
3043 		return;
3044 
3045 	txmsg->dst = mstb;
3046 	build_clear_payload_id_table(txmsg);
3047 
3048 	drm_dp_queue_down_tx(mgr, txmsg);
3049 
3050 	ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
3051 	if (ret > 0 && txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK)
3052 		DRM_DEBUG_KMS("clear payload table id nak received\n");
3053 
3054 	kfree(txmsg);
3055 }
3056 
3057 static int
drm_dp_send_enum_path_resources(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_branch * mstb,struct drm_dp_mst_port * port)3058 drm_dp_send_enum_path_resources(struct drm_dp_mst_topology_mgr *mgr,
3059 				struct drm_dp_mst_branch *mstb,
3060 				struct drm_dp_mst_port *port)
3061 {
3062 	struct drm_dp_enum_path_resources_ack_reply *path_res;
3063 	struct drm_dp_sideband_msg_tx *txmsg;
3064 	int ret;
3065 
3066 	txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
3067 	if (!txmsg)
3068 		return -ENOMEM;
3069 
3070 	txmsg->dst = mstb;
3071 	build_enum_path_resources(txmsg, port->port_num);
3072 
3073 	drm_dp_queue_down_tx(mgr, txmsg);
3074 
3075 	ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
3076 	if (ret > 0) {
3077 		ret = 0;
3078 		path_res = &txmsg->reply.u.path_resources;
3079 
3080 		if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK) {
3081 			DRM_DEBUG_KMS("enum path resources nak received\n");
3082 		} else {
3083 			if (port->port_num != path_res->port_number)
3084 				DRM_ERROR("got incorrect port in response\n");
3085 
3086 			DRM_DEBUG_KMS("enum path resources %d: %d %d\n",
3087 				      path_res->port_number,
3088 				      path_res->full_payload_bw_number,
3089 				      path_res->avail_payload_bw_number);
3090 
3091 			/*
3092 			 * If something changed, make sure we send a
3093 			 * hotplug
3094 			 */
3095 			if (port->full_pbn != path_res->full_payload_bw_number ||
3096 			    port->fec_capable != path_res->fec_capable)
3097 				ret = 1;
3098 
3099 			port->full_pbn = path_res->full_payload_bw_number;
3100 			port->fec_capable = path_res->fec_capable;
3101 		}
3102 	}
3103 
3104 	kfree(txmsg);
3105 	return ret;
3106 }
3107 
drm_dp_get_last_connected_port_to_mstb(struct drm_dp_mst_branch * mstb)3108 static struct drm_dp_mst_port *drm_dp_get_last_connected_port_to_mstb(struct drm_dp_mst_branch *mstb)
3109 {
3110 	if (!mstb->port_parent)
3111 		return NULL;
3112 
3113 	if (mstb->port_parent->mstb != mstb)
3114 		return mstb->port_parent;
3115 
3116 	return drm_dp_get_last_connected_port_to_mstb(mstb->port_parent->parent);
3117 }
3118 
3119 /*
3120  * Searches upwards in the topology starting from mstb to try to find the
3121  * closest available parent of mstb that's still connected to the rest of the
3122  * topology. This can be used in order to perform operations like releasing
3123  * payloads, where the branch device which owned the payload may no longer be
3124  * around and thus would require that the payload on the last living relative
3125  * be freed instead.
3126  */
3127 static struct drm_dp_mst_branch *
drm_dp_get_last_connected_port_and_mstb(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_branch * mstb,int * port_num)3128 drm_dp_get_last_connected_port_and_mstb(struct drm_dp_mst_topology_mgr *mgr,
3129 					struct drm_dp_mst_branch *mstb,
3130 					int *port_num)
3131 {
3132 	struct drm_dp_mst_branch *rmstb = NULL;
3133 	struct drm_dp_mst_port *found_port;
3134 
3135 	mutex_lock(&mgr->lock);
3136 	if (!mgr->mst_primary)
3137 		goto out;
3138 
3139 	do {
3140 		found_port = drm_dp_get_last_connected_port_to_mstb(mstb);
3141 		if (!found_port)
3142 			break;
3143 
3144 		if (drm_dp_mst_topology_try_get_mstb(found_port->parent)) {
3145 			rmstb = found_port->parent;
3146 			*port_num = found_port->port_num;
3147 		} else {
3148 			/* Search again, starting from this parent */
3149 			mstb = found_port->parent;
3150 		}
3151 	} while (!rmstb);
3152 out:
3153 	mutex_unlock(&mgr->lock);
3154 	return rmstb;
3155 }
3156 
drm_dp_payload_send_msg(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port,int id,int pbn)3157 static int drm_dp_payload_send_msg(struct drm_dp_mst_topology_mgr *mgr,
3158 				   struct drm_dp_mst_port *port,
3159 				   int id,
3160 				   int pbn)
3161 {
3162 	struct drm_dp_sideband_msg_tx *txmsg;
3163 	struct drm_dp_mst_branch *mstb;
3164 	int ret, port_num;
3165 	u8 sinks[DRM_DP_MAX_SDP_STREAMS];
3166 	int i;
3167 
3168 	port_num = port->port_num;
3169 	mstb = drm_dp_mst_topology_get_mstb_validated(mgr, port->parent);
3170 	if (!mstb) {
3171 		mstb = drm_dp_get_last_connected_port_and_mstb(mgr,
3172 							       port->parent,
3173 							       &port_num);
3174 
3175 		if (!mstb)
3176 			return -EINVAL;
3177 	}
3178 
3179 	txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
3180 	if (!txmsg) {
3181 		ret = -ENOMEM;
3182 		goto fail_put;
3183 	}
3184 
3185 	for (i = 0; i < port->num_sdp_streams; i++)
3186 		sinks[i] = i;
3187 
3188 	txmsg->dst = mstb;
3189 	build_allocate_payload(txmsg, port_num,
3190 			       id,
3191 			       pbn, port->num_sdp_streams, sinks);
3192 
3193 	drm_dp_queue_down_tx(mgr, txmsg);
3194 
3195 	/*
3196 	 * FIXME: there is a small chance that between getting the last
3197 	 * connected mstb and sending the payload message, the last connected
3198 	 * mstb could also be removed from the topology. In the future, this
3199 	 * needs to be fixed by restarting the
3200 	 * drm_dp_get_last_connected_port_and_mstb() search in the event of a
3201 	 * timeout if the topology is still connected to the system.
3202 	 */
3203 	ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
3204 	if (ret > 0) {
3205 		if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK)
3206 			ret = -EINVAL;
3207 		else
3208 			ret = 0;
3209 	}
3210 	kfree(txmsg);
3211 fail_put:
3212 	drm_dp_mst_topology_put_mstb(mstb);
3213 	return ret;
3214 }
3215 
drm_dp_send_power_updown_phy(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port,bool power_up)3216 int drm_dp_send_power_updown_phy(struct drm_dp_mst_topology_mgr *mgr,
3217 				 struct drm_dp_mst_port *port, bool power_up)
3218 {
3219 	struct drm_dp_sideband_msg_tx *txmsg;
3220 	int ret;
3221 
3222 	port = drm_dp_mst_topology_get_port_validated(mgr, port);
3223 	if (!port)
3224 		return -EINVAL;
3225 
3226 	txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
3227 	if (!txmsg) {
3228 		drm_dp_mst_topology_put_port(port);
3229 		return -ENOMEM;
3230 	}
3231 
3232 	txmsg->dst = port->parent;
3233 	build_power_updown_phy(txmsg, port->port_num, power_up);
3234 	drm_dp_queue_down_tx(mgr, txmsg);
3235 
3236 	ret = drm_dp_mst_wait_tx_reply(port->parent, txmsg);
3237 	if (ret > 0) {
3238 		if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK)
3239 			ret = -EINVAL;
3240 		else
3241 			ret = 0;
3242 	}
3243 	kfree(txmsg);
3244 	drm_dp_mst_topology_put_port(port);
3245 
3246 	return ret;
3247 }
3248 EXPORT_SYMBOL(drm_dp_send_power_updown_phy);
3249 
drm_dp_send_query_stream_enc_status(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port,struct drm_dp_query_stream_enc_status_ack_reply * status)3250 int drm_dp_send_query_stream_enc_status(struct drm_dp_mst_topology_mgr *mgr,
3251 		struct drm_dp_mst_port *port,
3252 		struct drm_dp_query_stream_enc_status_ack_reply *status)
3253 {
3254 	struct drm_dp_sideband_msg_tx *txmsg;
3255 	u8 nonce[7];
3256 	int len, ret;
3257 
3258 	txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
3259 	if (!txmsg)
3260 		return -ENOMEM;
3261 
3262 	port = drm_dp_mst_topology_get_port_validated(mgr, port);
3263 	if (!port) {
3264 		ret = -EINVAL;
3265 		goto out_get_port;
3266 	}
3267 
3268 	get_random_bytes(nonce, sizeof(nonce));
3269 
3270 	/*
3271 	 * "Source device targets the QUERY_STREAM_ENCRYPTION_STATUS message
3272 	 *  transaction at the MST Branch device directly connected to the
3273 	 *  Source"
3274 	 */
3275 	txmsg->dst = mgr->mst_primary;
3276 
3277 	len = build_query_stream_enc_status(txmsg, port->vcpi.vcpi, nonce);
3278 
3279 	drm_dp_queue_down_tx(mgr, txmsg);
3280 
3281 	ret = drm_dp_mst_wait_tx_reply(mgr->mst_primary, txmsg);
3282 	if (ret < 0) {
3283 		goto out;
3284 	} else if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK) {
3285 		drm_dbg_kms(mgr->dev, "query encryption status nak received\n");
3286 		ret = -ENXIO;
3287 		goto out;
3288 	}
3289 
3290 	ret = 0;
3291 	memcpy(status, &txmsg->reply.u.enc_status, sizeof(*status));
3292 
3293 out:
3294 	drm_dp_mst_topology_put_port(port);
3295 out_get_port:
3296 	kfree(txmsg);
3297 	return ret;
3298 }
3299 EXPORT_SYMBOL(drm_dp_send_query_stream_enc_status);
3300 
drm_dp_create_payload_step1(struct drm_dp_mst_topology_mgr * mgr,int id,struct drm_dp_payload * payload)3301 static int drm_dp_create_payload_step1(struct drm_dp_mst_topology_mgr *mgr,
3302 				       int id,
3303 				       struct drm_dp_payload *payload)
3304 {
3305 	int ret;
3306 
3307 	ret = drm_dp_dpcd_write_payload(mgr, id, payload);
3308 	if (ret < 0) {
3309 		payload->payload_state = 0;
3310 		return ret;
3311 	}
3312 	payload->payload_state = DP_PAYLOAD_LOCAL;
3313 	return 0;
3314 }
3315 
drm_dp_create_payload_step2(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port,int id,struct drm_dp_payload * payload)3316 static int drm_dp_create_payload_step2(struct drm_dp_mst_topology_mgr *mgr,
3317 				       struct drm_dp_mst_port *port,
3318 				       int id,
3319 				       struct drm_dp_payload *payload)
3320 {
3321 	int ret;
3322 
3323 	ret = drm_dp_payload_send_msg(mgr, port, id, port->vcpi.pbn);
3324 	if (ret < 0)
3325 		return ret;
3326 	payload->payload_state = DP_PAYLOAD_REMOTE;
3327 	return ret;
3328 }
3329 
drm_dp_destroy_payload_step1(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port,int id,struct drm_dp_payload * payload)3330 static int drm_dp_destroy_payload_step1(struct drm_dp_mst_topology_mgr *mgr,
3331 					struct drm_dp_mst_port *port,
3332 					int id,
3333 					struct drm_dp_payload *payload)
3334 {
3335 	DRM_DEBUG_KMS("\n");
3336 	/* it's okay for these to fail */
3337 	if (port) {
3338 		drm_dp_payload_send_msg(mgr, port, id, 0);
3339 	}
3340 
3341 	drm_dp_dpcd_write_payload(mgr, id, payload);
3342 	payload->payload_state = DP_PAYLOAD_DELETE_LOCAL;
3343 	return 0;
3344 }
3345 
drm_dp_destroy_payload_step2(struct drm_dp_mst_topology_mgr * mgr,int id,struct drm_dp_payload * payload)3346 static int drm_dp_destroy_payload_step2(struct drm_dp_mst_topology_mgr *mgr,
3347 					int id,
3348 					struct drm_dp_payload *payload)
3349 {
3350 	payload->payload_state = 0;
3351 	return 0;
3352 }
3353 
3354 /**
3355  * drm_dp_update_payload_part1() - Execute payload update part 1
3356  * @mgr: manager to use.
3357  *
3358  * This iterates over all proposed virtual channels, and tries to
3359  * allocate space in the link for them. For 0->slots transitions,
3360  * this step just writes the VCPI to the MST device. For slots->0
3361  * transitions, this writes the updated VCPIs and removes the
3362  * remote VC payloads.
3363  *
3364  * after calling this the driver should generate ACT and payload
3365  * packets.
3366  */
drm_dp_update_payload_part1(struct drm_dp_mst_topology_mgr * mgr)3367 int drm_dp_update_payload_part1(struct drm_dp_mst_topology_mgr *mgr)
3368 {
3369 	struct drm_dp_payload req_payload;
3370 	struct drm_dp_mst_port *port;
3371 	int i, j;
3372 	int cur_slots = 1;
3373 	bool skip;
3374 
3375 	mutex_lock(&mgr->payload_lock);
3376 	for (i = 0; i < mgr->max_payloads; i++) {
3377 		struct drm_dp_vcpi *vcpi = mgr->proposed_vcpis[i];
3378 		struct drm_dp_payload *payload = &mgr->payloads[i];
3379 		bool put_port = false;
3380 
3381 		/* solve the current payloads - compare to the hw ones
3382 		   - update the hw view */
3383 		req_payload.start_slot = cur_slots;
3384 		if (vcpi) {
3385 			port = container_of(vcpi, struct drm_dp_mst_port,
3386 					    vcpi);
3387 
3388 			mutex_lock(&mgr->lock);
3389 			skip = !drm_dp_mst_port_downstream_of_branch(port, mgr->mst_primary);
3390 			mutex_unlock(&mgr->lock);
3391 
3392 			if (skip) {
3393 				drm_dbg_kms(mgr->dev,
3394 					    "Virtual channel %d is not in current topology\n",
3395 					    i);
3396 				continue;
3397 			}
3398 			/* Validated ports don't matter if we're releasing
3399 			 * VCPI
3400 			 */
3401 			if (vcpi->num_slots) {
3402 				port = drm_dp_mst_topology_get_port_validated(
3403 				    mgr, port);
3404 				if (!port) {
3405 					if (vcpi->num_slots == payload->num_slots) {
3406 						cur_slots += vcpi->num_slots;
3407 						payload->start_slot = req_payload.start_slot;
3408 						continue;
3409 					} else {
3410 						drm_dbg_kms(mgr->dev,
3411 							    "Fail:set payload to invalid sink");
3412 						mutex_unlock(&mgr->payload_lock);
3413 						return -EINVAL;
3414 					}
3415 				}
3416 				put_port = true;
3417 			}
3418 
3419 			req_payload.num_slots = vcpi->num_slots;
3420 			req_payload.vcpi = vcpi->vcpi;
3421 		} else {
3422 			port = NULL;
3423 			req_payload.num_slots = 0;
3424 		}
3425 
3426 		payload->start_slot = req_payload.start_slot;
3427 		/* work out what is required to happen with this payload */
3428 		if (payload->num_slots != req_payload.num_slots) {
3429 
3430 			/* need to push an update for this payload */
3431 			if (req_payload.num_slots) {
3432 				drm_dp_create_payload_step1(mgr, vcpi->vcpi,
3433 							    &req_payload);
3434 				payload->num_slots = req_payload.num_slots;
3435 				payload->vcpi = req_payload.vcpi;
3436 
3437 			} else if (payload->num_slots) {
3438 				payload->num_slots = 0;
3439 				drm_dp_destroy_payload_step1(mgr, port,
3440 							     payload->vcpi,
3441 							     payload);
3442 				req_payload.payload_state =
3443 					payload->payload_state;
3444 				payload->start_slot = 0;
3445 			}
3446 			payload->payload_state = req_payload.payload_state;
3447 		}
3448 		cur_slots += req_payload.num_slots;
3449 
3450 		if (put_port)
3451 			drm_dp_mst_topology_put_port(port);
3452 	}
3453 
3454 	for (i = 0; i < mgr->max_payloads; /* do nothing */) {
3455 		if (mgr->payloads[i].payload_state != DP_PAYLOAD_DELETE_LOCAL) {
3456 			i++;
3457 			continue;
3458 		}
3459 
3460 		DRM_DEBUG_KMS("removing payload %d\n", i);
3461 		for (j = i; j < mgr->max_payloads - 1; j++) {
3462 			mgr->payloads[j] = mgr->payloads[j + 1];
3463 			mgr->proposed_vcpis[j] = mgr->proposed_vcpis[j + 1];
3464 
3465 			if (mgr->proposed_vcpis[j] &&
3466 			    mgr->proposed_vcpis[j]->num_slots) {
3467 				set_bit(j + 1, &mgr->payload_mask);
3468 			} else {
3469 				clear_bit(j + 1, &mgr->payload_mask);
3470 			}
3471 		}
3472 
3473 		memset(&mgr->payloads[mgr->max_payloads - 1], 0,
3474 		       sizeof(struct drm_dp_payload));
3475 		mgr->proposed_vcpis[mgr->max_payloads - 1] = NULL;
3476 		clear_bit(mgr->max_payloads, &mgr->payload_mask);
3477 	}
3478 	mutex_unlock(&mgr->payload_lock);
3479 
3480 	return 0;
3481 }
3482 EXPORT_SYMBOL(drm_dp_update_payload_part1);
3483 
3484 /**
3485  * drm_dp_update_payload_part2() - Execute payload update part 2
3486  * @mgr: manager to use.
3487  *
3488  * This iterates over all proposed virtual channels, and tries to
3489  * allocate space in the link for them. For 0->slots transitions,
3490  * this step writes the remote VC payload commands. For slots->0
3491  * this just resets some internal state.
3492  */
drm_dp_update_payload_part2(struct drm_dp_mst_topology_mgr * mgr)3493 int drm_dp_update_payload_part2(struct drm_dp_mst_topology_mgr *mgr)
3494 {
3495 	struct drm_dp_mst_port *port;
3496 	int i;
3497 	int ret = 0;
3498 	bool skip;
3499 
3500 	mutex_lock(&mgr->payload_lock);
3501 	for (i = 0; i < mgr->max_payloads; i++) {
3502 
3503 		if (!mgr->proposed_vcpis[i])
3504 			continue;
3505 
3506 		port = container_of(mgr->proposed_vcpis[i], struct drm_dp_mst_port, vcpi);
3507 
3508 		mutex_lock(&mgr->lock);
3509 		skip = !drm_dp_mst_port_downstream_of_branch(port, mgr->mst_primary);
3510 		mutex_unlock(&mgr->lock);
3511 
3512 		if (skip)
3513 			continue;
3514 
3515 		DRM_DEBUG_KMS("payload %d %d\n", i, mgr->payloads[i].payload_state);
3516 		if (mgr->payloads[i].payload_state == DP_PAYLOAD_LOCAL) {
3517 			ret = drm_dp_create_payload_step2(mgr, port, mgr->proposed_vcpis[i]->vcpi, &mgr->payloads[i]);
3518 		} else if (mgr->payloads[i].payload_state == DP_PAYLOAD_DELETE_LOCAL) {
3519 			ret = drm_dp_destroy_payload_step2(mgr, mgr->proposed_vcpis[i]->vcpi, &mgr->payloads[i]);
3520 		}
3521 		if (ret) {
3522 			mutex_unlock(&mgr->payload_lock);
3523 			return ret;
3524 		}
3525 	}
3526 	mutex_unlock(&mgr->payload_lock);
3527 	return 0;
3528 }
3529 EXPORT_SYMBOL(drm_dp_update_payload_part2);
3530 
drm_dp_send_dpcd_read(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port,int offset,int size,u8 * bytes)3531 static int drm_dp_send_dpcd_read(struct drm_dp_mst_topology_mgr *mgr,
3532 				 struct drm_dp_mst_port *port,
3533 				 int offset, int size, u8 *bytes)
3534 {
3535 	int ret = 0;
3536 	struct drm_dp_sideband_msg_tx *txmsg;
3537 	struct drm_dp_mst_branch *mstb;
3538 
3539 	mstb = drm_dp_mst_topology_get_mstb_validated(mgr, port->parent);
3540 	if (!mstb)
3541 		return -EINVAL;
3542 
3543 	txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
3544 	if (!txmsg) {
3545 		ret = -ENOMEM;
3546 		goto fail_put;
3547 	}
3548 
3549 	build_dpcd_read(txmsg, port->port_num, offset, size);
3550 	txmsg->dst = port->parent;
3551 
3552 	drm_dp_queue_down_tx(mgr, txmsg);
3553 
3554 	ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
3555 	if (ret < 0)
3556 		goto fail_free;
3557 
3558 	/* DPCD read should never be NACKed */
3559 	if (txmsg->reply.reply_type == 1) {
3560 		DRM_ERROR("mstb %p port %d: DPCD read on addr 0x%x for %d bytes NAKed\n",
3561 			  mstb, port->port_num, offset, size);
3562 		ret = -EIO;
3563 		goto fail_free;
3564 	}
3565 
3566 	if (txmsg->reply.u.remote_dpcd_read_ack.num_bytes != size) {
3567 		ret = -EPROTO;
3568 		goto fail_free;
3569 	}
3570 
3571 	ret = min_t(size_t, txmsg->reply.u.remote_dpcd_read_ack.num_bytes,
3572 		    size);
3573 	memcpy(bytes, txmsg->reply.u.remote_dpcd_read_ack.bytes, ret);
3574 
3575 fail_free:
3576 	kfree(txmsg);
3577 fail_put:
3578 	drm_dp_mst_topology_put_mstb(mstb);
3579 
3580 	return ret;
3581 }
3582 
drm_dp_send_dpcd_write(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port,int offset,int size,u8 * bytes)3583 static int drm_dp_send_dpcd_write(struct drm_dp_mst_topology_mgr *mgr,
3584 				  struct drm_dp_mst_port *port,
3585 				  int offset, int size, u8 *bytes)
3586 {
3587 	int ret;
3588 	struct drm_dp_sideband_msg_tx *txmsg;
3589 	struct drm_dp_mst_branch *mstb;
3590 
3591 	mstb = drm_dp_mst_topology_get_mstb_validated(mgr, port->parent);
3592 	if (!mstb)
3593 		return -EINVAL;
3594 
3595 	txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
3596 	if (!txmsg) {
3597 		ret = -ENOMEM;
3598 		goto fail_put;
3599 	}
3600 
3601 	build_dpcd_write(txmsg, port->port_num, offset, size, bytes);
3602 	txmsg->dst = mstb;
3603 
3604 	drm_dp_queue_down_tx(mgr, txmsg);
3605 
3606 	ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
3607 	if (ret > 0) {
3608 		if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK)
3609 			ret = -EIO;
3610 		else
3611 			ret = size;
3612 	}
3613 
3614 	kfree(txmsg);
3615 fail_put:
3616 	drm_dp_mst_topology_put_mstb(mstb);
3617 	return ret;
3618 }
3619 
drm_dp_encode_up_ack_reply(struct drm_dp_sideband_msg_tx * msg,u8 req_type)3620 static int drm_dp_encode_up_ack_reply(struct drm_dp_sideband_msg_tx *msg, u8 req_type)
3621 {
3622 	struct drm_dp_sideband_msg_reply_body reply;
3623 
3624 	reply.reply_type = DP_SIDEBAND_REPLY_ACK;
3625 	reply.req_type = req_type;
3626 	drm_dp_encode_sideband_reply(&reply, msg);
3627 	return 0;
3628 }
3629 
drm_dp_send_up_ack_reply(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_branch * mstb,int req_type,bool broadcast)3630 static int drm_dp_send_up_ack_reply(struct drm_dp_mst_topology_mgr *mgr,
3631 				    struct drm_dp_mst_branch *mstb,
3632 				    int req_type, bool broadcast)
3633 {
3634 	struct drm_dp_sideband_msg_tx *txmsg;
3635 
3636 	txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
3637 	if (!txmsg)
3638 		return -ENOMEM;
3639 
3640 	txmsg->dst = mstb;
3641 	drm_dp_encode_up_ack_reply(txmsg, req_type);
3642 
3643 	mutex_lock(&mgr->qlock);
3644 	/* construct a chunk from the first msg in the tx_msg queue */
3645 	process_single_tx_qlock(mgr, txmsg, true);
3646 	mutex_unlock(&mgr->qlock);
3647 
3648 	kfree(txmsg);
3649 	return 0;
3650 }
3651 
3652 /**
3653  * drm_dp_get_vc_payload_bw - get the VC payload BW for an MST link
3654  * @link_rate: link rate in 10kbits/s units
3655  * @link_lane_count: lane count
3656  *
3657  * Calculate the total bandwidth of a MultiStream Transport link. The returned
3658  * value is in units of PBNs/(timeslots/1 MTP). This value can be used to
3659  * convert the number of PBNs required for a given stream to the number of
3660  * timeslots this stream requires in each MTP.
3661  */
drm_dp_get_vc_payload_bw(int link_rate,int link_lane_count)3662 int drm_dp_get_vc_payload_bw(int link_rate, int link_lane_count)
3663 {
3664 	if (link_rate == 0 || link_lane_count == 0)
3665 		DRM_DEBUG_KMS("invalid link rate/lane count: (%d / %d)\n",
3666 			      link_rate, link_lane_count);
3667 
3668 	/* See DP v2.0 2.6.4.2, VCPayload_Bandwidth_for_OneTimeSlotPer_MTP_Allocation */
3669 	return link_rate * link_lane_count / 54000;
3670 }
3671 EXPORT_SYMBOL(drm_dp_get_vc_payload_bw);
3672 
3673 /**
3674  * drm_dp_read_mst_cap() - check whether or not a sink supports MST
3675  * @aux: The DP AUX channel to use
3676  * @dpcd: A cached copy of the DPCD capabilities for this sink
3677  *
3678  * Returns: %True if the sink supports MST, %false otherwise
3679  */
drm_dp_read_mst_cap(struct drm_dp_aux * aux,const u8 dpcd[DP_RECEIVER_CAP_SIZE])3680 bool drm_dp_read_mst_cap(struct drm_dp_aux *aux,
3681 			 const u8 dpcd[DP_RECEIVER_CAP_SIZE])
3682 {
3683 	u8 mstm_cap;
3684 
3685 	if (dpcd[DP_DPCD_REV] < DP_DPCD_REV_12)
3686 		return false;
3687 
3688 	if (drm_dp_dpcd_readb(aux, DP_MSTM_CAP, &mstm_cap) != 1)
3689 		return false;
3690 
3691 	return mstm_cap & DP_MST_CAP;
3692 }
3693 EXPORT_SYMBOL(drm_dp_read_mst_cap);
3694 
3695 /**
3696  * drm_dp_mst_topology_mgr_set_mst() - Set the MST state for a topology manager
3697  * @mgr: manager to set state for
3698  * @mst_state: true to enable MST on this connector - false to disable.
3699  *
3700  * This is called by the driver when it detects an MST capable device plugged
3701  * into a DP MST capable port, or when a DP MST capable device is unplugged.
3702  */
drm_dp_mst_topology_mgr_set_mst(struct drm_dp_mst_topology_mgr * mgr,bool mst_state)3703 int drm_dp_mst_topology_mgr_set_mst(struct drm_dp_mst_topology_mgr *mgr, bool mst_state)
3704 {
3705 	int ret = 0;
3706 	struct drm_dp_mst_branch *mstb = NULL;
3707 
3708 	mutex_lock(&mgr->payload_lock);
3709 	mutex_lock(&mgr->lock);
3710 	if (mst_state == mgr->mst_state)
3711 		goto out_unlock;
3712 
3713 	mgr->mst_state = mst_state;
3714 	/* set the device into MST mode */
3715 	if (mst_state) {
3716 		struct drm_dp_payload reset_pay;
3717 
3718 		WARN_ON(mgr->mst_primary);
3719 
3720 		/* get dpcd info */
3721 		ret = drm_dp_dpcd_read(mgr->aux, DP_DPCD_REV, mgr->dpcd, DP_RECEIVER_CAP_SIZE);
3722 		if (ret != DP_RECEIVER_CAP_SIZE) {
3723 			DRM_DEBUG_KMS("failed to read DPCD\n");
3724 			goto out_unlock;
3725 		}
3726 
3727 		mgr->pbn_div = drm_dp_get_vc_payload_bw(drm_dp_bw_code_to_link_rate(mgr->dpcd[1]),
3728 							mgr->dpcd[2] & DP_MAX_LANE_COUNT_MASK);
3729 		if (mgr->pbn_div == 0) {
3730 			ret = -EINVAL;
3731 			goto out_unlock;
3732 		}
3733 
3734 		/* add initial branch device at LCT 1 */
3735 		mstb = drm_dp_add_mst_branch_device(1, NULL);
3736 		if (mstb == NULL) {
3737 			ret = -ENOMEM;
3738 			goto out_unlock;
3739 		}
3740 		mstb->mgr = mgr;
3741 
3742 		/* give this the main reference */
3743 		mgr->mst_primary = mstb;
3744 		drm_dp_mst_topology_get_mstb(mgr->mst_primary);
3745 
3746 		ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3747 					 DP_MST_EN |
3748 					 DP_UP_REQ_EN |
3749 					 DP_UPSTREAM_IS_SRC);
3750 		if (ret < 0)
3751 			goto out_unlock;
3752 
3753 		reset_pay.start_slot = 0;
3754 		reset_pay.num_slots = 0x3f;
3755 		drm_dp_dpcd_write_payload(mgr, 0, &reset_pay);
3756 
3757 		queue_work(system_long_wq, &mgr->work);
3758 
3759 		ret = 0;
3760 	} else {
3761 		/* disable MST on the device */
3762 		mstb = mgr->mst_primary;
3763 		mgr->mst_primary = NULL;
3764 		/* this can fail if the device is gone */
3765 		drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL, 0);
3766 		ret = 0;
3767 		memset(mgr->payloads, 0,
3768 		       mgr->max_payloads * sizeof(mgr->payloads[0]));
3769 		memset(mgr->proposed_vcpis, 0,
3770 		       mgr->max_payloads * sizeof(mgr->proposed_vcpis[0]));
3771 		mgr->payload_mask = 0;
3772 		set_bit(0, &mgr->payload_mask);
3773 		mgr->vcpi_mask = 0;
3774 		mgr->payload_id_table_cleared = false;
3775 
3776 		mgr->reset_rx_state = true;
3777 	}
3778 
3779 out_unlock:
3780 	mutex_unlock(&mgr->lock);
3781 	mutex_unlock(&mgr->payload_lock);
3782 	if (mstb)
3783 		drm_dp_mst_topology_put_mstb(mstb);
3784 	return ret;
3785 
3786 }
3787 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_set_mst);
3788 
3789 static void
drm_dp_mst_topology_mgr_invalidate_mstb(struct drm_dp_mst_branch * mstb)3790 drm_dp_mst_topology_mgr_invalidate_mstb(struct drm_dp_mst_branch *mstb)
3791 {
3792 	struct drm_dp_mst_port *port;
3793 
3794 	/* The link address will need to be re-sent on resume */
3795 	mstb->link_address_sent = false;
3796 
3797 	list_for_each_entry(port, &mstb->ports, next)
3798 		if (port->mstb)
3799 			drm_dp_mst_topology_mgr_invalidate_mstb(port->mstb);
3800 }
3801 
3802 /**
3803  * drm_dp_mst_topology_mgr_suspend() - suspend the MST manager
3804  * @mgr: manager to suspend
3805  *
3806  * This function tells the MST device that we can't handle UP messages
3807  * anymore. This should stop it from sending any since we are suspended.
3808  */
drm_dp_mst_topology_mgr_suspend(struct drm_dp_mst_topology_mgr * mgr)3809 void drm_dp_mst_topology_mgr_suspend(struct drm_dp_mst_topology_mgr *mgr)
3810 {
3811 	mutex_lock(&mgr->lock);
3812 	drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3813 			   DP_MST_EN | DP_UPSTREAM_IS_SRC);
3814 	mutex_unlock(&mgr->lock);
3815 	flush_work(&mgr->up_req_work);
3816 	flush_work(&mgr->work);
3817 	flush_work(&mgr->delayed_destroy_work);
3818 
3819 	mutex_lock(&mgr->lock);
3820 	if (mgr->mst_state && mgr->mst_primary)
3821 		drm_dp_mst_topology_mgr_invalidate_mstb(mgr->mst_primary);
3822 	mutex_unlock(&mgr->lock);
3823 }
3824 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_suspend);
3825 
3826 /**
3827  * drm_dp_mst_topology_mgr_resume() - resume the MST manager
3828  * @mgr: manager to resume
3829  * @sync: whether or not to perform topology reprobing synchronously
3830  *
3831  * This will fetch DPCD and see if the device is still there,
3832  * if it is, it will rewrite the MSTM control bits, and return.
3833  *
3834  * If the device fails this returns -1, and the driver should do
3835  * a full MST reprobe, in case we were undocked.
3836  *
3837  * During system resume (where it is assumed that the driver will be calling
3838  * drm_atomic_helper_resume()) this function should be called beforehand with
3839  * @sync set to true. In contexts like runtime resume where the driver is not
3840  * expected to be calling drm_atomic_helper_resume(), this function should be
3841  * called with @sync set to false in order to avoid deadlocking.
3842  *
3843  * Returns: -1 if the MST topology was removed while we were suspended, 0
3844  * otherwise.
3845  */
drm_dp_mst_topology_mgr_resume(struct drm_dp_mst_topology_mgr * mgr,bool sync)3846 int drm_dp_mst_topology_mgr_resume(struct drm_dp_mst_topology_mgr *mgr,
3847 				   bool sync)
3848 {
3849 	int ret;
3850 	u8 guid[16];
3851 
3852 	mutex_lock(&mgr->lock);
3853 	if (!mgr->mst_primary)
3854 		goto out_fail;
3855 
3856 	ret = drm_dp_dpcd_read(mgr->aux, DP_DPCD_REV, mgr->dpcd,
3857 			       DP_RECEIVER_CAP_SIZE);
3858 	if (ret != DP_RECEIVER_CAP_SIZE) {
3859 		DRM_DEBUG_KMS("dpcd read failed - undocked during suspend?\n");
3860 		goto out_fail;
3861 	}
3862 
3863 	ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3864 				 DP_MST_EN |
3865 				 DP_UP_REQ_EN |
3866 				 DP_UPSTREAM_IS_SRC);
3867 	if (ret < 0) {
3868 		DRM_DEBUG_KMS("mst write failed - undocked during suspend?\n");
3869 		goto out_fail;
3870 	}
3871 
3872 	/* Some hubs forget their guids after they resume */
3873 	ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, guid, 16);
3874 	if (ret != 16) {
3875 		DRM_DEBUG_KMS("dpcd read failed - undocked during suspend?\n");
3876 		goto out_fail;
3877 	}
3878 
3879 	ret = drm_dp_check_mstb_guid(mgr->mst_primary, guid);
3880 	if (ret) {
3881 		DRM_DEBUG_KMS("check mstb failed - undocked during suspend?\n");
3882 		goto out_fail;
3883 	}
3884 
3885 	/*
3886 	 * For the final step of resuming the topology, we need to bring the
3887 	 * state of our in-memory topology back into sync with reality. So,
3888 	 * restart the probing process as if we're probing a new hub
3889 	 */
3890 	queue_work(system_long_wq, &mgr->work);
3891 	mutex_unlock(&mgr->lock);
3892 
3893 	if (sync) {
3894 		DRM_DEBUG_KMS("Waiting for link probe work to finish re-syncing topology...\n");
3895 		flush_work(&mgr->work);
3896 	}
3897 
3898 	return 0;
3899 
3900 out_fail:
3901 	mutex_unlock(&mgr->lock);
3902 	return -1;
3903 }
3904 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_resume);
3905 
reset_msg_rx_state(struct drm_dp_sideband_msg_rx * msg)3906 static void reset_msg_rx_state(struct drm_dp_sideband_msg_rx *msg)
3907 {
3908 	memset(msg, 0, sizeof(*msg));
3909 }
3910 
3911 static bool
drm_dp_get_one_sb_msg(struct drm_dp_mst_topology_mgr * mgr,bool up,struct drm_dp_mst_branch ** mstb)3912 drm_dp_get_one_sb_msg(struct drm_dp_mst_topology_mgr *mgr, bool up,
3913 		      struct drm_dp_mst_branch **mstb)
3914 {
3915 	int len;
3916 	u8 replyblock[32];
3917 	int replylen, curreply;
3918 	int ret;
3919 	u8 hdrlen;
3920 	struct drm_dp_sideband_msg_hdr hdr;
3921 	struct drm_dp_sideband_msg_rx *msg =
3922 		up ? &mgr->up_req_recv : &mgr->down_rep_recv;
3923 	int basereg = up ? DP_SIDEBAND_MSG_UP_REQ_BASE :
3924 			   DP_SIDEBAND_MSG_DOWN_REP_BASE;
3925 
3926 	if (!up)
3927 		*mstb = NULL;
3928 
3929 	len = min(mgr->max_dpcd_transaction_bytes, 16);
3930 	ret = drm_dp_dpcd_read(mgr->aux, basereg, replyblock, len);
3931 	if (ret != len) {
3932 		DRM_DEBUG_KMS("failed to read DPCD down rep %d %d\n", len, ret);
3933 		return false;
3934 	}
3935 
3936 	ret = drm_dp_decode_sideband_msg_hdr(&hdr, replyblock, len, &hdrlen);
3937 	if (ret == false) {
3938 		print_hex_dump(KERN_DEBUG, "failed hdr", DUMP_PREFIX_NONE, 16,
3939 			       1, replyblock, len, false);
3940 		DRM_DEBUG_KMS("ERROR: failed header\n");
3941 		return false;
3942 	}
3943 
3944 	if (!up) {
3945 		/* Caller is responsible for giving back this reference */
3946 		*mstb = drm_dp_get_mst_branch_device(mgr, hdr.lct, hdr.rad);
3947 		if (!*mstb) {
3948 			DRM_DEBUG_KMS("Got MST reply from unknown device %d\n",
3949 				      hdr.lct);
3950 			return false;
3951 		}
3952 	}
3953 
3954 	if (!drm_dp_sideband_msg_set_header(msg, &hdr, hdrlen)) {
3955 		DRM_DEBUG_KMS("sideband msg set header failed %d\n",
3956 			      replyblock[0]);
3957 		return false;
3958 	}
3959 
3960 	replylen = min(msg->curchunk_len, (u8)(len - hdrlen));
3961 	ret = drm_dp_sideband_append_payload(msg, replyblock + hdrlen, replylen);
3962 	if (!ret) {
3963 		DRM_DEBUG_KMS("sideband msg build failed %d\n", replyblock[0]);
3964 		return false;
3965 	}
3966 
3967 	replylen = msg->curchunk_len + msg->curchunk_hdrlen - len;
3968 	curreply = len;
3969 	while (replylen > 0) {
3970 		len = min3(replylen, mgr->max_dpcd_transaction_bytes, 16);
3971 		ret = drm_dp_dpcd_read(mgr->aux, basereg + curreply,
3972 				    replyblock, len);
3973 		if (ret != len) {
3974 			DRM_DEBUG_KMS("failed to read a chunk (len %d, ret %d)\n",
3975 				      len, ret);
3976 			return false;
3977 		}
3978 
3979 		ret = drm_dp_sideband_append_payload(msg, replyblock, len);
3980 		if (!ret) {
3981 			DRM_DEBUG_KMS("failed to build sideband msg\n");
3982 			return false;
3983 		}
3984 
3985 		curreply += len;
3986 		replylen -= len;
3987 	}
3988 	return true;
3989 }
3990 
drm_dp_mst_handle_down_rep(struct drm_dp_mst_topology_mgr * mgr)3991 static int drm_dp_mst_handle_down_rep(struct drm_dp_mst_topology_mgr *mgr)
3992 {
3993 	struct drm_dp_sideband_msg_tx *txmsg;
3994 	struct drm_dp_mst_branch *mstb = NULL;
3995 	struct drm_dp_sideband_msg_rx *msg = &mgr->down_rep_recv;
3996 
3997 	if (!drm_dp_get_one_sb_msg(mgr, false, &mstb))
3998 		goto out_clear_reply;
3999 
4000 	/* Multi-packet message transmission, don't clear the reply */
4001 	if (!msg->have_eomt)
4002 		goto out;
4003 
4004 	/* find the message */
4005 	mutex_lock(&mgr->qlock);
4006 	txmsg = list_first_entry_or_null(&mgr->tx_msg_downq,
4007 					 struct drm_dp_sideband_msg_tx, next);
4008 	mutex_unlock(&mgr->qlock);
4009 
4010 	/* Were we actually expecting a response, and from this mstb? */
4011 	if (!txmsg || txmsg->dst != mstb) {
4012 		struct drm_dp_sideband_msg_hdr *hdr;
4013 
4014 		hdr = &msg->initial_hdr;
4015 		DRM_DEBUG_KMS("Got MST reply with no msg %p %d %d %02x %02x\n",
4016 			      mstb, hdr->seqno, hdr->lct, hdr->rad[0],
4017 			      msg->msg[0]);
4018 		goto out_clear_reply;
4019 	}
4020 
4021 	drm_dp_sideband_parse_reply(msg, &txmsg->reply);
4022 
4023 	if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK) {
4024 		DRM_DEBUG_KMS("Got NAK reply: req 0x%02x (%s), reason 0x%02x (%s), nak data 0x%02x\n",
4025 			      txmsg->reply.req_type,
4026 			      drm_dp_mst_req_type_str(txmsg->reply.req_type),
4027 			      txmsg->reply.u.nak.reason,
4028 			      drm_dp_mst_nak_reason_str(txmsg->reply.u.nak.reason),
4029 			      txmsg->reply.u.nak.nak_data);
4030 	}
4031 
4032 	memset(msg, 0, sizeof(struct drm_dp_sideband_msg_rx));
4033 	drm_dp_mst_topology_put_mstb(mstb);
4034 
4035 	mutex_lock(&mgr->qlock);
4036 	txmsg->state = DRM_DP_SIDEBAND_TX_RX;
4037 	list_del(&txmsg->next);
4038 	mutex_unlock(&mgr->qlock);
4039 
4040 	wake_up_all(&mgr->tx_waitq);
4041 
4042 	return 0;
4043 
4044 out_clear_reply:
4045 	memset(msg, 0, sizeof(struct drm_dp_sideband_msg_rx));
4046 out:
4047 	if (mstb)
4048 		drm_dp_mst_topology_put_mstb(mstb);
4049 
4050 	return 0;
4051 }
4052 
4053 static inline bool
drm_dp_mst_process_up_req(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_pending_up_req * up_req)4054 drm_dp_mst_process_up_req(struct drm_dp_mst_topology_mgr *mgr,
4055 			  struct drm_dp_pending_up_req *up_req)
4056 {
4057 	struct drm_dp_mst_branch *mstb = NULL;
4058 	struct drm_dp_sideband_msg_req_body *msg = &up_req->msg;
4059 	struct drm_dp_sideband_msg_hdr *hdr = &up_req->hdr;
4060 	bool hotplug = false;
4061 
4062 	if (hdr->broadcast) {
4063 		const u8 *guid = NULL;
4064 
4065 		if (msg->req_type == DP_CONNECTION_STATUS_NOTIFY)
4066 			guid = msg->u.conn_stat.guid;
4067 		else if (msg->req_type == DP_RESOURCE_STATUS_NOTIFY)
4068 			guid = msg->u.resource_stat.guid;
4069 
4070 		if (guid)
4071 			mstb = drm_dp_get_mst_branch_device_by_guid(mgr, guid);
4072 	} else {
4073 		mstb = drm_dp_get_mst_branch_device(mgr, hdr->lct, hdr->rad);
4074 	}
4075 
4076 	if (!mstb) {
4077 		DRM_DEBUG_KMS("Got MST reply from unknown device %d\n",
4078 			      hdr->lct);
4079 		return false;
4080 	}
4081 
4082 	/* TODO: Add missing handler for DP_RESOURCE_STATUS_NOTIFY events */
4083 	if (msg->req_type == DP_CONNECTION_STATUS_NOTIFY) {
4084 		drm_dp_mst_handle_conn_stat(mstb, &msg->u.conn_stat);
4085 		hotplug = true;
4086 	}
4087 
4088 	drm_dp_mst_topology_put_mstb(mstb);
4089 	return hotplug;
4090 }
4091 
drm_dp_mst_up_req_work(struct work_struct * work)4092 static void drm_dp_mst_up_req_work(struct work_struct *work)
4093 {
4094 	struct drm_dp_mst_topology_mgr *mgr =
4095 		container_of(work, struct drm_dp_mst_topology_mgr,
4096 			     up_req_work);
4097 	struct drm_dp_pending_up_req *up_req;
4098 	bool send_hotplug = false;
4099 
4100 	mutex_lock(&mgr->probe_lock);
4101 	while (true) {
4102 		mutex_lock(&mgr->up_req_lock);
4103 		up_req = list_first_entry_or_null(&mgr->up_req_list,
4104 						  struct drm_dp_pending_up_req,
4105 						  next);
4106 		if (up_req)
4107 			list_del(&up_req->next);
4108 		mutex_unlock(&mgr->up_req_lock);
4109 
4110 		if (!up_req)
4111 			break;
4112 
4113 		send_hotplug |= drm_dp_mst_process_up_req(mgr, up_req);
4114 		kfree(up_req);
4115 	}
4116 	mutex_unlock(&mgr->probe_lock);
4117 
4118 	if (send_hotplug)
4119 		drm_kms_helper_hotplug_event(mgr->dev);
4120 }
4121 
drm_dp_mst_handle_up_req(struct drm_dp_mst_topology_mgr * mgr)4122 static int drm_dp_mst_handle_up_req(struct drm_dp_mst_topology_mgr *mgr)
4123 {
4124 	struct drm_dp_pending_up_req *up_req;
4125 	struct drm_dp_mst_branch *mst_primary;
4126 
4127 	if (!drm_dp_get_one_sb_msg(mgr, true, NULL))
4128 		goto out_clear_reply;
4129 
4130 	if (!mgr->up_req_recv.have_eomt)
4131 		return 0;
4132 
4133 	up_req = kzalloc(sizeof(*up_req), GFP_KERNEL);
4134 	if (!up_req) {
4135 		DRM_ERROR("Not enough memory to process MST up req\n");
4136 		return -ENOMEM;
4137 	}
4138 	INIT_LIST_HEAD(&up_req->next);
4139 
4140 	drm_dp_sideband_parse_req(&mgr->up_req_recv, &up_req->msg);
4141 
4142 	if (up_req->msg.req_type != DP_CONNECTION_STATUS_NOTIFY &&
4143 	    up_req->msg.req_type != DP_RESOURCE_STATUS_NOTIFY) {
4144 		DRM_DEBUG_KMS("Received unknown up req type, ignoring: %x\n",
4145 			      up_req->msg.req_type);
4146 		kfree(up_req);
4147 		goto out_clear_reply;
4148 	}
4149 
4150 	mutex_lock(&mgr->lock);
4151 	mst_primary = mgr->mst_primary;
4152 	if (!mst_primary || !drm_dp_mst_topology_try_get_mstb(mst_primary)) {
4153 		mutex_unlock(&mgr->lock);
4154 		kfree(up_req);
4155 		goto out_clear_reply;
4156 	}
4157 	mutex_unlock(&mgr->lock);
4158 
4159 	drm_dp_send_up_ack_reply(mgr, mst_primary, up_req->msg.req_type,
4160 				 false);
4161 
4162 	if (up_req->msg.req_type == DP_CONNECTION_STATUS_NOTIFY) {
4163 		const struct drm_dp_connection_status_notify *conn_stat =
4164 			&up_req->msg.u.conn_stat;
4165 
4166 		DRM_DEBUG_KMS("Got CSN: pn: %d ldps:%d ddps: %d mcs: %d ip: %d pdt: %d\n",
4167 			      conn_stat->port_number,
4168 			      conn_stat->legacy_device_plug_status,
4169 			      conn_stat->displayport_device_plug_status,
4170 			      conn_stat->message_capability_status,
4171 			      conn_stat->input_port,
4172 			      conn_stat->peer_device_type);
4173 	} else if (up_req->msg.req_type == DP_RESOURCE_STATUS_NOTIFY) {
4174 		const struct drm_dp_resource_status_notify *res_stat =
4175 			&up_req->msg.u.resource_stat;
4176 
4177 		DRM_DEBUG_KMS("Got RSN: pn: %d avail_pbn %d\n",
4178 			      res_stat->port_number,
4179 			      res_stat->available_pbn);
4180 	}
4181 
4182 	up_req->hdr = mgr->up_req_recv.initial_hdr;
4183 	mutex_lock(&mgr->up_req_lock);
4184 	list_add_tail(&up_req->next, &mgr->up_req_list);
4185 	mutex_unlock(&mgr->up_req_lock);
4186 	queue_work(system_long_wq, &mgr->up_req_work);
4187 
4188 	drm_dp_mst_topology_put_mstb(mst_primary);
4189 out_clear_reply:
4190 	memset(&mgr->up_req_recv, 0, sizeof(struct drm_dp_sideband_msg_rx));
4191 	return 0;
4192 }
4193 
update_msg_rx_state(struct drm_dp_mst_topology_mgr * mgr)4194 static void update_msg_rx_state(struct drm_dp_mst_topology_mgr *mgr)
4195 {
4196 	mutex_lock(&mgr->lock);
4197 	if (mgr->reset_rx_state) {
4198 		mgr->reset_rx_state = false;
4199 		reset_msg_rx_state(&mgr->down_rep_recv);
4200 		reset_msg_rx_state(&mgr->up_req_recv);
4201 	}
4202 	mutex_unlock(&mgr->lock);
4203 }
4204 
4205 /**
4206  * drm_dp_mst_hpd_irq() - MST hotplug IRQ notify
4207  * @mgr: manager to notify irq for.
4208  * @esi: 4 bytes from SINK_COUNT_ESI
4209  * @handled: whether the hpd interrupt was consumed or not
4210  *
4211  * This should be called from the driver when it detects a short IRQ,
4212  * along with the value of the DEVICE_SERVICE_IRQ_VECTOR_ESI0. The
4213  * topology manager will process the sideband messages received as a result
4214  * of this.
4215  */
drm_dp_mst_hpd_irq(struct drm_dp_mst_topology_mgr * mgr,u8 * esi,bool * handled)4216 int drm_dp_mst_hpd_irq(struct drm_dp_mst_topology_mgr *mgr, u8 *esi, bool *handled)
4217 {
4218 	int ret = 0;
4219 	int sc;
4220 	*handled = false;
4221 	sc = esi[0] & 0x3f;
4222 
4223 	if (sc != mgr->sink_count) {
4224 		mgr->sink_count = sc;
4225 		*handled = true;
4226 	}
4227 
4228 	update_msg_rx_state(mgr);
4229 
4230 	if (esi[1] & DP_DOWN_REP_MSG_RDY) {
4231 		ret = drm_dp_mst_handle_down_rep(mgr);
4232 		*handled = true;
4233 	}
4234 
4235 	if (esi[1] & DP_UP_REQ_MSG_RDY) {
4236 		ret |= drm_dp_mst_handle_up_req(mgr);
4237 		*handled = true;
4238 	}
4239 
4240 	drm_dp_mst_kick_tx(mgr);
4241 	return ret;
4242 }
4243 EXPORT_SYMBOL(drm_dp_mst_hpd_irq);
4244 
4245 /**
4246  * drm_dp_mst_detect_port() - get connection status for an MST port
4247  * @connector: DRM connector for this port
4248  * @ctx: The acquisition context to use for grabbing locks
4249  * @mgr: manager for this port
4250  * @port: pointer to a port
4251  *
4252  * This returns the current connection state for a port.
4253  */
4254 int
drm_dp_mst_detect_port(struct drm_connector * connector,struct drm_modeset_acquire_ctx * ctx,struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port)4255 drm_dp_mst_detect_port(struct drm_connector *connector,
4256 		       struct drm_modeset_acquire_ctx *ctx,
4257 		       struct drm_dp_mst_topology_mgr *mgr,
4258 		       struct drm_dp_mst_port *port)
4259 {
4260 	int ret;
4261 
4262 	/* we need to search for the port in the mgr in case it's gone */
4263 	port = drm_dp_mst_topology_get_port_validated(mgr, port);
4264 	if (!port)
4265 		return connector_status_disconnected;
4266 
4267 	ret = drm_modeset_lock(&mgr->base.lock, ctx);
4268 	if (ret)
4269 		goto out;
4270 
4271 	ret = connector_status_disconnected;
4272 
4273 	if (!port->ddps)
4274 		goto out;
4275 
4276 	switch (port->pdt) {
4277 	case DP_PEER_DEVICE_NONE:
4278 		break;
4279 	case DP_PEER_DEVICE_MST_BRANCHING:
4280 		if (!port->mcs)
4281 			ret = connector_status_connected;
4282 		break;
4283 
4284 	case DP_PEER_DEVICE_SST_SINK:
4285 		ret = connector_status_connected;
4286 		/* for logical ports - cache the EDID */
4287 		if (port->port_num >= 8 && !port->cached_edid) {
4288 			port->cached_edid = drm_get_edid(connector, &port->aux.ddc);
4289 		}
4290 		break;
4291 	case DP_PEER_DEVICE_DP_LEGACY_CONV:
4292 		if (port->ldps)
4293 			ret = connector_status_connected;
4294 		break;
4295 	}
4296 out:
4297 	drm_dp_mst_topology_put_port(port);
4298 	return ret;
4299 }
4300 EXPORT_SYMBOL(drm_dp_mst_detect_port);
4301 
4302 /**
4303  * drm_dp_mst_get_edid() - get EDID for an MST port
4304  * @connector: toplevel connector to get EDID for
4305  * @mgr: manager for this port
4306  * @port: unverified pointer to a port.
4307  *
4308  * This returns an EDID for the port connected to a connector,
4309  * It validates the pointer still exists so the caller doesn't require a
4310  * reference.
4311  */
drm_dp_mst_get_edid(struct drm_connector * connector,struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port)4312 struct edid *drm_dp_mst_get_edid(struct drm_connector *connector, struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
4313 {
4314 	struct edid *edid = NULL;
4315 
4316 	/* we need to search for the port in the mgr in case it's gone */
4317 	port = drm_dp_mst_topology_get_port_validated(mgr, port);
4318 	if (!port)
4319 		return NULL;
4320 
4321 	if (port->cached_edid)
4322 		edid = drm_edid_duplicate(port->cached_edid);
4323 	else {
4324 		edid = drm_get_edid(connector, &port->aux.ddc);
4325 	}
4326 	port->has_audio = drm_detect_monitor_audio(edid);
4327 	drm_dp_mst_topology_put_port(port);
4328 	return edid;
4329 }
4330 EXPORT_SYMBOL(drm_dp_mst_get_edid);
4331 
4332 /**
4333  * drm_dp_find_vcpi_slots() - Find VCPI slots for this PBN value
4334  * @mgr: manager to use
4335  * @pbn: payload bandwidth to convert into slots.
4336  *
4337  * Calculate the number of VCPI slots that will be required for the given PBN
4338  * value. This function is deprecated, and should not be used in atomic
4339  * drivers.
4340  *
4341  * RETURNS:
4342  * The total slots required for this port, or error.
4343  */
drm_dp_find_vcpi_slots(struct drm_dp_mst_topology_mgr * mgr,int pbn)4344 int drm_dp_find_vcpi_slots(struct drm_dp_mst_topology_mgr *mgr,
4345 			   int pbn)
4346 {
4347 	int num_slots;
4348 
4349 	num_slots = DIV_ROUND_UP(pbn, mgr->pbn_div);
4350 
4351 	/* max. time slots - one slot for MTP header */
4352 	if (num_slots > 63)
4353 		return -ENOSPC;
4354 	return num_slots;
4355 }
4356 EXPORT_SYMBOL(drm_dp_find_vcpi_slots);
4357 
drm_dp_init_vcpi(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_vcpi * vcpi,int pbn,int slots)4358 static int drm_dp_init_vcpi(struct drm_dp_mst_topology_mgr *mgr,
4359 			    struct drm_dp_vcpi *vcpi, int pbn, int slots)
4360 {
4361 	int ret;
4362 
4363 	/* max. time slots - one slot for MTP header */
4364 	if (slots > 63)
4365 		return -ENOSPC;
4366 
4367 	vcpi->pbn = pbn;
4368 	vcpi->aligned_pbn = slots * mgr->pbn_div;
4369 	vcpi->num_slots = slots;
4370 
4371 	ret = drm_dp_mst_assign_payload_id(mgr, vcpi);
4372 	if (ret < 0)
4373 		return ret;
4374 	return 0;
4375 }
4376 
4377 /**
4378  * drm_dp_atomic_find_vcpi_slots() - Find and add VCPI slots to the state
4379  * @state: global atomic state
4380  * @mgr: MST topology manager for the port
4381  * @port: port to find vcpi slots for
4382  * @pbn: bandwidth required for the mode in PBN
4383  * @pbn_div: divider for DSC mode that takes FEC into account
4384  *
4385  * Allocates VCPI slots to @port, replacing any previous VCPI allocations it
4386  * may have had. Any atomic drivers which support MST must call this function
4387  * in their &drm_encoder_helper_funcs.atomic_check() callback to change the
4388  * current VCPI allocation for the new state, but only when
4389  * &drm_crtc_state.mode_changed or &drm_crtc_state.connectors_changed is set
4390  * to ensure compatibility with userspace applications that still use the
4391  * legacy modesetting UAPI.
4392  *
4393  * Allocations set by this function are not checked against the bandwidth
4394  * restraints of @mgr until the driver calls drm_dp_mst_atomic_check().
4395  *
4396  * Additionally, it is OK to call this function multiple times on the same
4397  * @port as needed. It is not OK however, to call this function and
4398  * drm_dp_atomic_release_vcpi_slots() in the same atomic check phase.
4399  *
4400  * See also:
4401  * drm_dp_atomic_release_vcpi_slots()
4402  * drm_dp_mst_atomic_check()
4403  *
4404  * Returns:
4405  * Total slots in the atomic state assigned for this port, or a negative error
4406  * code if the port no longer exists
4407  */
drm_dp_atomic_find_vcpi_slots(struct drm_atomic_state * state,struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port,int pbn,int pbn_div)4408 int drm_dp_atomic_find_vcpi_slots(struct drm_atomic_state *state,
4409 				  struct drm_dp_mst_topology_mgr *mgr,
4410 				  struct drm_dp_mst_port *port, int pbn,
4411 				  int pbn_div)
4412 {
4413 	struct drm_dp_mst_topology_state *topology_state;
4414 	struct drm_dp_vcpi_allocation *pos, *vcpi = NULL;
4415 	int prev_slots, prev_bw, req_slots;
4416 
4417 	topology_state = drm_atomic_get_mst_topology_state(state, mgr);
4418 	if (IS_ERR(topology_state))
4419 		return PTR_ERR(topology_state);
4420 
4421 	/* Find the current allocation for this port, if any */
4422 	list_for_each_entry(pos, &topology_state->vcpis, next) {
4423 		if (pos->port == port) {
4424 			vcpi = pos;
4425 			prev_slots = vcpi->vcpi;
4426 			prev_bw = vcpi->pbn;
4427 
4428 			/*
4429 			 * This should never happen, unless the driver tries
4430 			 * releasing and allocating the same VCPI allocation,
4431 			 * which is an error
4432 			 */
4433 			if (WARN_ON(!prev_slots)) {
4434 				DRM_ERROR("cannot allocate and release VCPI on [MST PORT:%p] in the same state\n",
4435 					  port);
4436 				return -EINVAL;
4437 			}
4438 
4439 			break;
4440 		}
4441 	}
4442 	if (!vcpi) {
4443 		prev_slots = 0;
4444 		prev_bw = 0;
4445 	}
4446 
4447 	if (pbn_div <= 0)
4448 		pbn_div = mgr->pbn_div;
4449 
4450 	req_slots = DIV_ROUND_UP(pbn, pbn_div);
4451 
4452 	DRM_DEBUG_ATOMIC("[CONNECTOR:%d:%s] [MST PORT:%p] VCPI %d -> %d\n",
4453 			 port->connector->base.id, port->connector->name,
4454 			 port, prev_slots, req_slots);
4455 	DRM_DEBUG_ATOMIC("[CONNECTOR:%d:%s] [MST PORT:%p] PBN %d -> %d\n",
4456 			 port->connector->base.id, port->connector->name,
4457 			 port, prev_bw, pbn);
4458 
4459 	/* Add the new allocation to the state */
4460 	if (!vcpi) {
4461 		vcpi = kzalloc(sizeof(*vcpi), GFP_KERNEL);
4462 		if (!vcpi)
4463 			return -ENOMEM;
4464 
4465 		drm_dp_mst_get_port_malloc(port);
4466 		vcpi->port = port;
4467 		list_add(&vcpi->next, &topology_state->vcpis);
4468 	}
4469 	vcpi->vcpi = req_slots;
4470 	vcpi->pbn = pbn;
4471 
4472 	return req_slots;
4473 }
4474 EXPORT_SYMBOL(drm_dp_atomic_find_vcpi_slots);
4475 
4476 /**
4477  * drm_dp_atomic_release_vcpi_slots() - Release allocated vcpi slots
4478  * @state: global atomic state
4479  * @mgr: MST topology manager for the port
4480  * @port: The port to release the VCPI slots from
4481  *
4482  * Releases any VCPI slots that have been allocated to a port in the atomic
4483  * state. Any atomic drivers which support MST must call this function in
4484  * their &drm_connector_helper_funcs.atomic_check() callback when the
4485  * connector will no longer have VCPI allocated (e.g. because its CRTC was
4486  * removed) when it had VCPI allocated in the previous atomic state.
4487  *
4488  * It is OK to call this even if @port has been removed from the system.
4489  * Additionally, it is OK to call this function multiple times on the same
4490  * @port as needed. It is not OK however, to call this function and
4491  * drm_dp_atomic_find_vcpi_slots() on the same @port in a single atomic check
4492  * phase.
4493  *
4494  * See also:
4495  * drm_dp_atomic_find_vcpi_slots()
4496  * drm_dp_mst_atomic_check()
4497  *
4498  * Returns:
4499  * 0 if all slots for this port were added back to
4500  * &drm_dp_mst_topology_state.avail_slots or negative error code
4501  */
drm_dp_atomic_release_vcpi_slots(struct drm_atomic_state * state,struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port)4502 int drm_dp_atomic_release_vcpi_slots(struct drm_atomic_state *state,
4503 				     struct drm_dp_mst_topology_mgr *mgr,
4504 				     struct drm_dp_mst_port *port)
4505 {
4506 	struct drm_dp_mst_topology_state *topology_state;
4507 	struct drm_dp_vcpi_allocation *pos;
4508 	bool found = false;
4509 
4510 	topology_state = drm_atomic_get_mst_topology_state(state, mgr);
4511 	if (IS_ERR(topology_state))
4512 		return PTR_ERR(topology_state);
4513 
4514 	list_for_each_entry(pos, &topology_state->vcpis, next) {
4515 		if (pos->port == port) {
4516 			found = true;
4517 			break;
4518 		}
4519 	}
4520 	if (WARN_ON(!found)) {
4521 		DRM_ERROR("no VCPI for [MST PORT:%p] found in mst state %p\n",
4522 			  port, &topology_state->base);
4523 		return -EINVAL;
4524 	}
4525 
4526 	DRM_DEBUG_ATOMIC("[MST PORT:%p] VCPI %d -> 0\n", port, pos->vcpi);
4527 	if (pos->vcpi) {
4528 		drm_dp_mst_put_port_malloc(port);
4529 		pos->vcpi = 0;
4530 		pos->pbn = 0;
4531 	}
4532 
4533 	return 0;
4534 }
4535 EXPORT_SYMBOL(drm_dp_atomic_release_vcpi_slots);
4536 
4537 /**
4538  * drm_dp_mst_allocate_vcpi() - Allocate a virtual channel
4539  * @mgr: manager for this port
4540  * @port: port to allocate a virtual channel for.
4541  * @pbn: payload bandwidth number to request
4542  * @slots: returned number of slots for this PBN.
4543  */
drm_dp_mst_allocate_vcpi(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port,int pbn,int slots)4544 bool drm_dp_mst_allocate_vcpi(struct drm_dp_mst_topology_mgr *mgr,
4545 			      struct drm_dp_mst_port *port, int pbn, int slots)
4546 {
4547 	int ret;
4548 
4549 	if (slots < 0)
4550 		return false;
4551 
4552 	port = drm_dp_mst_topology_get_port_validated(mgr, port);
4553 	if (!port)
4554 		return false;
4555 
4556 	if (port->vcpi.vcpi > 0) {
4557 		DRM_DEBUG_KMS("payload: vcpi %d already allocated for pbn %d - requested pbn %d\n",
4558 			      port->vcpi.vcpi, port->vcpi.pbn, pbn);
4559 		if (pbn == port->vcpi.pbn) {
4560 			drm_dp_mst_topology_put_port(port);
4561 			return true;
4562 		}
4563 	}
4564 
4565 	ret = drm_dp_init_vcpi(mgr, &port->vcpi, pbn, slots);
4566 	if (ret) {
4567 		DRM_DEBUG_KMS("failed to init vcpi slots=%d max=63 ret=%d\n",
4568 			      DIV_ROUND_UP(pbn, mgr->pbn_div), ret);
4569 		drm_dp_mst_topology_put_port(port);
4570 		goto out;
4571 	}
4572 	DRM_DEBUG_KMS("initing vcpi for pbn=%d slots=%d\n",
4573 		      pbn, port->vcpi.num_slots);
4574 
4575 	/* Keep port allocated until its payload has been removed */
4576 	drm_dp_mst_get_port_malloc(port);
4577 	drm_dp_mst_topology_put_port(port);
4578 	return true;
4579 out:
4580 	return false;
4581 }
4582 EXPORT_SYMBOL(drm_dp_mst_allocate_vcpi);
4583 
drm_dp_mst_get_vcpi_slots(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port)4584 int drm_dp_mst_get_vcpi_slots(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
4585 {
4586 	int slots = 0;
4587 
4588 	port = drm_dp_mst_topology_get_port_validated(mgr, port);
4589 	if (!port)
4590 		return slots;
4591 
4592 	slots = port->vcpi.num_slots;
4593 	drm_dp_mst_topology_put_port(port);
4594 	return slots;
4595 }
4596 EXPORT_SYMBOL(drm_dp_mst_get_vcpi_slots);
4597 
4598 /**
4599  * drm_dp_mst_reset_vcpi_slots() - Reset number of slots to 0 for VCPI
4600  * @mgr: manager for this port
4601  * @port: unverified pointer to a port.
4602  *
4603  * This just resets the number of slots for the ports VCPI for later programming.
4604  */
drm_dp_mst_reset_vcpi_slots(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port)4605 void drm_dp_mst_reset_vcpi_slots(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
4606 {
4607 	/*
4608 	 * A port with VCPI will remain allocated until its VCPI is
4609 	 * released, no verified ref needed
4610 	 */
4611 
4612 	port->vcpi.num_slots = 0;
4613 }
4614 EXPORT_SYMBOL(drm_dp_mst_reset_vcpi_slots);
4615 
4616 /**
4617  * drm_dp_mst_deallocate_vcpi() - deallocate a VCPI
4618  * @mgr: manager for this port
4619  * @port: port to deallocate vcpi for
4620  *
4621  * This can be called unconditionally, regardless of whether
4622  * drm_dp_mst_allocate_vcpi() succeeded or not.
4623  */
drm_dp_mst_deallocate_vcpi(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port)4624 void drm_dp_mst_deallocate_vcpi(struct drm_dp_mst_topology_mgr *mgr,
4625 				struct drm_dp_mst_port *port)
4626 {
4627 	bool skip;
4628 
4629 	if (!port->vcpi.vcpi)
4630 		return;
4631 
4632 	mutex_lock(&mgr->lock);
4633 	skip = !drm_dp_mst_port_downstream_of_branch(port, mgr->mst_primary);
4634 	mutex_unlock(&mgr->lock);
4635 
4636 	if (skip)
4637 		return;
4638 
4639 	drm_dp_mst_put_payload_id(mgr, port->vcpi.vcpi);
4640 	port->vcpi.num_slots = 0;
4641 	port->vcpi.pbn = 0;
4642 	port->vcpi.aligned_pbn = 0;
4643 	port->vcpi.vcpi = 0;
4644 	drm_dp_mst_put_port_malloc(port);
4645 }
4646 EXPORT_SYMBOL(drm_dp_mst_deallocate_vcpi);
4647 
drm_dp_dpcd_write_payload(struct drm_dp_mst_topology_mgr * mgr,int id,struct drm_dp_payload * payload)4648 static int drm_dp_dpcd_write_payload(struct drm_dp_mst_topology_mgr *mgr,
4649 				     int id, struct drm_dp_payload *payload)
4650 {
4651 	u8 payload_alloc[3], status;
4652 	int ret;
4653 	int retries = 0;
4654 
4655 	drm_dp_dpcd_writeb(mgr->aux, DP_PAYLOAD_TABLE_UPDATE_STATUS,
4656 			   DP_PAYLOAD_TABLE_UPDATED);
4657 
4658 	payload_alloc[0] = id;
4659 	payload_alloc[1] = payload->start_slot;
4660 	payload_alloc[2] = payload->num_slots;
4661 
4662 	ret = drm_dp_dpcd_write(mgr->aux, DP_PAYLOAD_ALLOCATE_SET, payload_alloc, 3);
4663 	if (ret != 3) {
4664 		DRM_DEBUG_KMS("failed to write payload allocation %d\n", ret);
4665 		goto fail;
4666 	}
4667 
4668 retry:
4669 	ret = drm_dp_dpcd_readb(mgr->aux, DP_PAYLOAD_TABLE_UPDATE_STATUS, &status);
4670 	if (ret < 0) {
4671 		DRM_DEBUG_KMS("failed to read payload table status %d\n", ret);
4672 		goto fail;
4673 	}
4674 
4675 	if (!(status & DP_PAYLOAD_TABLE_UPDATED)) {
4676 		retries++;
4677 		if (retries < 20) {
4678 			usleep_range(10000, 20000);
4679 			goto retry;
4680 		}
4681 		DRM_DEBUG_KMS("status not set after read payload table status %d\n", status);
4682 		ret = -EINVAL;
4683 		goto fail;
4684 	}
4685 	ret = 0;
4686 fail:
4687 	return ret;
4688 }
4689 
do_get_act_status(struct drm_dp_aux * aux)4690 static int do_get_act_status(struct drm_dp_aux *aux)
4691 {
4692 	int ret;
4693 	u8 status;
4694 
4695 	ret = drm_dp_dpcd_readb(aux, DP_PAYLOAD_TABLE_UPDATE_STATUS, &status);
4696 	if (ret < 0)
4697 		return ret;
4698 
4699 	return status;
4700 }
4701 
4702 /**
4703  * drm_dp_check_act_status() - Polls for ACT handled status.
4704  * @mgr: manager to use
4705  *
4706  * Tries waiting for the MST hub to finish updating it's payload table by
4707  * polling for the ACT handled bit for up to 3 seconds (yes-some hubs really
4708  * take that long).
4709  *
4710  * Returns:
4711  * 0 if the ACT was handled in time, negative error code on failure.
4712  */
drm_dp_check_act_status(struct drm_dp_mst_topology_mgr * mgr)4713 int drm_dp_check_act_status(struct drm_dp_mst_topology_mgr *mgr)
4714 {
4715 	/*
4716 	 * There doesn't seem to be any recommended retry count or timeout in
4717 	 * the MST specification. Since some hubs have been observed to take
4718 	 * over 1 second to update their payload allocations under certain
4719 	 * conditions, we use a rather large timeout value.
4720 	 */
4721 	const int timeout_ms = 3000;
4722 	int ret, status;
4723 
4724 	ret = readx_poll_timeout(do_get_act_status, mgr->aux, status,
4725 				 status & DP_PAYLOAD_ACT_HANDLED || status < 0,
4726 				 200, timeout_ms * USEC_PER_MSEC);
4727 	if (ret < 0 && status >= 0) {
4728 		DRM_ERROR("Failed to get ACT after %dms, last status: %02x\n",
4729 			  timeout_ms, status);
4730 		return -EINVAL;
4731 	} else if (status < 0) {
4732 		/*
4733 		 * Failure here isn't unexpected - the hub may have
4734 		 * just been unplugged
4735 		 */
4736 		DRM_DEBUG_KMS("Failed to read payload table status: %d\n",
4737 			      status);
4738 		return status;
4739 	}
4740 
4741 	return 0;
4742 }
4743 EXPORT_SYMBOL(drm_dp_check_act_status);
4744 
4745 /**
4746  * drm_dp_calc_pbn_mode() - Calculate the PBN for a mode.
4747  * @clock: dot clock for the mode
4748  * @bpp: bpp for the mode.
4749  * @dsc: DSC mode. If true, bpp has units of 1/16 of a bit per pixel
4750  *
4751  * This uses the formula in the spec to calculate the PBN value for a mode.
4752  */
drm_dp_calc_pbn_mode(int clock,int bpp,bool dsc)4753 int drm_dp_calc_pbn_mode(int clock, int bpp, bool dsc)
4754 {
4755 	/*
4756 	 * margin 5300ppm + 300ppm ~ 0.6% as per spec, factor is 1.006
4757 	 * The unit of 54/64Mbytes/sec is an arbitrary unit chosen based on
4758 	 * common multiplier to render an integer PBN for all link rate/lane
4759 	 * counts combinations
4760 	 * calculate
4761 	 * peak_kbps *= (1006/1000)
4762 	 * peak_kbps *= (64/54)
4763 	 * peak_kbps *= 8    convert to bytes
4764 	 *
4765 	 * If the bpp is in units of 1/16, further divide by 16. Put this
4766 	 * factor in the numerator rather than the denominator to avoid
4767 	 * integer overflow
4768 	 */
4769 
4770 	if (dsc)
4771 		return DIV_ROUND_UP_ULL(mul_u32_u32(clock * (bpp / 16), 64 * 1006),
4772 					8 * 54 * 1000 * 1000);
4773 
4774 	return DIV_ROUND_UP_ULL(mul_u32_u32(clock * bpp, 64 * 1006),
4775 				8 * 54 * 1000 * 1000);
4776 }
4777 EXPORT_SYMBOL(drm_dp_calc_pbn_mode);
4778 
4779 /* we want to kick the TX after we've ack the up/down IRQs. */
drm_dp_mst_kick_tx(struct drm_dp_mst_topology_mgr * mgr)4780 static void drm_dp_mst_kick_tx(struct drm_dp_mst_topology_mgr *mgr)
4781 {
4782 	queue_work(system_long_wq, &mgr->tx_work);
4783 }
4784 
drm_dp_mst_dump_mstb(struct seq_file * m,struct drm_dp_mst_branch * mstb)4785 static void drm_dp_mst_dump_mstb(struct seq_file *m,
4786 				 struct drm_dp_mst_branch *mstb)
4787 {
4788 	struct drm_dp_mst_port *port;
4789 	int tabs = mstb->lct;
4790 	char prefix[10];
4791 	int i;
4792 
4793 	for (i = 0; i < tabs; i++)
4794 		prefix[i] = '\t';
4795 	prefix[i] = '\0';
4796 
4797 	seq_printf(m, "%smst: %p, %d\n", prefix, mstb, mstb->num_ports);
4798 	list_for_each_entry(port, &mstb->ports, next) {
4799 		seq_printf(m, "%sport: %d: input: %d: pdt: %d, ddps: %d ldps: %d, sdp: %d/%d, %p, conn: %p\n", prefix, port->port_num, port->input, port->pdt, port->ddps, port->ldps, port->num_sdp_streams, port->num_sdp_stream_sinks, port, port->connector);
4800 		if (port->mstb)
4801 			drm_dp_mst_dump_mstb(m, port->mstb);
4802 	}
4803 }
4804 
4805 #define DP_PAYLOAD_TABLE_SIZE		64
4806 
dump_dp_payload_table(struct drm_dp_mst_topology_mgr * mgr,char * buf)4807 static bool dump_dp_payload_table(struct drm_dp_mst_topology_mgr *mgr,
4808 				  char *buf)
4809 {
4810 	int i;
4811 
4812 	for (i = 0; i < DP_PAYLOAD_TABLE_SIZE; i += 16) {
4813 		if (drm_dp_dpcd_read(mgr->aux,
4814 				     DP_PAYLOAD_TABLE_UPDATE_STATUS + i,
4815 				     &buf[i], 16) != 16)
4816 			return false;
4817 	}
4818 	return true;
4819 }
4820 
fetch_monitor_name(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_port * port,char * name,int namelen)4821 static void fetch_monitor_name(struct drm_dp_mst_topology_mgr *mgr,
4822 			       struct drm_dp_mst_port *port, char *name,
4823 			       int namelen)
4824 {
4825 	struct edid *mst_edid;
4826 
4827 	mst_edid = drm_dp_mst_get_edid(port->connector, mgr, port);
4828 	drm_edid_get_monitor_name(mst_edid, name, namelen);
4829 	kfree(mst_edid);
4830 }
4831 
4832 /**
4833  * drm_dp_mst_dump_topology(): dump topology to seq file.
4834  * @m: seq_file to dump output to
4835  * @mgr: manager to dump current topology for.
4836  *
4837  * helper to dump MST topology to a seq file for debugfs.
4838  */
drm_dp_mst_dump_topology(struct seq_file * m,struct drm_dp_mst_topology_mgr * mgr)4839 void drm_dp_mst_dump_topology(struct seq_file *m,
4840 			      struct drm_dp_mst_topology_mgr *mgr)
4841 {
4842 	int i;
4843 	struct drm_dp_mst_port *port;
4844 
4845 	mutex_lock(&mgr->lock);
4846 	if (mgr->mst_primary)
4847 		drm_dp_mst_dump_mstb(m, mgr->mst_primary);
4848 
4849 	/* dump VCPIs */
4850 	mutex_unlock(&mgr->lock);
4851 
4852 	mutex_lock(&mgr->payload_lock);
4853 	seq_printf(m, "vcpi: %lx %lx %d\n", mgr->payload_mask, mgr->vcpi_mask,
4854 		mgr->max_payloads);
4855 
4856 	for (i = 0; i < mgr->max_payloads; i++) {
4857 		if (mgr->proposed_vcpis[i]) {
4858 			char name[14];
4859 
4860 			port = container_of(mgr->proposed_vcpis[i], struct drm_dp_mst_port, vcpi);
4861 			fetch_monitor_name(mgr, port, name, sizeof(name));
4862 			seq_printf(m, "vcpi %d: %d %d %d sink name: %s\n", i,
4863 				   port->port_num, port->vcpi.vcpi,
4864 				   port->vcpi.num_slots,
4865 				   (*name != 0) ? name :  "Unknown");
4866 		} else
4867 			seq_printf(m, "vcpi %d:unused\n", i);
4868 	}
4869 	for (i = 0; i < mgr->max_payloads; i++) {
4870 		seq_printf(m, "payload %d: %d, %d, %d\n",
4871 			   i,
4872 			   mgr->payloads[i].payload_state,
4873 			   mgr->payloads[i].start_slot,
4874 			   mgr->payloads[i].num_slots);
4875 
4876 
4877 	}
4878 	mutex_unlock(&mgr->payload_lock);
4879 
4880 	mutex_lock(&mgr->lock);
4881 	if (mgr->mst_primary) {
4882 		u8 buf[DP_PAYLOAD_TABLE_SIZE];
4883 		int ret;
4884 
4885 		ret = drm_dp_dpcd_read(mgr->aux, DP_DPCD_REV, buf, DP_RECEIVER_CAP_SIZE);
4886 		if (ret) {
4887 			seq_printf(m, "dpcd read failed\n");
4888 			goto out;
4889 		}
4890 		seq_printf(m, "dpcd: %*ph\n", DP_RECEIVER_CAP_SIZE, buf);
4891 
4892 		ret = drm_dp_dpcd_read(mgr->aux, DP_FAUX_CAP, buf, 2);
4893 		if (ret != 2) {
4894 			seq_printf(m, "faux/mst read failed\n");
4895 			goto out;
4896 		}
4897 		seq_printf(m, "faux/mst: %*ph\n", 2, buf);
4898 
4899 		ret = drm_dp_dpcd_read(mgr->aux, DP_MSTM_CTRL, buf, 1);
4900 		if (ret != 1) {
4901 			seq_printf(m, "mst ctrl read failed\n");
4902 			goto out;
4903 		}
4904 		seq_printf(m, "mst ctrl: %*ph\n", 1, buf);
4905 
4906 		/* dump the standard OUI branch header */
4907 		ret = drm_dp_dpcd_read(mgr->aux, DP_BRANCH_OUI, buf, DP_BRANCH_OUI_HEADER_SIZE);
4908 		if (ret != DP_BRANCH_OUI_HEADER_SIZE) {
4909 			seq_printf(m, "branch oui read failed\n");
4910 			goto out;
4911 		}
4912 		seq_printf(m, "branch oui: %*phN devid: ", 3, buf);
4913 
4914 		for (i = 0x3; i < 0x8 && buf[i]; i++)
4915 			seq_printf(m, "%c", buf[i]);
4916 		seq_printf(m, " revision: hw: %x.%x sw: %x.%x\n",
4917 			   buf[0x9] >> 4, buf[0x9] & 0xf, buf[0xa], buf[0xb]);
4918 		if (dump_dp_payload_table(mgr, buf))
4919 			seq_printf(m, "payload table: %*ph\n", DP_PAYLOAD_TABLE_SIZE, buf);
4920 	}
4921 
4922 out:
4923 	mutex_unlock(&mgr->lock);
4924 
4925 }
4926 EXPORT_SYMBOL(drm_dp_mst_dump_topology);
4927 
drm_dp_tx_work(struct work_struct * work)4928 static void drm_dp_tx_work(struct work_struct *work)
4929 {
4930 	struct drm_dp_mst_topology_mgr *mgr = container_of(work, struct drm_dp_mst_topology_mgr, tx_work);
4931 
4932 	mutex_lock(&mgr->qlock);
4933 	if (!list_empty(&mgr->tx_msg_downq))
4934 		process_single_down_tx_qlock(mgr);
4935 	mutex_unlock(&mgr->qlock);
4936 }
4937 
4938 static inline void
drm_dp_delayed_destroy_port(struct drm_dp_mst_port * port)4939 drm_dp_delayed_destroy_port(struct drm_dp_mst_port *port)
4940 {
4941 	drm_dp_port_set_pdt(port, DP_PEER_DEVICE_NONE, port->mcs);
4942 
4943 	if (port->connector) {
4944 		drm_connector_unregister(port->connector);
4945 		drm_connector_put(port->connector);
4946 	}
4947 
4948 	drm_dp_mst_put_port_malloc(port);
4949 }
4950 
4951 static inline void
drm_dp_delayed_destroy_mstb(struct drm_dp_mst_branch * mstb)4952 drm_dp_delayed_destroy_mstb(struct drm_dp_mst_branch *mstb)
4953 {
4954 	struct drm_dp_mst_topology_mgr *mgr = mstb->mgr;
4955 	struct drm_dp_mst_port *port, *port_tmp;
4956 	struct drm_dp_sideband_msg_tx *txmsg, *txmsg_tmp;
4957 	bool wake_tx = false;
4958 
4959 	mutex_lock(&mgr->lock);
4960 	list_for_each_entry_safe(port, port_tmp, &mstb->ports, next) {
4961 		list_del(&port->next);
4962 		drm_dp_mst_topology_put_port(port);
4963 	}
4964 	mutex_unlock(&mgr->lock);
4965 
4966 	/* drop any tx slot msg */
4967 	mutex_lock(&mstb->mgr->qlock);
4968 	list_for_each_entry_safe(txmsg, txmsg_tmp, &mgr->tx_msg_downq, next) {
4969 		if (txmsg->dst != mstb)
4970 			continue;
4971 
4972 		txmsg->state = DRM_DP_SIDEBAND_TX_TIMEOUT;
4973 		list_del(&txmsg->next);
4974 		wake_tx = true;
4975 	}
4976 	mutex_unlock(&mstb->mgr->qlock);
4977 
4978 	if (wake_tx)
4979 		wake_up_all(&mstb->mgr->tx_waitq);
4980 
4981 	drm_dp_mst_put_mstb_malloc(mstb);
4982 }
4983 
drm_dp_delayed_destroy_work(struct work_struct * work)4984 static void drm_dp_delayed_destroy_work(struct work_struct *work)
4985 {
4986 	struct drm_dp_mst_topology_mgr *mgr =
4987 		container_of(work, struct drm_dp_mst_topology_mgr,
4988 			     delayed_destroy_work);
4989 	bool send_hotplug = false, go_again;
4990 
4991 	/*
4992 	 * Not a regular list traverse as we have to drop the destroy
4993 	 * connector lock before destroying the mstb/port, to avoid AB->BA
4994 	 * ordering between this lock and the config mutex.
4995 	 */
4996 	do {
4997 		go_again = false;
4998 
4999 		for (;;) {
5000 			struct drm_dp_mst_branch *mstb;
5001 
5002 			mutex_lock(&mgr->delayed_destroy_lock);
5003 			mstb = list_first_entry_or_null(&mgr->destroy_branch_device_list,
5004 							struct drm_dp_mst_branch,
5005 							destroy_next);
5006 			if (mstb)
5007 				list_del(&mstb->destroy_next);
5008 			mutex_unlock(&mgr->delayed_destroy_lock);
5009 
5010 			if (!mstb)
5011 				break;
5012 
5013 			drm_dp_delayed_destroy_mstb(mstb);
5014 			go_again = true;
5015 		}
5016 
5017 		for (;;) {
5018 			struct drm_dp_mst_port *port;
5019 
5020 			mutex_lock(&mgr->delayed_destroy_lock);
5021 			port = list_first_entry_or_null(&mgr->destroy_port_list,
5022 							struct drm_dp_mst_port,
5023 							next);
5024 			if (port)
5025 				list_del(&port->next);
5026 			mutex_unlock(&mgr->delayed_destroy_lock);
5027 
5028 			if (!port)
5029 				break;
5030 
5031 			drm_dp_delayed_destroy_port(port);
5032 			send_hotplug = true;
5033 			go_again = true;
5034 		}
5035 	} while (go_again);
5036 
5037 	if (send_hotplug)
5038 		drm_kms_helper_hotplug_event(mgr->dev);
5039 }
5040 
5041 static struct drm_private_state *
drm_dp_mst_duplicate_state(struct drm_private_obj * obj)5042 drm_dp_mst_duplicate_state(struct drm_private_obj *obj)
5043 {
5044 	struct drm_dp_mst_topology_state *state, *old_state =
5045 		to_dp_mst_topology_state(obj->state);
5046 	struct drm_dp_vcpi_allocation *pos, *vcpi;
5047 
5048 	state = kmemdup(old_state, sizeof(*state), GFP_KERNEL);
5049 	if (!state)
5050 		return NULL;
5051 
5052 	__drm_atomic_helper_private_obj_duplicate_state(obj, &state->base);
5053 
5054 	INIT_LIST_HEAD(&state->vcpis);
5055 
5056 	list_for_each_entry(pos, &old_state->vcpis, next) {
5057 		/* Prune leftover freed VCPI allocations */
5058 		if (!pos->vcpi)
5059 			continue;
5060 
5061 		vcpi = kmemdup(pos, sizeof(*vcpi), GFP_KERNEL);
5062 		if (!vcpi)
5063 			goto fail;
5064 
5065 		drm_dp_mst_get_port_malloc(vcpi->port);
5066 		list_add(&vcpi->next, &state->vcpis);
5067 	}
5068 
5069 	return &state->base;
5070 
5071 fail:
5072 	list_for_each_entry_safe(pos, vcpi, &state->vcpis, next) {
5073 		drm_dp_mst_put_port_malloc(pos->port);
5074 		kfree(pos);
5075 	}
5076 	kfree(state);
5077 
5078 	return NULL;
5079 }
5080 
drm_dp_mst_destroy_state(struct drm_private_obj * obj,struct drm_private_state * state)5081 static void drm_dp_mst_destroy_state(struct drm_private_obj *obj,
5082 				     struct drm_private_state *state)
5083 {
5084 	struct drm_dp_mst_topology_state *mst_state =
5085 		to_dp_mst_topology_state(state);
5086 	struct drm_dp_vcpi_allocation *pos, *tmp;
5087 
5088 	list_for_each_entry_safe(pos, tmp, &mst_state->vcpis, next) {
5089 		/* We only keep references to ports with non-zero VCPIs */
5090 		if (pos->vcpi)
5091 			drm_dp_mst_put_port_malloc(pos->port);
5092 		kfree(pos);
5093 	}
5094 
5095 	kfree(mst_state);
5096 }
5097 
drm_dp_mst_port_downstream_of_branch(struct drm_dp_mst_port * port,struct drm_dp_mst_branch * branch)5098 static bool drm_dp_mst_port_downstream_of_branch(struct drm_dp_mst_port *port,
5099 						 struct drm_dp_mst_branch *branch)
5100 {
5101 	while (port->parent) {
5102 		if (port->parent == branch)
5103 			return true;
5104 
5105 		if (port->parent->port_parent)
5106 			port = port->parent->port_parent;
5107 		else
5108 			break;
5109 	}
5110 	return false;
5111 }
5112 
5113 static int
5114 drm_dp_mst_atomic_check_port_bw_limit(struct drm_dp_mst_port *port,
5115 				      struct drm_dp_mst_topology_state *state);
5116 
5117 static int
drm_dp_mst_atomic_check_mstb_bw_limit(struct drm_dp_mst_branch * mstb,struct drm_dp_mst_topology_state * state)5118 drm_dp_mst_atomic_check_mstb_bw_limit(struct drm_dp_mst_branch *mstb,
5119 				      struct drm_dp_mst_topology_state *state)
5120 {
5121 	struct drm_dp_vcpi_allocation *vcpi;
5122 	struct drm_dp_mst_port *port;
5123 	int pbn_used = 0, ret;
5124 	bool found = false;
5125 
5126 	/* Check that we have at least one port in our state that's downstream
5127 	 * of this branch, otherwise we can skip this branch
5128 	 */
5129 	list_for_each_entry(vcpi, &state->vcpis, next) {
5130 		if (!vcpi->pbn ||
5131 		    !drm_dp_mst_port_downstream_of_branch(vcpi->port, mstb))
5132 			continue;
5133 
5134 		found = true;
5135 		break;
5136 	}
5137 	if (!found)
5138 		return 0;
5139 
5140 	if (mstb->port_parent)
5141 		DRM_DEBUG_ATOMIC("[MSTB:%p] [MST PORT:%p] Checking bandwidth limits on [MSTB:%p]\n",
5142 				 mstb->port_parent->parent, mstb->port_parent,
5143 				 mstb);
5144 	else
5145 		DRM_DEBUG_ATOMIC("[MSTB:%p] Checking bandwidth limits\n",
5146 				 mstb);
5147 
5148 	list_for_each_entry(port, &mstb->ports, next) {
5149 		ret = drm_dp_mst_atomic_check_port_bw_limit(port, state);
5150 		if (ret < 0)
5151 			return ret;
5152 
5153 		pbn_used += ret;
5154 	}
5155 
5156 	return pbn_used;
5157 }
5158 
5159 static int
drm_dp_mst_atomic_check_port_bw_limit(struct drm_dp_mst_port * port,struct drm_dp_mst_topology_state * state)5160 drm_dp_mst_atomic_check_port_bw_limit(struct drm_dp_mst_port *port,
5161 				      struct drm_dp_mst_topology_state *state)
5162 {
5163 	struct drm_dp_vcpi_allocation *vcpi;
5164 	int pbn_used = 0;
5165 
5166 	if (port->pdt == DP_PEER_DEVICE_NONE)
5167 		return 0;
5168 
5169 	if (drm_dp_mst_is_end_device(port->pdt, port->mcs)) {
5170 		bool found = false;
5171 
5172 		list_for_each_entry(vcpi, &state->vcpis, next) {
5173 			if (vcpi->port != port)
5174 				continue;
5175 			if (!vcpi->pbn)
5176 				return 0;
5177 
5178 			found = true;
5179 			break;
5180 		}
5181 		if (!found)
5182 			return 0;
5183 
5184 		/* This should never happen, as it means we tried to
5185 		 * set a mode before querying the full_pbn
5186 		 */
5187 		if (WARN_ON(!port->full_pbn))
5188 			return -EINVAL;
5189 
5190 		pbn_used = vcpi->pbn;
5191 	} else {
5192 		pbn_used = drm_dp_mst_atomic_check_mstb_bw_limit(port->mstb,
5193 								 state);
5194 		if (pbn_used <= 0)
5195 			return pbn_used;
5196 	}
5197 
5198 	if (pbn_used > port->full_pbn) {
5199 		DRM_DEBUG_ATOMIC("[MSTB:%p] [MST PORT:%p] required PBN of %d exceeds port limit of %d\n",
5200 				 port->parent, port, pbn_used,
5201 				 port->full_pbn);
5202 		return -ENOSPC;
5203 	}
5204 
5205 	DRM_DEBUG_ATOMIC("[MSTB:%p] [MST PORT:%p] uses %d out of %d PBN\n",
5206 			 port->parent, port, pbn_used, port->full_pbn);
5207 
5208 	return pbn_used;
5209 }
5210 
5211 static inline int
drm_dp_mst_atomic_check_vcpi_alloc_limit(struct drm_dp_mst_topology_mgr * mgr,struct drm_dp_mst_topology_state * mst_state)5212 drm_dp_mst_atomic_check_vcpi_alloc_limit(struct drm_dp_mst_topology_mgr *mgr,
5213 					 struct drm_dp_mst_topology_state *mst_state)
5214 {
5215 	struct drm_dp_vcpi_allocation *vcpi;
5216 	int avail_slots = 63, payload_count = 0;
5217 
5218 	list_for_each_entry(vcpi, &mst_state->vcpis, next) {
5219 		/* Releasing VCPI is always OK-even if the port is gone */
5220 		if (!vcpi->vcpi) {
5221 			DRM_DEBUG_ATOMIC("[MST PORT:%p] releases all VCPI slots\n",
5222 					 vcpi->port);
5223 			continue;
5224 		}
5225 
5226 		DRM_DEBUG_ATOMIC("[MST PORT:%p] requires %d vcpi slots\n",
5227 				 vcpi->port, vcpi->vcpi);
5228 
5229 		avail_slots -= vcpi->vcpi;
5230 		if (avail_slots < 0) {
5231 			DRM_DEBUG_ATOMIC("[MST PORT:%p] not enough VCPI slots in mst state %p (avail=%d)\n",
5232 					 vcpi->port, mst_state,
5233 					 avail_slots + vcpi->vcpi);
5234 			return -ENOSPC;
5235 		}
5236 
5237 		if (++payload_count > mgr->max_payloads) {
5238 			DRM_DEBUG_ATOMIC("[MST MGR:%p] state %p has too many payloads (max=%d)\n",
5239 					 mgr, mst_state, mgr->max_payloads);
5240 			return -EINVAL;
5241 		}
5242 	}
5243 	DRM_DEBUG_ATOMIC("[MST MGR:%p] mst state %p VCPI avail=%d used=%d\n",
5244 			 mgr, mst_state, avail_slots,
5245 			 63 - avail_slots);
5246 
5247 	return 0;
5248 }
5249 
5250 /**
5251  * drm_dp_mst_add_affected_dsc_crtcs
5252  * @state: Pointer to the new struct drm_dp_mst_topology_state
5253  * @mgr: MST topology manager
5254  *
5255  * Whenever there is a change in mst topology
5256  * DSC configuration would have to be recalculated
5257  * therefore we need to trigger modeset on all affected
5258  * CRTCs in that topology
5259  *
5260  * See also:
5261  * drm_dp_mst_atomic_enable_dsc()
5262  */
drm_dp_mst_add_affected_dsc_crtcs(struct drm_atomic_state * state,struct drm_dp_mst_topology_mgr * mgr)5263 int drm_dp_mst_add_affected_dsc_crtcs(struct drm_atomic_state *state, struct drm_dp_mst_topology_mgr *mgr)
5264 {
5265 	struct drm_dp_mst_topology_state *mst_state;
5266 	struct drm_dp_vcpi_allocation *pos;
5267 	struct drm_connector *connector;
5268 	struct drm_connector_state *conn_state;
5269 	struct drm_crtc *crtc;
5270 	struct drm_crtc_state *crtc_state;
5271 
5272 	mst_state = drm_atomic_get_mst_topology_state(state, mgr);
5273 
5274 	if (IS_ERR(mst_state))
5275 		return PTR_ERR(mst_state);
5276 
5277 	list_for_each_entry(pos, &mst_state->vcpis, next) {
5278 
5279 		connector = pos->port->connector;
5280 
5281 		if (!connector)
5282 			return -EINVAL;
5283 
5284 		conn_state = drm_atomic_get_connector_state(state, connector);
5285 
5286 		if (IS_ERR(conn_state))
5287 			return PTR_ERR(conn_state);
5288 
5289 		crtc = conn_state->crtc;
5290 
5291 		if (!crtc)
5292 			continue;
5293 
5294 		if (!drm_dp_mst_dsc_aux_for_port(pos->port))
5295 			continue;
5296 
5297 		crtc_state = drm_atomic_get_crtc_state(mst_state->base.state, crtc);
5298 
5299 		if (IS_ERR(crtc_state))
5300 			return PTR_ERR(crtc_state);
5301 
5302 		DRM_DEBUG_ATOMIC("[MST MGR:%p] Setting mode_changed flag on CRTC %p\n",
5303 				 mgr, crtc);
5304 
5305 		crtc_state->mode_changed = true;
5306 	}
5307 	return 0;
5308 }
5309 EXPORT_SYMBOL(drm_dp_mst_add_affected_dsc_crtcs);
5310 
5311 /**
5312  * drm_dp_mst_atomic_enable_dsc - Set DSC Enable Flag to On/Off
5313  * @state: Pointer to the new drm_atomic_state
5314  * @port: Pointer to the affected MST Port
5315  * @pbn: Newly recalculated bw required for link with DSC enabled
5316  * @pbn_div: Divider to calculate correct number of pbn per slot
5317  * @enable: Boolean flag to enable or disable DSC on the port
5318  *
5319  * This function enables DSC on the given Port
5320  * by recalculating its vcpi from pbn provided
5321  * and sets dsc_enable flag to keep track of which
5322  * ports have DSC enabled
5323  *
5324  */
drm_dp_mst_atomic_enable_dsc(struct drm_atomic_state * state,struct drm_dp_mst_port * port,int pbn,int pbn_div,bool enable)5325 int drm_dp_mst_atomic_enable_dsc(struct drm_atomic_state *state,
5326 				 struct drm_dp_mst_port *port,
5327 				 int pbn, int pbn_div,
5328 				 bool enable)
5329 {
5330 	struct drm_dp_mst_topology_state *mst_state;
5331 	struct drm_dp_vcpi_allocation *pos;
5332 	bool found = false;
5333 	int vcpi = 0;
5334 
5335 	mst_state = drm_atomic_get_mst_topology_state(state, port->mgr);
5336 
5337 	if (IS_ERR(mst_state))
5338 		return PTR_ERR(mst_state);
5339 
5340 	list_for_each_entry(pos, &mst_state->vcpis, next) {
5341 		if (pos->port == port) {
5342 			found = true;
5343 			break;
5344 		}
5345 	}
5346 
5347 	if (!found) {
5348 		DRM_DEBUG_ATOMIC("[MST PORT:%p] Couldn't find VCPI allocation in mst state %p\n",
5349 				 port, mst_state);
5350 		return -EINVAL;
5351 	}
5352 
5353 	if (pos->dsc_enabled == enable) {
5354 		DRM_DEBUG_ATOMIC("[MST PORT:%p] DSC flag is already set to %d, returning %d VCPI slots\n",
5355 				 port, enable, pos->vcpi);
5356 		vcpi = pos->vcpi;
5357 	}
5358 
5359 	if (enable) {
5360 		vcpi = drm_dp_atomic_find_vcpi_slots(state, port->mgr, port, pbn, pbn_div);
5361 		DRM_DEBUG_ATOMIC("[MST PORT:%p] Enabling DSC flag, reallocating %d VCPI slots on the port\n",
5362 				 port, vcpi);
5363 		if (vcpi < 0)
5364 			return -EINVAL;
5365 	}
5366 
5367 	pos->dsc_enabled = enable;
5368 
5369 	return vcpi;
5370 }
5371 EXPORT_SYMBOL(drm_dp_mst_atomic_enable_dsc);
5372 /**
5373  * drm_dp_mst_atomic_check - Check that the new state of an MST topology in an
5374  * atomic update is valid
5375  * @state: Pointer to the new &struct drm_dp_mst_topology_state
5376  *
5377  * Checks the given topology state for an atomic update to ensure that it's
5378  * valid. This includes checking whether there's enough bandwidth to support
5379  * the new VCPI allocations in the atomic update.
5380  *
5381  * Any atomic drivers supporting DP MST must make sure to call this after
5382  * checking the rest of their state in their
5383  * &drm_mode_config_funcs.atomic_check() callback.
5384  *
5385  * See also:
5386  * drm_dp_atomic_find_vcpi_slots()
5387  * drm_dp_atomic_release_vcpi_slots()
5388  *
5389  * Returns:
5390  *
5391  * 0 if the new state is valid, negative error code otherwise.
5392  */
drm_dp_mst_atomic_check(struct drm_atomic_state * state)5393 int drm_dp_mst_atomic_check(struct drm_atomic_state *state)
5394 {
5395 	struct drm_dp_mst_topology_mgr *mgr;
5396 	struct drm_dp_mst_topology_state *mst_state;
5397 	int i, ret = 0;
5398 
5399 	for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
5400 		if (!mgr->mst_state)
5401 			continue;
5402 
5403 		ret = drm_dp_mst_atomic_check_vcpi_alloc_limit(mgr, mst_state);
5404 		if (ret)
5405 			break;
5406 
5407 		mutex_lock(&mgr->lock);
5408 		ret = drm_dp_mst_atomic_check_mstb_bw_limit(mgr->mst_primary,
5409 							    mst_state);
5410 		mutex_unlock(&mgr->lock);
5411 		if (ret < 0)
5412 			break;
5413 		else
5414 			ret = 0;
5415 	}
5416 
5417 	return ret;
5418 }
5419 EXPORT_SYMBOL(drm_dp_mst_atomic_check);
5420 
5421 const struct drm_private_state_funcs drm_dp_mst_topology_state_funcs = {
5422 	.atomic_duplicate_state = drm_dp_mst_duplicate_state,
5423 	.atomic_destroy_state = drm_dp_mst_destroy_state,
5424 };
5425 EXPORT_SYMBOL(drm_dp_mst_topology_state_funcs);
5426 
5427 /**
5428  * drm_atomic_get_mst_topology_state: get MST topology state
5429  *
5430  * @state: global atomic state
5431  * @mgr: MST topology manager, also the private object in this case
5432  *
5433  * This function wraps drm_atomic_get_priv_obj_state() passing in the MST atomic
5434  * state vtable so that the private object state returned is that of a MST
5435  * topology object. Also, drm_atomic_get_private_obj_state() expects the caller
5436  * to care of the locking, so warn if don't hold the connection_mutex.
5437  *
5438  * RETURNS:
5439  *
5440  * The MST topology state or error pointer.
5441  */
drm_atomic_get_mst_topology_state(struct drm_atomic_state * state,struct drm_dp_mst_topology_mgr * mgr)5442 struct drm_dp_mst_topology_state *drm_atomic_get_mst_topology_state(struct drm_atomic_state *state,
5443 								    struct drm_dp_mst_topology_mgr *mgr)
5444 {
5445 	return to_dp_mst_topology_state(drm_atomic_get_private_obj_state(state, &mgr->base));
5446 }
5447 EXPORT_SYMBOL(drm_atomic_get_mst_topology_state);
5448 
5449 /**
5450  * drm_dp_mst_topology_mgr_init - initialise a topology manager
5451  * @mgr: manager struct to initialise
5452  * @dev: device providing this structure - for i2c addition.
5453  * @aux: DP helper aux channel to talk to this device
5454  * @max_dpcd_transaction_bytes: hw specific DPCD transaction limit
5455  * @max_payloads: maximum number of payloads this GPU can source
5456  * @conn_base_id: the connector object ID the MST device is connected to.
5457  *
5458  * Return 0 for success, or negative error code on failure
5459  */
drm_dp_mst_topology_mgr_init(struct drm_dp_mst_topology_mgr * mgr,struct drm_device * dev,struct drm_dp_aux * aux,int max_dpcd_transaction_bytes,int max_payloads,int conn_base_id)5460 int drm_dp_mst_topology_mgr_init(struct drm_dp_mst_topology_mgr *mgr,
5461 				 struct drm_device *dev, struct drm_dp_aux *aux,
5462 				 int max_dpcd_transaction_bytes,
5463 				 int max_payloads, int conn_base_id)
5464 {
5465 	struct drm_dp_mst_topology_state *mst_state;
5466 
5467 	mutex_init(&mgr->lock);
5468 	mutex_init(&mgr->qlock);
5469 	mutex_init(&mgr->payload_lock);
5470 	mutex_init(&mgr->delayed_destroy_lock);
5471 	mutex_init(&mgr->up_req_lock);
5472 	mutex_init(&mgr->probe_lock);
5473 #if IS_ENABLED(CONFIG_DRM_DEBUG_DP_MST_TOPOLOGY_REFS)
5474 	mutex_init(&mgr->topology_ref_history_lock);
5475 #endif
5476 	INIT_LIST_HEAD(&mgr->tx_msg_downq);
5477 	INIT_LIST_HEAD(&mgr->destroy_port_list);
5478 	INIT_LIST_HEAD(&mgr->destroy_branch_device_list);
5479 	INIT_LIST_HEAD(&mgr->up_req_list);
5480 
5481 	/*
5482 	 * delayed_destroy_work will be queued on a dedicated WQ, so that any
5483 	 * requeuing will be also flushed when deiniting the topology manager.
5484 	 */
5485 	mgr->delayed_destroy_wq = alloc_ordered_workqueue("drm_dp_mst_wq", 0);
5486 	if (mgr->delayed_destroy_wq == NULL)
5487 		return -ENOMEM;
5488 
5489 	INIT_WORK(&mgr->work, drm_dp_mst_link_probe_work);
5490 	INIT_WORK(&mgr->tx_work, drm_dp_tx_work);
5491 	INIT_WORK(&mgr->delayed_destroy_work, drm_dp_delayed_destroy_work);
5492 	INIT_WORK(&mgr->up_req_work, drm_dp_mst_up_req_work);
5493 	init_waitqueue_head(&mgr->tx_waitq);
5494 	mgr->dev = dev;
5495 	mgr->aux = aux;
5496 	mgr->max_dpcd_transaction_bytes = max_dpcd_transaction_bytes;
5497 	mgr->max_payloads = max_payloads;
5498 	mgr->conn_base_id = conn_base_id;
5499 	if (max_payloads + 1 > sizeof(mgr->payload_mask) * 8 ||
5500 	    max_payloads + 1 > sizeof(mgr->vcpi_mask) * 8)
5501 		return -EINVAL;
5502 	mgr->payloads = kcalloc(max_payloads, sizeof(struct drm_dp_payload), GFP_KERNEL);
5503 	if (!mgr->payloads)
5504 		return -ENOMEM;
5505 	mgr->proposed_vcpis = kcalloc(max_payloads, sizeof(struct drm_dp_vcpi *), GFP_KERNEL);
5506 	if (!mgr->proposed_vcpis)
5507 		return -ENOMEM;
5508 	set_bit(0, &mgr->payload_mask);
5509 
5510 	mst_state = kzalloc(sizeof(*mst_state), GFP_KERNEL);
5511 	if (mst_state == NULL)
5512 		return -ENOMEM;
5513 
5514 	mst_state->mgr = mgr;
5515 	INIT_LIST_HEAD(&mst_state->vcpis);
5516 
5517 	drm_atomic_private_obj_init(dev, &mgr->base,
5518 				    &mst_state->base,
5519 				    &drm_dp_mst_topology_state_funcs);
5520 
5521 	return 0;
5522 }
5523 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_init);
5524 
5525 /**
5526  * drm_dp_mst_topology_mgr_destroy() - destroy topology manager.
5527  * @mgr: manager to destroy
5528  */
drm_dp_mst_topology_mgr_destroy(struct drm_dp_mst_topology_mgr * mgr)5529 void drm_dp_mst_topology_mgr_destroy(struct drm_dp_mst_topology_mgr *mgr)
5530 {
5531 	drm_dp_mst_topology_mgr_set_mst(mgr, false);
5532 	flush_work(&mgr->work);
5533 	/* The following will also drain any requeued work on the WQ. */
5534 	if (mgr->delayed_destroy_wq) {
5535 		destroy_workqueue(mgr->delayed_destroy_wq);
5536 		mgr->delayed_destroy_wq = NULL;
5537 	}
5538 	mutex_lock(&mgr->payload_lock);
5539 	kfree(mgr->payloads);
5540 	mgr->payloads = NULL;
5541 	kfree(mgr->proposed_vcpis);
5542 	mgr->proposed_vcpis = NULL;
5543 	mutex_unlock(&mgr->payload_lock);
5544 	mgr->dev = NULL;
5545 	mgr->aux = NULL;
5546 	drm_atomic_private_obj_fini(&mgr->base);
5547 	mgr->funcs = NULL;
5548 
5549 	mutex_destroy(&mgr->delayed_destroy_lock);
5550 	mutex_destroy(&mgr->payload_lock);
5551 	mutex_destroy(&mgr->qlock);
5552 	mutex_destroy(&mgr->lock);
5553 	mutex_destroy(&mgr->up_req_lock);
5554 	mutex_destroy(&mgr->probe_lock);
5555 #if IS_ENABLED(CONFIG_DRM_DEBUG_DP_MST_TOPOLOGY_REFS)
5556 	mutex_destroy(&mgr->topology_ref_history_lock);
5557 #endif
5558 }
5559 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_destroy);
5560 
remote_i2c_read_ok(const struct i2c_msg msgs[],int num)5561 static bool remote_i2c_read_ok(const struct i2c_msg msgs[], int num)
5562 {
5563 	int i;
5564 
5565 	if (num - 1 > DP_REMOTE_I2C_READ_MAX_TRANSACTIONS)
5566 		return false;
5567 
5568 	for (i = 0; i < num - 1; i++) {
5569 		if (msgs[i].flags & I2C_M_RD ||
5570 		    msgs[i].len > 0xff)
5571 			return false;
5572 	}
5573 
5574 	return msgs[num - 1].flags & I2C_M_RD &&
5575 		msgs[num - 1].len <= 0xff;
5576 }
5577 
remote_i2c_write_ok(const struct i2c_msg msgs[],int num)5578 static bool remote_i2c_write_ok(const struct i2c_msg msgs[], int num)
5579 {
5580 	int i;
5581 
5582 	for (i = 0; i < num - 1; i++) {
5583 		if (msgs[i].flags & I2C_M_RD || !(msgs[i].flags & I2C_M_STOP) ||
5584 		    msgs[i].len > 0xff)
5585 			return false;
5586 	}
5587 
5588 	return !(msgs[num - 1].flags & I2C_M_RD) && msgs[num - 1].len <= 0xff;
5589 }
5590 
drm_dp_mst_i2c_read(struct drm_dp_mst_branch * mstb,struct drm_dp_mst_port * port,struct i2c_msg * msgs,int num)5591 static int drm_dp_mst_i2c_read(struct drm_dp_mst_branch *mstb,
5592 			       struct drm_dp_mst_port *port,
5593 			       struct i2c_msg *msgs, int num)
5594 {
5595 	struct drm_dp_mst_topology_mgr *mgr = port->mgr;
5596 	unsigned int i;
5597 	struct drm_dp_sideband_msg_req_body msg;
5598 	struct drm_dp_sideband_msg_tx *txmsg = NULL;
5599 	int ret;
5600 
5601 	memset(&msg, 0, sizeof(msg));
5602 	msg.req_type = DP_REMOTE_I2C_READ;
5603 	msg.u.i2c_read.num_transactions = num - 1;
5604 	msg.u.i2c_read.port_number = port->port_num;
5605 	for (i = 0; i < num - 1; i++) {
5606 		msg.u.i2c_read.transactions[i].i2c_dev_id = msgs[i].addr;
5607 		msg.u.i2c_read.transactions[i].num_bytes = msgs[i].len;
5608 		msg.u.i2c_read.transactions[i].bytes = msgs[i].buf;
5609 		msg.u.i2c_read.transactions[i].no_stop_bit = !(msgs[i].flags & I2C_M_STOP);
5610 	}
5611 	msg.u.i2c_read.read_i2c_device_id = msgs[num - 1].addr;
5612 	msg.u.i2c_read.num_bytes_read = msgs[num - 1].len;
5613 
5614 	txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
5615 	if (!txmsg) {
5616 		ret = -ENOMEM;
5617 		goto out;
5618 	}
5619 
5620 	txmsg->dst = mstb;
5621 	drm_dp_encode_sideband_req(&msg, txmsg);
5622 
5623 	drm_dp_queue_down_tx(mgr, txmsg);
5624 
5625 	ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
5626 	if (ret > 0) {
5627 
5628 		if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK) {
5629 			ret = -EREMOTEIO;
5630 			goto out;
5631 		}
5632 		if (txmsg->reply.u.remote_i2c_read_ack.num_bytes != msgs[num - 1].len) {
5633 			ret = -EIO;
5634 			goto out;
5635 		}
5636 		memcpy(msgs[num - 1].buf, txmsg->reply.u.remote_i2c_read_ack.bytes, msgs[num - 1].len);
5637 		ret = num;
5638 	}
5639 out:
5640 	kfree(txmsg);
5641 	return ret;
5642 }
5643 
drm_dp_mst_i2c_write(struct drm_dp_mst_branch * mstb,struct drm_dp_mst_port * port,struct i2c_msg * msgs,int num)5644 static int drm_dp_mst_i2c_write(struct drm_dp_mst_branch *mstb,
5645 				struct drm_dp_mst_port *port,
5646 				struct i2c_msg *msgs, int num)
5647 {
5648 	struct drm_dp_mst_topology_mgr *mgr = port->mgr;
5649 	unsigned int i;
5650 	struct drm_dp_sideband_msg_req_body msg;
5651 	struct drm_dp_sideband_msg_tx *txmsg = NULL;
5652 	int ret;
5653 
5654 	txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
5655 	if (!txmsg) {
5656 		ret = -ENOMEM;
5657 		goto out;
5658 	}
5659 	for (i = 0; i < num; i++) {
5660 		memset(&msg, 0, sizeof(msg));
5661 		msg.req_type = DP_REMOTE_I2C_WRITE;
5662 		msg.u.i2c_write.port_number = port->port_num;
5663 		msg.u.i2c_write.write_i2c_device_id = msgs[i].addr;
5664 		msg.u.i2c_write.num_bytes = msgs[i].len;
5665 		msg.u.i2c_write.bytes = msgs[i].buf;
5666 
5667 		memset(txmsg, 0, sizeof(*txmsg));
5668 		txmsg->dst = mstb;
5669 
5670 		drm_dp_encode_sideband_req(&msg, txmsg);
5671 		drm_dp_queue_down_tx(mgr, txmsg);
5672 
5673 		ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
5674 		if (ret > 0) {
5675 			if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK) {
5676 				ret = -EREMOTEIO;
5677 				goto out;
5678 			}
5679 		} else {
5680 			goto out;
5681 		}
5682 	}
5683 	ret = num;
5684 out:
5685 	kfree(txmsg);
5686 	return ret;
5687 }
5688 
5689 /* I2C device */
drm_dp_mst_i2c_xfer(struct i2c_adapter * adapter,struct i2c_msg * msgs,int num)5690 static int drm_dp_mst_i2c_xfer(struct i2c_adapter *adapter,
5691 			       struct i2c_msg *msgs, int num)
5692 {
5693 	struct drm_dp_aux *aux = adapter->algo_data;
5694 	struct drm_dp_mst_port *port =
5695 		container_of(aux, struct drm_dp_mst_port, aux);
5696 	struct drm_dp_mst_branch *mstb;
5697 	struct drm_dp_mst_topology_mgr *mgr = port->mgr;
5698 	int ret;
5699 
5700 	mstb = drm_dp_mst_topology_get_mstb_validated(mgr, port->parent);
5701 	if (!mstb)
5702 		return -EREMOTEIO;
5703 
5704 	if (remote_i2c_read_ok(msgs, num)) {
5705 		ret = drm_dp_mst_i2c_read(mstb, port, msgs, num);
5706 	} else if (remote_i2c_write_ok(msgs, num)) {
5707 		ret = drm_dp_mst_i2c_write(mstb, port, msgs, num);
5708 	} else {
5709 		DRM_DEBUG_KMS("Unsupported I2C transaction for MST device\n");
5710 		ret = -EIO;
5711 	}
5712 
5713 	drm_dp_mst_topology_put_mstb(mstb);
5714 	return ret;
5715 }
5716 
drm_dp_mst_i2c_functionality(struct i2c_adapter * adapter)5717 static u32 drm_dp_mst_i2c_functionality(struct i2c_adapter *adapter)
5718 {
5719 	return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
5720 	       I2C_FUNC_SMBUS_READ_BLOCK_DATA |
5721 	       I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
5722 	       I2C_FUNC_10BIT_ADDR;
5723 }
5724 
5725 static const struct i2c_algorithm drm_dp_mst_i2c_algo = {
5726 	.functionality = drm_dp_mst_i2c_functionality,
5727 	.master_xfer = drm_dp_mst_i2c_xfer,
5728 };
5729 
5730 /**
5731  * drm_dp_mst_register_i2c_bus() - register an I2C adapter for I2C-over-AUX
5732  * @port: The port to add the I2C bus on
5733  *
5734  * Returns 0 on success or a negative error code on failure.
5735  */
drm_dp_mst_register_i2c_bus(struct drm_dp_mst_port * port)5736 static int drm_dp_mst_register_i2c_bus(struct drm_dp_mst_port *port)
5737 {
5738 	struct drm_dp_aux *aux = &port->aux;
5739 	struct device *parent_dev = port->mgr->dev->dev;
5740 
5741 	aux->ddc.algo = &drm_dp_mst_i2c_algo;
5742 	aux->ddc.algo_data = aux;
5743 	aux->ddc.retries = 3;
5744 
5745 	aux->ddc.class = I2C_CLASS_DDC;
5746 	aux->ddc.owner = THIS_MODULE;
5747 	/* FIXME: set the kdev of the port's connector as parent */
5748 	aux->ddc.dev.parent = parent_dev;
5749 	aux->ddc.dev.of_node = parent_dev->of_node;
5750 
5751 	strlcpy(aux->ddc.name, aux->name ? aux->name : dev_name(parent_dev),
5752 		sizeof(aux->ddc.name));
5753 
5754 	return i2c_add_adapter(&aux->ddc);
5755 }
5756 
5757 /**
5758  * drm_dp_mst_unregister_i2c_bus() - unregister an I2C-over-AUX adapter
5759  * @port: The port to remove the I2C bus from
5760  */
drm_dp_mst_unregister_i2c_bus(struct drm_dp_mst_port * port)5761 static void drm_dp_mst_unregister_i2c_bus(struct drm_dp_mst_port *port)
5762 {
5763 	i2c_del_adapter(&port->aux.ddc);
5764 }
5765 
5766 /**
5767  * drm_dp_mst_is_virtual_dpcd() - Is the given port a virtual DP Peer Device
5768  * @port: The port to check
5769  *
5770  * A single physical MST hub object can be represented in the topology
5771  * by multiple branches, with virtual ports between those branches.
5772  *
5773  * As of DP1.4, An MST hub with internal (virtual) ports must expose
5774  * certain DPCD registers over those ports. See sections 2.6.1.1.1
5775  * and 2.6.1.1.2 of Display Port specification v1.4 for details.
5776  *
5777  * May acquire mgr->lock
5778  *
5779  * Returns:
5780  * true if the port is a virtual DP peer device, false otherwise
5781  */
drm_dp_mst_is_virtual_dpcd(struct drm_dp_mst_port * port)5782 static bool drm_dp_mst_is_virtual_dpcd(struct drm_dp_mst_port *port)
5783 {
5784 	struct drm_dp_mst_port *downstream_port;
5785 
5786 	if (!port || port->dpcd_rev < DP_DPCD_REV_14)
5787 		return false;
5788 
5789 	/* Virtual DP Sink (Internal Display Panel) */
5790 	if (port->port_num >= 8)
5791 		return true;
5792 
5793 	/* DP-to-HDMI Protocol Converter */
5794 	if (port->pdt == DP_PEER_DEVICE_DP_LEGACY_CONV &&
5795 	    !port->mcs &&
5796 	    port->ldps)
5797 		return true;
5798 
5799 	/* DP-to-DP */
5800 	mutex_lock(&port->mgr->lock);
5801 	if (port->pdt == DP_PEER_DEVICE_MST_BRANCHING &&
5802 	    port->mstb &&
5803 	    port->mstb->num_ports == 2) {
5804 		list_for_each_entry(downstream_port, &port->mstb->ports, next) {
5805 			if (downstream_port->pdt == DP_PEER_DEVICE_SST_SINK &&
5806 			    !downstream_port->input) {
5807 				mutex_unlock(&port->mgr->lock);
5808 				return true;
5809 			}
5810 		}
5811 	}
5812 	mutex_unlock(&port->mgr->lock);
5813 
5814 	return false;
5815 }
5816 
5817 /**
5818  * drm_dp_mst_dsc_aux_for_port() - Find the correct aux for DSC
5819  * @port: The port to check. A leaf of the MST tree with an attached display.
5820  *
5821  * Depending on the situation, DSC may be enabled via the endpoint aux,
5822  * the immediately upstream aux, or the connector's physical aux.
5823  *
5824  * This is both the correct aux to read DSC_CAPABILITY and the
5825  * correct aux to write DSC_ENABLED.
5826  *
5827  * This operation can be expensive (up to four aux reads), so
5828  * the caller should cache the return.
5829  *
5830  * Returns:
5831  * NULL if DSC cannot be enabled on this port, otherwise the aux device
5832  */
drm_dp_mst_dsc_aux_for_port(struct drm_dp_mst_port * port)5833 struct drm_dp_aux *drm_dp_mst_dsc_aux_for_port(struct drm_dp_mst_port *port)
5834 {
5835 	struct drm_dp_mst_port *immediate_upstream_port;
5836 	struct drm_dp_mst_port *fec_port;
5837 	struct drm_dp_desc desc = {};
5838 	u8 endpoint_fec;
5839 	u8 endpoint_dsc;
5840 
5841 	if (!port)
5842 		return NULL;
5843 
5844 	if (port->parent->port_parent)
5845 		immediate_upstream_port = port->parent->port_parent;
5846 	else
5847 		immediate_upstream_port = NULL;
5848 
5849 	fec_port = immediate_upstream_port;
5850 	while (fec_port) {
5851 		/*
5852 		 * Each physical link (i.e. not a virtual port) between the
5853 		 * output and the primary device must support FEC
5854 		 */
5855 		if (!drm_dp_mst_is_virtual_dpcd(fec_port) &&
5856 		    !fec_port->fec_capable)
5857 			return NULL;
5858 
5859 		fec_port = fec_port->parent->port_parent;
5860 	}
5861 
5862 	/* DP-to-DP peer device */
5863 	if (drm_dp_mst_is_virtual_dpcd(immediate_upstream_port)) {
5864 		u8 upstream_dsc;
5865 
5866 		if (drm_dp_dpcd_read(&port->aux,
5867 				     DP_DSC_SUPPORT, &endpoint_dsc, 1) != 1)
5868 			return NULL;
5869 		if (drm_dp_dpcd_read(&port->aux,
5870 				     DP_FEC_CAPABILITY, &endpoint_fec, 1) != 1)
5871 			return NULL;
5872 		if (drm_dp_dpcd_read(&immediate_upstream_port->aux,
5873 				     DP_DSC_SUPPORT, &upstream_dsc, 1) != 1)
5874 			return NULL;
5875 
5876 		/* Enpoint decompression with DP-to-DP peer device */
5877 		if ((endpoint_dsc & DP_DSC_DECOMPRESSION_IS_SUPPORTED) &&
5878 		    (endpoint_fec & DP_FEC_CAPABLE) &&
5879 		    (upstream_dsc & 0x2) /* DSC passthrough */)
5880 			return &port->aux;
5881 
5882 		/* Virtual DPCD decompression with DP-to-DP peer device */
5883 		return &immediate_upstream_port->aux;
5884 	}
5885 
5886 	/* Virtual DPCD decompression with DP-to-HDMI or Virtual DP Sink */
5887 	if (drm_dp_mst_is_virtual_dpcd(port))
5888 		return &port->aux;
5889 
5890 	/*
5891 	 * Synaptics quirk
5892 	 * Applies to ports for which:
5893 	 * - Physical aux has Synaptics OUI
5894 	 * - DPv1.4 or higher
5895 	 * - Port is on primary branch device
5896 	 * - Not a VGA adapter (DP_DWN_STRM_PORT_TYPE_ANALOG)
5897 	 */
5898 	if (drm_dp_read_desc(port->mgr->aux, &desc, true))
5899 		return NULL;
5900 
5901 	if (drm_dp_has_quirk(&desc, 0,
5902 			     DP_DPCD_QUIRK_DSC_WITHOUT_VIRTUAL_DPCD) &&
5903 	    port->mgr->dpcd[DP_DPCD_REV] >= DP_DPCD_REV_14 &&
5904 	    port->parent == port->mgr->mst_primary) {
5905 		u8 downstreamport;
5906 
5907 		if (drm_dp_dpcd_read(&port->aux, DP_DOWNSTREAMPORT_PRESENT,
5908 				     &downstreamport, 1) < 0)
5909 			return NULL;
5910 
5911 		if ((downstreamport & DP_DWN_STRM_PORT_PRESENT) &&
5912 		   ((downstreamport & DP_DWN_STRM_PORT_TYPE_MASK)
5913 		     != DP_DWN_STRM_PORT_TYPE_ANALOG))
5914 			return port->mgr->aux;
5915 	}
5916 
5917 	/*
5918 	 * The check below verifies if the MST sink
5919 	 * connected to the GPU is capable of DSC -
5920 	 * therefore the endpoint needs to be
5921 	 * both DSC and FEC capable.
5922 	 */
5923 	if (drm_dp_dpcd_read(&port->aux,
5924 	   DP_DSC_SUPPORT, &endpoint_dsc, 1) != 1)
5925 		return NULL;
5926 	if (drm_dp_dpcd_read(&port->aux,
5927 	   DP_FEC_CAPABILITY, &endpoint_fec, 1) != 1)
5928 		return NULL;
5929 	if ((endpoint_dsc & DP_DSC_DECOMPRESSION_IS_SUPPORTED) &&
5930 	   (endpoint_fec & DP_FEC_CAPABLE))
5931 		return &port->aux;
5932 
5933 	return NULL;
5934 }
5935 EXPORT_SYMBOL(drm_dp_mst_dsc_aux_for_port);
5936