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