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