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