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