Backmerge remote-tracking branch 'drm/drm-next' into drm-misc-next
[platform/kernel/linux-rpi.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) {
3418                 if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK)
3419                         ret = -EIO;
3420                 else
3421                         ret = size;
3422         }
3423
3424         kfree(txmsg);
3425 fail_put:
3426         drm_dp_mst_topology_put_mstb(mstb);
3427         return ret;
3428 }
3429
3430 static int drm_dp_encode_up_ack_reply(struct drm_dp_sideband_msg_tx *msg, u8 req_type)
3431 {
3432         struct drm_dp_sideband_msg_reply_body reply;
3433
3434         reply.reply_type = DP_SIDEBAND_REPLY_ACK;
3435         reply.req_type = req_type;
3436         drm_dp_encode_sideband_reply(&reply, msg);
3437         return 0;
3438 }
3439
3440 static int drm_dp_send_up_ack_reply(struct drm_dp_mst_topology_mgr *mgr,
3441                                     struct drm_dp_mst_branch *mstb,
3442                                     int req_type, bool broadcast)
3443 {
3444         struct drm_dp_sideband_msg_tx *txmsg;
3445
3446         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
3447         if (!txmsg)
3448                 return -ENOMEM;
3449
3450         txmsg->dst = mstb;
3451         drm_dp_encode_up_ack_reply(txmsg, req_type);
3452
3453         mutex_lock(&mgr->qlock);
3454         /* construct a chunk from the first msg in the tx_msg queue */
3455         process_single_tx_qlock(mgr, txmsg, true);
3456         mutex_unlock(&mgr->qlock);
3457
3458         kfree(txmsg);
3459         return 0;
3460 }
3461
3462 static int drm_dp_get_vc_payload_bw(u8 dp_link_bw, u8  dp_link_count)
3463 {
3464         if (dp_link_bw == 0 || dp_link_count == 0)
3465                 DRM_DEBUG_KMS("invalid link bandwidth in DPCD: %x (link count: %d)\n",
3466                               dp_link_bw, dp_link_count);
3467
3468         return dp_link_bw * dp_link_count / 2;
3469 }
3470
3471 /**
3472  * drm_dp_mst_topology_mgr_set_mst() - Set the MST state for a topology manager
3473  * @mgr: manager to set state for
3474  * @mst_state: true to enable MST on this connector - false to disable.
3475  *
3476  * This is called by the driver when it detects an MST capable device plugged
3477  * into a DP MST capable port, or when a DP MST capable device is unplugged.
3478  */
3479 int drm_dp_mst_topology_mgr_set_mst(struct drm_dp_mst_topology_mgr *mgr, bool mst_state)
3480 {
3481         int ret = 0;
3482         struct drm_dp_mst_branch *mstb = NULL;
3483
3484         mutex_lock(&mgr->payload_lock);
3485         mutex_lock(&mgr->lock);
3486         if (mst_state == mgr->mst_state)
3487                 goto out_unlock;
3488
3489         mgr->mst_state = mst_state;
3490         /* set the device into MST mode */
3491         if (mst_state) {
3492                 struct drm_dp_payload reset_pay;
3493
3494                 WARN_ON(mgr->mst_primary);
3495
3496                 /* get dpcd info */
3497                 ret = drm_dp_dpcd_read(mgr->aux, DP_DPCD_REV, mgr->dpcd, DP_RECEIVER_CAP_SIZE);
3498                 if (ret != DP_RECEIVER_CAP_SIZE) {
3499                         DRM_DEBUG_KMS("failed to read DPCD\n");
3500                         goto out_unlock;
3501                 }
3502
3503                 mgr->pbn_div = drm_dp_get_vc_payload_bw(mgr->dpcd[1],
3504                                                         mgr->dpcd[2] & DP_MAX_LANE_COUNT_MASK);
3505                 if (mgr->pbn_div == 0) {
3506                         ret = -EINVAL;
3507                         goto out_unlock;
3508                 }
3509
3510                 /* add initial branch device at LCT 1 */
3511                 mstb = drm_dp_add_mst_branch_device(1, NULL);
3512                 if (mstb == NULL) {
3513                         ret = -ENOMEM;
3514                         goto out_unlock;
3515                 }
3516                 mstb->mgr = mgr;
3517
3518                 /* give this the main reference */
3519                 mgr->mst_primary = mstb;
3520                 drm_dp_mst_topology_get_mstb(mgr->mst_primary);
3521
3522                 ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3523                                          DP_MST_EN |
3524                                          DP_UP_REQ_EN |
3525                                          DP_UPSTREAM_IS_SRC);
3526                 if (ret < 0)
3527                         goto out_unlock;
3528
3529                 reset_pay.start_slot = 0;
3530                 reset_pay.num_slots = 0x3f;
3531                 drm_dp_dpcd_write_payload(mgr, 0, &reset_pay);
3532
3533                 queue_work(system_long_wq, &mgr->work);
3534
3535                 ret = 0;
3536         } else {
3537                 /* disable MST on the device */
3538                 mstb = mgr->mst_primary;
3539                 mgr->mst_primary = NULL;
3540                 /* this can fail if the device is gone */
3541                 drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL, 0);
3542                 ret = 0;
3543                 memset(mgr->payloads, 0,
3544                        mgr->max_payloads * sizeof(mgr->payloads[0]));
3545                 memset(mgr->proposed_vcpis, 0,
3546                        mgr->max_payloads * sizeof(mgr->proposed_vcpis[0]));
3547                 mgr->payload_mask = 0;
3548                 set_bit(0, &mgr->payload_mask);
3549                 mgr->vcpi_mask = 0;
3550                 mgr->payload_id_table_cleared = false;
3551         }
3552
3553 out_unlock:
3554         mutex_unlock(&mgr->lock);
3555         mutex_unlock(&mgr->payload_lock);
3556         if (mstb)
3557                 drm_dp_mst_topology_put_mstb(mstb);
3558         return ret;
3559
3560 }
3561 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_set_mst);
3562
3563 static void
3564 drm_dp_mst_topology_mgr_invalidate_mstb(struct drm_dp_mst_branch *mstb)
3565 {
3566         struct drm_dp_mst_port *port;
3567
3568         /* The link address will need to be re-sent on resume */
3569         mstb->link_address_sent = false;
3570
3571         list_for_each_entry(port, &mstb->ports, next)
3572                 if (port->mstb)
3573                         drm_dp_mst_topology_mgr_invalidate_mstb(port->mstb);
3574 }
3575
3576 /**
3577  * drm_dp_mst_topology_mgr_suspend() - suspend the MST manager
3578  * @mgr: manager to suspend
3579  *
3580  * This function tells the MST device that we can't handle UP messages
3581  * anymore. This should stop it from sending any since we are suspended.
3582  */
3583 void drm_dp_mst_topology_mgr_suspend(struct drm_dp_mst_topology_mgr *mgr)
3584 {
3585         mutex_lock(&mgr->lock);
3586         drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3587                            DP_MST_EN | DP_UPSTREAM_IS_SRC);
3588         mutex_unlock(&mgr->lock);
3589         flush_work(&mgr->up_req_work);
3590         flush_work(&mgr->work);
3591         flush_work(&mgr->delayed_destroy_work);
3592
3593         mutex_lock(&mgr->lock);
3594         if (mgr->mst_state && mgr->mst_primary)
3595                 drm_dp_mst_topology_mgr_invalidate_mstb(mgr->mst_primary);
3596         mutex_unlock(&mgr->lock);
3597 }
3598 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_suspend);
3599
3600 /**
3601  * drm_dp_mst_topology_mgr_resume() - resume the MST manager
3602  * @mgr: manager to resume
3603  * @sync: whether or not to perform topology reprobing synchronously
3604  *
3605  * This will fetch DPCD and see if the device is still there,
3606  * if it is, it will rewrite the MSTM control bits, and return.
3607  *
3608  * If the device fails this returns -1, and the driver should do
3609  * a full MST reprobe, in case we were undocked.
3610  *
3611  * During system resume (where it is assumed that the driver will be calling
3612  * drm_atomic_helper_resume()) this function should be called beforehand with
3613  * @sync set to true. In contexts like runtime resume where the driver is not
3614  * expected to be calling drm_atomic_helper_resume(), this function should be
3615  * called with @sync set to false in order to avoid deadlocking.
3616  *
3617  * Returns: -1 if the MST topology was removed while we were suspended, 0
3618  * otherwise.
3619  */
3620 int drm_dp_mst_topology_mgr_resume(struct drm_dp_mst_topology_mgr *mgr,
3621                                    bool sync)
3622 {
3623         int ret;
3624         u8 guid[16];
3625
3626         mutex_lock(&mgr->lock);
3627         if (!mgr->mst_primary)
3628                 goto out_fail;
3629
3630         ret = drm_dp_dpcd_read(mgr->aux, DP_DPCD_REV, mgr->dpcd,
3631                                DP_RECEIVER_CAP_SIZE);
3632         if (ret != DP_RECEIVER_CAP_SIZE) {
3633                 DRM_DEBUG_KMS("dpcd read failed - undocked during suspend?\n");
3634                 goto out_fail;
3635         }
3636
3637         ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3638                                  DP_MST_EN |
3639                                  DP_UP_REQ_EN |
3640                                  DP_UPSTREAM_IS_SRC);
3641         if (ret < 0) {
3642                 DRM_DEBUG_KMS("mst write failed - undocked during suspend?\n");
3643                 goto out_fail;
3644         }
3645
3646         /* Some hubs forget their guids after they resume */
3647         ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, guid, 16);
3648         if (ret != 16) {
3649                 DRM_DEBUG_KMS("dpcd read failed - undocked during suspend?\n");
3650                 goto out_fail;
3651         }
3652
3653         ret = drm_dp_check_mstb_guid(mgr->mst_primary, guid);
3654         if (ret) {
3655                 DRM_DEBUG_KMS("check mstb failed - undocked during suspend?\n");
3656                 goto out_fail;
3657         }
3658
3659         /*
3660          * For the final step of resuming the topology, we need to bring the
3661          * state of our in-memory topology back into sync with reality. So,
3662          * restart the probing process as if we're probing a new hub
3663          */
3664         queue_work(system_long_wq, &mgr->work);
3665         mutex_unlock(&mgr->lock);
3666
3667         if (sync) {
3668                 DRM_DEBUG_KMS("Waiting for link probe work to finish re-syncing topology...\n");
3669                 flush_work(&mgr->work);
3670         }
3671
3672         return 0;
3673
3674 out_fail:
3675         mutex_unlock(&mgr->lock);
3676         return -1;
3677 }
3678 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_resume);
3679
3680 static bool
3681 drm_dp_get_one_sb_msg(struct drm_dp_mst_topology_mgr *mgr, bool up,
3682                       struct drm_dp_mst_branch **mstb)
3683 {
3684         int len;
3685         u8 replyblock[32];
3686         int replylen, curreply;
3687         int ret;
3688         u8 hdrlen;
3689         struct drm_dp_sideband_msg_hdr hdr;
3690         struct drm_dp_sideband_msg_rx *msg =
3691                 up ? &mgr->up_req_recv : &mgr->down_rep_recv;
3692         int basereg = up ? DP_SIDEBAND_MSG_UP_REQ_BASE :
3693                            DP_SIDEBAND_MSG_DOWN_REP_BASE;
3694
3695         if (!up)
3696                 *mstb = NULL;
3697
3698         len = min(mgr->max_dpcd_transaction_bytes, 16);
3699         ret = drm_dp_dpcd_read(mgr->aux, basereg, replyblock, len);
3700         if (ret != len) {
3701                 DRM_DEBUG_KMS("failed to read DPCD down rep %d %d\n", len, ret);
3702                 return false;
3703         }
3704
3705         ret = drm_dp_decode_sideband_msg_hdr(&hdr, replyblock, len, &hdrlen);
3706         if (ret == false) {
3707                 print_hex_dump(KERN_DEBUG, "failed hdr", DUMP_PREFIX_NONE, 16,
3708                                1, replyblock, len, false);
3709                 DRM_DEBUG_KMS("ERROR: failed header\n");
3710                 return false;
3711         }
3712
3713         if (!up) {
3714                 /* Caller is responsible for giving back this reference */
3715                 *mstb = drm_dp_get_mst_branch_device(mgr, hdr.lct, hdr.rad);
3716                 if (!*mstb) {
3717                         DRM_DEBUG_KMS("Got MST reply from unknown device %d\n",
3718                                       hdr.lct);
3719                         return false;
3720                 }
3721         }
3722
3723         if (!drm_dp_sideband_msg_set_header(msg, &hdr, hdrlen)) {
3724                 DRM_DEBUG_KMS("sideband msg set header failed %d\n",
3725                               replyblock[0]);
3726                 return false;
3727         }
3728
3729         replylen = min(msg->curchunk_len, (u8)(len - hdrlen));
3730         ret = drm_dp_sideband_append_payload(msg, replyblock + hdrlen, replylen);
3731         if (!ret) {
3732                 DRM_DEBUG_KMS("sideband msg build failed %d\n", replyblock[0]);
3733                 return false;
3734         }
3735
3736         replylen = msg->curchunk_len + msg->curchunk_hdrlen - len;
3737         curreply = len;
3738         while (replylen > 0) {
3739                 len = min3(replylen, mgr->max_dpcd_transaction_bytes, 16);
3740                 ret = drm_dp_dpcd_read(mgr->aux, basereg + curreply,
3741                                     replyblock, len);
3742                 if (ret != len) {
3743                         DRM_DEBUG_KMS("failed to read a chunk (len %d, ret %d)\n",
3744                                       len, ret);
3745                         return false;
3746                 }
3747
3748                 ret = drm_dp_sideband_append_payload(msg, replyblock, len);
3749                 if (!ret) {
3750                         DRM_DEBUG_KMS("failed to build sideband msg\n");
3751                         return false;
3752                 }
3753
3754                 curreply += len;
3755                 replylen -= len;
3756         }
3757         return true;
3758 }
3759
3760 static int drm_dp_mst_handle_down_rep(struct drm_dp_mst_topology_mgr *mgr)
3761 {
3762         struct drm_dp_sideband_msg_tx *txmsg;
3763         struct drm_dp_mst_branch *mstb = NULL;
3764         struct drm_dp_sideband_msg_rx *msg = &mgr->down_rep_recv;
3765
3766         if (!drm_dp_get_one_sb_msg(mgr, false, &mstb))
3767                 goto out;
3768
3769         /* Multi-packet message transmission, don't clear the reply */
3770         if (!msg->have_eomt)
3771                 goto out;
3772
3773         /* find the message */
3774         mutex_lock(&mgr->qlock);
3775         txmsg = list_first_entry_or_null(&mgr->tx_msg_downq,
3776                                          struct drm_dp_sideband_msg_tx, next);
3777         mutex_unlock(&mgr->qlock);
3778
3779         /* Were we actually expecting a response, and from this mstb? */
3780         if (!txmsg || txmsg->dst != mstb) {
3781                 struct drm_dp_sideband_msg_hdr *hdr;
3782                 hdr = &msg->initial_hdr;
3783                 DRM_DEBUG_KMS("Got MST reply with no msg %p %d %d %02x %02x\n",
3784                               mstb, hdr->seqno, hdr->lct, hdr->rad[0],
3785                               msg->msg[0]);
3786                 goto out_clear_reply;
3787         }
3788
3789         drm_dp_sideband_parse_reply(msg, &txmsg->reply);
3790
3791         if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK) {
3792                 DRM_DEBUG_KMS("Got NAK reply: req 0x%02x (%s), reason 0x%02x (%s), nak data 0x%02x\n",
3793                               txmsg->reply.req_type,
3794                               drm_dp_mst_req_type_str(txmsg->reply.req_type),
3795                               txmsg->reply.u.nak.reason,
3796                               drm_dp_mst_nak_reason_str(txmsg->reply.u.nak.reason),
3797                               txmsg->reply.u.nak.nak_data);
3798         }
3799
3800         memset(msg, 0, sizeof(struct drm_dp_sideband_msg_rx));
3801         drm_dp_mst_topology_put_mstb(mstb);
3802
3803         mutex_lock(&mgr->qlock);
3804         txmsg->state = DRM_DP_SIDEBAND_TX_RX;
3805         list_del(&txmsg->next);
3806         mutex_unlock(&mgr->qlock);
3807
3808         wake_up_all(&mgr->tx_waitq);
3809
3810         return 0;
3811
3812 out_clear_reply:
3813         memset(msg, 0, sizeof(struct drm_dp_sideband_msg_rx));
3814 out:
3815         if (mstb)
3816                 drm_dp_mst_topology_put_mstb(mstb);
3817
3818         return 0;
3819 }
3820
3821 static inline bool
3822 drm_dp_mst_process_up_req(struct drm_dp_mst_topology_mgr *mgr,
3823                           struct drm_dp_pending_up_req *up_req)
3824 {
3825         struct drm_dp_mst_branch *mstb = NULL;
3826         struct drm_dp_sideband_msg_req_body *msg = &up_req->msg;
3827         struct drm_dp_sideband_msg_hdr *hdr = &up_req->hdr;
3828         bool hotplug = false;
3829
3830         if (hdr->broadcast) {
3831                 const u8 *guid = NULL;
3832
3833                 if (msg->req_type == DP_CONNECTION_STATUS_NOTIFY)
3834                         guid = msg->u.conn_stat.guid;
3835                 else if (msg->req_type == DP_RESOURCE_STATUS_NOTIFY)
3836                         guid = msg->u.resource_stat.guid;
3837
3838                 if (guid)
3839                         mstb = drm_dp_get_mst_branch_device_by_guid(mgr, guid);
3840         } else {
3841                 mstb = drm_dp_get_mst_branch_device(mgr, hdr->lct, hdr->rad);
3842         }
3843
3844         if (!mstb) {
3845                 DRM_DEBUG_KMS("Got MST reply from unknown device %d\n",
3846                               hdr->lct);
3847                 return false;
3848         }
3849
3850         /* TODO: Add missing handler for DP_RESOURCE_STATUS_NOTIFY events */
3851         if (msg->req_type == DP_CONNECTION_STATUS_NOTIFY) {
3852                 drm_dp_mst_handle_conn_stat(mstb, &msg->u.conn_stat);
3853                 hotplug = true;
3854         }
3855
3856         drm_dp_mst_topology_put_mstb(mstb);
3857         return hotplug;
3858 }
3859
3860 static void drm_dp_mst_up_req_work(struct work_struct *work)
3861 {
3862         struct drm_dp_mst_topology_mgr *mgr =
3863                 container_of(work, struct drm_dp_mst_topology_mgr,
3864                              up_req_work);
3865         struct drm_dp_pending_up_req *up_req;
3866         bool send_hotplug = false;
3867
3868         mutex_lock(&mgr->probe_lock);
3869         while (true) {
3870                 mutex_lock(&mgr->up_req_lock);
3871                 up_req = list_first_entry_or_null(&mgr->up_req_list,
3872                                                   struct drm_dp_pending_up_req,
3873                                                   next);
3874                 if (up_req)
3875                         list_del(&up_req->next);
3876                 mutex_unlock(&mgr->up_req_lock);
3877
3878                 if (!up_req)
3879                         break;
3880
3881                 send_hotplug |= drm_dp_mst_process_up_req(mgr, up_req);
3882                 kfree(up_req);
3883         }
3884         mutex_unlock(&mgr->probe_lock);
3885
3886         if (send_hotplug)
3887                 drm_kms_helper_hotplug_event(mgr->dev);
3888 }
3889
3890 static int drm_dp_mst_handle_up_req(struct drm_dp_mst_topology_mgr *mgr)
3891 {
3892         struct drm_dp_pending_up_req *up_req;
3893
3894         if (!drm_dp_get_one_sb_msg(mgr, true, NULL))
3895                 goto out;
3896
3897         if (!mgr->up_req_recv.have_eomt)
3898                 return 0;
3899
3900         up_req = kzalloc(sizeof(*up_req), GFP_KERNEL);
3901         if (!up_req) {
3902                 DRM_ERROR("Not enough memory to process MST up req\n");
3903                 return -ENOMEM;
3904         }
3905         INIT_LIST_HEAD(&up_req->next);
3906
3907         drm_dp_sideband_parse_req(&mgr->up_req_recv, &up_req->msg);
3908
3909         if (up_req->msg.req_type != DP_CONNECTION_STATUS_NOTIFY &&
3910             up_req->msg.req_type != DP_RESOURCE_STATUS_NOTIFY) {
3911                 DRM_DEBUG_KMS("Received unknown up req type, ignoring: %x\n",
3912                               up_req->msg.req_type);
3913                 kfree(up_req);
3914                 goto out;
3915         }
3916
3917         drm_dp_send_up_ack_reply(mgr, mgr->mst_primary, up_req->msg.req_type,
3918                                  false);
3919
3920         if (up_req->msg.req_type == DP_CONNECTION_STATUS_NOTIFY) {
3921                 const struct drm_dp_connection_status_notify *conn_stat =
3922                         &up_req->msg.u.conn_stat;
3923
3924                 DRM_DEBUG_KMS("Got CSN: pn: %d ldps:%d ddps: %d mcs: %d ip: %d pdt: %d\n",
3925                               conn_stat->port_number,
3926                               conn_stat->legacy_device_plug_status,
3927                               conn_stat->displayport_device_plug_status,
3928                               conn_stat->message_capability_status,
3929                               conn_stat->input_port,
3930                               conn_stat->peer_device_type);
3931         } else if (up_req->msg.req_type == DP_RESOURCE_STATUS_NOTIFY) {
3932                 const struct drm_dp_resource_status_notify *res_stat =
3933                         &up_req->msg.u.resource_stat;
3934
3935                 DRM_DEBUG_KMS("Got RSN: pn: %d avail_pbn %d\n",
3936                               res_stat->port_number,
3937                               res_stat->available_pbn);
3938         }
3939
3940         up_req->hdr = mgr->up_req_recv.initial_hdr;
3941         mutex_lock(&mgr->up_req_lock);
3942         list_add_tail(&up_req->next, &mgr->up_req_list);
3943         mutex_unlock(&mgr->up_req_lock);
3944         queue_work(system_long_wq, &mgr->up_req_work);
3945
3946 out:
3947         memset(&mgr->up_req_recv, 0, sizeof(struct drm_dp_sideband_msg_rx));
3948         return 0;
3949 }
3950
3951 /**
3952  * drm_dp_mst_hpd_irq() - MST hotplug IRQ notify
3953  * @mgr: manager to notify irq for.
3954  * @esi: 4 bytes from SINK_COUNT_ESI
3955  * @handled: whether the hpd interrupt was consumed or not
3956  *
3957  * This should be called from the driver when it detects a short IRQ,
3958  * along with the value of the DEVICE_SERVICE_IRQ_VECTOR_ESI0. The
3959  * topology manager will process the sideband messages received as a result
3960  * of this.
3961  */
3962 int drm_dp_mst_hpd_irq(struct drm_dp_mst_topology_mgr *mgr, u8 *esi, bool *handled)
3963 {
3964         int ret = 0;
3965         int sc;
3966         *handled = false;
3967         sc = esi[0] & 0x3f;
3968
3969         if (sc != mgr->sink_count) {
3970                 mgr->sink_count = sc;
3971                 *handled = true;
3972         }
3973
3974         if (esi[1] & DP_DOWN_REP_MSG_RDY) {
3975                 ret = drm_dp_mst_handle_down_rep(mgr);
3976                 *handled = true;
3977         }
3978
3979         if (esi[1] & DP_UP_REQ_MSG_RDY) {
3980                 ret |= drm_dp_mst_handle_up_req(mgr);
3981                 *handled = true;
3982         }
3983
3984         drm_dp_mst_kick_tx(mgr);
3985         return ret;
3986 }
3987 EXPORT_SYMBOL(drm_dp_mst_hpd_irq);
3988
3989 /**
3990  * drm_dp_mst_detect_port() - get connection status for an MST port
3991  * @connector: DRM connector for this port
3992  * @ctx: The acquisition context to use for grabbing locks
3993  * @mgr: manager for this port
3994  * @port: pointer to a port
3995  *
3996  * This returns the current connection state for a port.
3997  */
3998 int
3999 drm_dp_mst_detect_port(struct drm_connector *connector,
4000                        struct drm_modeset_acquire_ctx *ctx,
4001                        struct drm_dp_mst_topology_mgr *mgr,
4002                        struct drm_dp_mst_port *port)
4003 {
4004         int ret;
4005
4006         /* we need to search for the port in the mgr in case it's gone */
4007         port = drm_dp_mst_topology_get_port_validated(mgr, port);
4008         if (!port)
4009                 return connector_status_disconnected;
4010
4011         ret = drm_modeset_lock(&mgr->base.lock, ctx);
4012         if (ret)
4013                 goto out;
4014
4015         ret = connector_status_disconnected;
4016
4017         if (!port->ddps)
4018                 goto out;
4019
4020         switch (port->pdt) {
4021         case DP_PEER_DEVICE_NONE:
4022         case DP_PEER_DEVICE_MST_BRANCHING:
4023                 if (!port->mcs)
4024                         ret = connector_status_connected;
4025                 break;
4026
4027         case DP_PEER_DEVICE_SST_SINK:
4028                 ret = connector_status_connected;
4029                 /* for logical ports - cache the EDID */
4030                 if (port->port_num >= 8 && !port->cached_edid) {
4031                         port->cached_edid = drm_get_edid(connector, &port->aux.ddc);
4032                 }
4033                 break;
4034         case DP_PEER_DEVICE_DP_LEGACY_CONV:
4035                 if (port->ldps)
4036                         ret = connector_status_connected;
4037                 break;
4038         }
4039 out:
4040         drm_dp_mst_topology_put_port(port);
4041         return ret;
4042 }
4043 EXPORT_SYMBOL(drm_dp_mst_detect_port);
4044
4045 /**
4046  * drm_dp_mst_get_edid() - get EDID for an MST port
4047  * @connector: toplevel connector to get EDID for
4048  * @mgr: manager for this port
4049  * @port: unverified pointer to a port.
4050  *
4051  * This returns an EDID for the port connected to a connector,
4052  * It validates the pointer still exists so the caller doesn't require a
4053  * reference.
4054  */
4055 struct edid *drm_dp_mst_get_edid(struct drm_connector *connector, struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
4056 {
4057         struct edid *edid = NULL;
4058
4059         /* we need to search for the port in the mgr in case it's gone */
4060         port = drm_dp_mst_topology_get_port_validated(mgr, port);
4061         if (!port)
4062                 return NULL;
4063
4064         if (port->cached_edid)
4065                 edid = drm_edid_duplicate(port->cached_edid);
4066         else {
4067                 edid = drm_get_edid(connector, &port->aux.ddc);
4068         }
4069         port->has_audio = drm_detect_monitor_audio(edid);
4070         drm_dp_mst_topology_put_port(port);
4071         return edid;
4072 }
4073 EXPORT_SYMBOL(drm_dp_mst_get_edid);
4074
4075 /**
4076  * drm_dp_find_vcpi_slots() - Find VCPI slots for this PBN value
4077  * @mgr: manager to use
4078  * @pbn: payload bandwidth to convert into slots.
4079  *
4080  * Calculate the number of VCPI slots that will be required for the given PBN
4081  * value. This function is deprecated, and should not be used in atomic
4082  * drivers.
4083  *
4084  * RETURNS:
4085  * The total slots required for this port, or error.
4086  */
4087 int drm_dp_find_vcpi_slots(struct drm_dp_mst_topology_mgr *mgr,
4088                            int pbn)
4089 {
4090         int num_slots;
4091
4092         num_slots = DIV_ROUND_UP(pbn, mgr->pbn_div);
4093
4094         /* max. time slots - one slot for MTP header */
4095         if (num_slots > 63)
4096                 return -ENOSPC;
4097         return num_slots;
4098 }
4099 EXPORT_SYMBOL(drm_dp_find_vcpi_slots);
4100
4101 static int drm_dp_init_vcpi(struct drm_dp_mst_topology_mgr *mgr,
4102                             struct drm_dp_vcpi *vcpi, int pbn, int slots)
4103 {
4104         int ret;
4105
4106         /* max. time slots - one slot for MTP header */
4107         if (slots > 63)
4108                 return -ENOSPC;
4109
4110         vcpi->pbn = pbn;
4111         vcpi->aligned_pbn = slots * mgr->pbn_div;
4112         vcpi->num_slots = slots;
4113
4114         ret = drm_dp_mst_assign_payload_id(mgr, vcpi);
4115         if (ret < 0)
4116                 return ret;
4117         return 0;
4118 }
4119
4120 /**
4121  * drm_dp_atomic_find_vcpi_slots() - Find and add VCPI slots to the state
4122  * @state: global atomic state
4123  * @mgr: MST topology manager for the port
4124  * @port: port to find vcpi slots for
4125  * @pbn: bandwidth required for the mode in PBN
4126  * @pbn_div: divider for DSC mode that takes FEC into account
4127  *
4128  * Allocates VCPI slots to @port, replacing any previous VCPI allocations it
4129  * may have had. Any atomic drivers which support MST must call this function
4130  * in their &drm_encoder_helper_funcs.atomic_check() callback to change the
4131  * current VCPI allocation for the new state, but only when
4132  * &drm_crtc_state.mode_changed or &drm_crtc_state.connectors_changed is set
4133  * to ensure compatibility with userspace applications that still use the
4134  * legacy modesetting UAPI.
4135  *
4136  * Allocations set by this function are not checked against the bandwidth
4137  * restraints of @mgr until the driver calls drm_dp_mst_atomic_check().
4138  *
4139  * Additionally, it is OK to call this function multiple times on the same
4140  * @port as needed. It is not OK however, to call this function and
4141  * drm_dp_atomic_release_vcpi_slots() in the same atomic check phase.
4142  *
4143  * See also:
4144  * drm_dp_atomic_release_vcpi_slots()
4145  * drm_dp_mst_atomic_check()
4146  *
4147  * Returns:
4148  * Total slots in the atomic state assigned for this port, or a negative error
4149  * code if the port no longer exists
4150  */
4151 int drm_dp_atomic_find_vcpi_slots(struct drm_atomic_state *state,
4152                                   struct drm_dp_mst_topology_mgr *mgr,
4153                                   struct drm_dp_mst_port *port, int pbn,
4154                                   int pbn_div)
4155 {
4156         struct drm_dp_mst_topology_state *topology_state;
4157         struct drm_dp_vcpi_allocation *pos, *vcpi = NULL;
4158         int prev_slots, prev_bw, req_slots;
4159
4160         topology_state = drm_atomic_get_mst_topology_state(state, mgr);
4161         if (IS_ERR(topology_state))
4162                 return PTR_ERR(topology_state);
4163
4164         /* Find the current allocation for this port, if any */
4165         list_for_each_entry(pos, &topology_state->vcpis, next) {
4166                 if (pos->port == port) {
4167                         vcpi = pos;
4168                         prev_slots = vcpi->vcpi;
4169                         prev_bw = vcpi->pbn;
4170
4171                         /*
4172                          * This should never happen, unless the driver tries
4173                          * releasing and allocating the same VCPI allocation,
4174                          * which is an error
4175                          */
4176                         if (WARN_ON(!prev_slots)) {
4177                                 DRM_ERROR("cannot allocate and release VCPI on [MST PORT:%p] in the same state\n",
4178                                           port);
4179                                 return -EINVAL;
4180                         }
4181
4182                         break;
4183                 }
4184         }
4185         if (!vcpi) {
4186                 prev_slots = 0;
4187                 prev_bw = 0;
4188         }
4189
4190         if (pbn_div <= 0)
4191                 pbn_div = mgr->pbn_div;
4192
4193         req_slots = DIV_ROUND_UP(pbn, pbn_div);
4194
4195         DRM_DEBUG_ATOMIC("[CONNECTOR:%d:%s] [MST PORT:%p] VCPI %d -> %d\n",
4196                          port->connector->base.id, port->connector->name,
4197                          port, prev_slots, req_slots);
4198         DRM_DEBUG_ATOMIC("[CONNECTOR:%d:%s] [MST PORT:%p] PBN %d -> %d\n",
4199                          port->connector->base.id, port->connector->name,
4200                          port, prev_bw, pbn);
4201
4202         /* Add the new allocation to the state */
4203         if (!vcpi) {
4204                 vcpi = kzalloc(sizeof(*vcpi), GFP_KERNEL);
4205                 if (!vcpi)
4206                         return -ENOMEM;
4207
4208                 drm_dp_mst_get_port_malloc(port);
4209                 vcpi->port = port;
4210                 list_add(&vcpi->next, &topology_state->vcpis);
4211         }
4212         vcpi->vcpi = req_slots;
4213         vcpi->pbn = pbn;
4214
4215         return req_slots;
4216 }
4217 EXPORT_SYMBOL(drm_dp_atomic_find_vcpi_slots);
4218
4219 /**
4220  * drm_dp_atomic_release_vcpi_slots() - Release allocated vcpi slots
4221  * @state: global atomic state
4222  * @mgr: MST topology manager for the port
4223  * @port: The port to release the VCPI slots from
4224  *
4225  * Releases any VCPI slots that have been allocated to a port in the atomic
4226  * state. Any atomic drivers which support MST must call this function in
4227  * their &drm_connector_helper_funcs.atomic_check() callback when the
4228  * connector will no longer have VCPI allocated (e.g. because its CRTC was
4229  * removed) when it had VCPI allocated in the previous atomic state.
4230  *
4231  * It is OK to call this even if @port has been removed from the system.
4232  * Additionally, it is OK to call this function multiple times on the same
4233  * @port as needed. It is not OK however, to call this function and
4234  * drm_dp_atomic_find_vcpi_slots() on the same @port in a single atomic check
4235  * phase.
4236  *
4237  * See also:
4238  * drm_dp_atomic_find_vcpi_slots()
4239  * drm_dp_mst_atomic_check()
4240  *
4241  * Returns:
4242  * 0 if all slots for this port were added back to
4243  * &drm_dp_mst_topology_state.avail_slots or negative error code
4244  */
4245 int drm_dp_atomic_release_vcpi_slots(struct drm_atomic_state *state,
4246                                      struct drm_dp_mst_topology_mgr *mgr,
4247                                      struct drm_dp_mst_port *port)
4248 {
4249         struct drm_dp_mst_topology_state *topology_state;
4250         struct drm_dp_vcpi_allocation *pos;
4251         bool found = false;
4252
4253         topology_state = drm_atomic_get_mst_topology_state(state, mgr);
4254         if (IS_ERR(topology_state))
4255                 return PTR_ERR(topology_state);
4256
4257         list_for_each_entry(pos, &topology_state->vcpis, next) {
4258                 if (pos->port == port) {
4259                         found = true;
4260                         break;
4261                 }
4262         }
4263         if (WARN_ON(!found)) {
4264                 DRM_ERROR("no VCPI for [MST PORT:%p] found in mst state %p\n",
4265                           port, &topology_state->base);
4266                 return -EINVAL;
4267         }
4268
4269         DRM_DEBUG_ATOMIC("[MST PORT:%p] VCPI %d -> 0\n", port, pos->vcpi);
4270         if (pos->vcpi) {
4271                 drm_dp_mst_put_port_malloc(port);
4272                 pos->vcpi = 0;
4273                 pos->pbn = 0;
4274         }
4275
4276         return 0;
4277 }
4278 EXPORT_SYMBOL(drm_dp_atomic_release_vcpi_slots);
4279
4280 /**
4281  * drm_dp_mst_allocate_vcpi() - Allocate a virtual channel
4282  * @mgr: manager for this port
4283  * @port: port to allocate a virtual channel for.
4284  * @pbn: payload bandwidth number to request
4285  * @slots: returned number of slots for this PBN.
4286  */
4287 bool drm_dp_mst_allocate_vcpi(struct drm_dp_mst_topology_mgr *mgr,
4288                               struct drm_dp_mst_port *port, int pbn, int slots)
4289 {
4290         int ret;
4291
4292         port = drm_dp_mst_topology_get_port_validated(mgr, port);
4293         if (!port)
4294                 return false;
4295
4296         if (slots < 0)
4297                 return false;
4298
4299         if (port->vcpi.vcpi > 0) {
4300                 DRM_DEBUG_KMS("payload: vcpi %d already allocated for pbn %d - requested pbn %d\n",
4301                               port->vcpi.vcpi, port->vcpi.pbn, pbn);
4302                 if (pbn == port->vcpi.pbn) {
4303                         drm_dp_mst_topology_put_port(port);
4304                         return true;
4305                 }
4306         }
4307
4308         ret = drm_dp_init_vcpi(mgr, &port->vcpi, pbn, slots);
4309         if (ret) {
4310                 DRM_DEBUG_KMS("failed to init vcpi slots=%d max=63 ret=%d\n",
4311                               DIV_ROUND_UP(pbn, mgr->pbn_div), ret);
4312                 goto out;
4313         }
4314         DRM_DEBUG_KMS("initing vcpi for pbn=%d slots=%d\n",
4315                       pbn, port->vcpi.num_slots);
4316
4317         /* Keep port allocated until its payload has been removed */
4318         drm_dp_mst_get_port_malloc(port);
4319         drm_dp_mst_topology_put_port(port);
4320         return true;
4321 out:
4322         return false;
4323 }
4324 EXPORT_SYMBOL(drm_dp_mst_allocate_vcpi);
4325
4326 int drm_dp_mst_get_vcpi_slots(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
4327 {
4328         int slots = 0;
4329         port = drm_dp_mst_topology_get_port_validated(mgr, port);
4330         if (!port)
4331                 return slots;
4332
4333         slots = port->vcpi.num_slots;
4334         drm_dp_mst_topology_put_port(port);
4335         return slots;
4336 }
4337 EXPORT_SYMBOL(drm_dp_mst_get_vcpi_slots);
4338
4339 /**
4340  * drm_dp_mst_reset_vcpi_slots() - Reset number of slots to 0 for VCPI
4341  * @mgr: manager for this port
4342  * @port: unverified pointer to a port.
4343  *
4344  * This just resets the number of slots for the ports VCPI for later programming.
4345  */
4346 void drm_dp_mst_reset_vcpi_slots(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
4347 {
4348         /*
4349          * A port with VCPI will remain allocated until its VCPI is
4350          * released, no verified ref needed
4351          */
4352
4353         port->vcpi.num_slots = 0;
4354 }
4355 EXPORT_SYMBOL(drm_dp_mst_reset_vcpi_slots);
4356
4357 /**
4358  * drm_dp_mst_deallocate_vcpi() - deallocate a VCPI
4359  * @mgr: manager for this port
4360  * @port: port to deallocate vcpi for
4361  *
4362  * This can be called unconditionally, regardless of whether
4363  * drm_dp_mst_allocate_vcpi() succeeded or not.
4364  */
4365 void drm_dp_mst_deallocate_vcpi(struct drm_dp_mst_topology_mgr *mgr,
4366                                 struct drm_dp_mst_port *port)
4367 {
4368         if (!port->vcpi.vcpi)
4369                 return;
4370
4371         drm_dp_mst_put_payload_id(mgr, port->vcpi.vcpi);
4372         port->vcpi.num_slots = 0;
4373         port->vcpi.pbn = 0;
4374         port->vcpi.aligned_pbn = 0;
4375         port->vcpi.vcpi = 0;
4376         drm_dp_mst_put_port_malloc(port);
4377 }
4378 EXPORT_SYMBOL(drm_dp_mst_deallocate_vcpi);
4379
4380 static int drm_dp_dpcd_write_payload(struct drm_dp_mst_topology_mgr *mgr,
4381                                      int id, struct drm_dp_payload *payload)
4382 {
4383         u8 payload_alloc[3], status;
4384         int ret;
4385         int retries = 0;
4386
4387         drm_dp_dpcd_writeb(mgr->aux, DP_PAYLOAD_TABLE_UPDATE_STATUS,
4388                            DP_PAYLOAD_TABLE_UPDATED);
4389
4390         payload_alloc[0] = id;
4391         payload_alloc[1] = payload->start_slot;
4392         payload_alloc[2] = payload->num_slots;
4393
4394         ret = drm_dp_dpcd_write(mgr->aux, DP_PAYLOAD_ALLOCATE_SET, payload_alloc, 3);
4395         if (ret != 3) {
4396                 DRM_DEBUG_KMS("failed to write payload allocation %d\n", ret);
4397                 goto fail;
4398         }
4399
4400 retry:
4401         ret = drm_dp_dpcd_readb(mgr->aux, DP_PAYLOAD_TABLE_UPDATE_STATUS, &status);
4402         if (ret < 0) {
4403                 DRM_DEBUG_KMS("failed to read payload table status %d\n", ret);
4404                 goto fail;
4405         }
4406
4407         if (!(status & DP_PAYLOAD_TABLE_UPDATED)) {
4408                 retries++;
4409                 if (retries < 20) {
4410                         usleep_range(10000, 20000);
4411                         goto retry;
4412                 }
4413                 DRM_DEBUG_KMS("status not set after read payload table status %d\n", status);
4414                 ret = -EINVAL;
4415                 goto fail;
4416         }
4417         ret = 0;
4418 fail:
4419         return ret;
4420 }
4421
4422 static int do_get_act_status(struct drm_dp_aux *aux)
4423 {
4424         int ret;
4425         u8 status;
4426
4427         ret = drm_dp_dpcd_readb(aux, DP_PAYLOAD_TABLE_UPDATE_STATUS, &status);
4428         if (ret < 0)
4429                 return ret;
4430
4431         return status;
4432 }
4433
4434 /**
4435  * drm_dp_check_act_status() - Polls for ACT handled status.
4436  * @mgr: manager to use
4437  *
4438  * Tries waiting for the MST hub to finish updating it's payload table by
4439  * polling for the ACT handled bit for up to 3 seconds (yes-some hubs really
4440  * take that long).
4441  *
4442  * Returns:
4443  * 0 if the ACT was handled in time, negative error code on failure.
4444  */
4445 int drm_dp_check_act_status(struct drm_dp_mst_topology_mgr *mgr)
4446 {
4447         /*
4448          * There doesn't seem to be any recommended retry count or timeout in
4449          * the MST specification. Since some hubs have been observed to take
4450          * over 1 second to update their payload allocations under certain
4451          * conditions, we use a rather large timeout value.
4452          */
4453         const int timeout_ms = 3000;
4454         int ret, status;
4455
4456         ret = readx_poll_timeout(do_get_act_status, mgr->aux, status,
4457                                  status & DP_PAYLOAD_ACT_HANDLED || status < 0,
4458                                  200, timeout_ms * USEC_PER_MSEC);
4459         if (ret < 0 && status >= 0) {
4460                 DRM_ERROR("Failed to get ACT after %dms, last status: %02x\n",
4461                           timeout_ms, status);
4462                 return -EINVAL;
4463         } else if (status < 0) {
4464                 /*
4465                  * Failure here isn't unexpected - the hub may have
4466                  * just been unplugged
4467                  */
4468                 DRM_DEBUG_KMS("Failed to read payload table status: %d\n",
4469                               status);
4470                 return status;
4471         }
4472
4473         return 0;
4474 }
4475 EXPORT_SYMBOL(drm_dp_check_act_status);
4476
4477 /**
4478  * drm_dp_calc_pbn_mode() - Calculate the PBN for a mode.
4479  * @clock: dot clock for the mode
4480  * @bpp: bpp for the mode.
4481  * @dsc: DSC mode. If true, bpp has units of 1/16 of a bit per pixel
4482  *
4483  * This uses the formula in the spec to calculate the PBN value for a mode.
4484  */
4485 int drm_dp_calc_pbn_mode(int clock, int bpp, bool dsc)
4486 {
4487         /*
4488          * margin 5300ppm + 300ppm ~ 0.6% as per spec, factor is 1.006
4489          * The unit of 54/64Mbytes/sec is an arbitrary unit chosen based on
4490          * common multiplier to render an integer PBN for all link rate/lane
4491          * counts combinations
4492          * calculate
4493          * peak_kbps *= (1006/1000)
4494          * peak_kbps *= (64/54)
4495          * peak_kbps *= 8    convert to bytes
4496          *
4497          * If the bpp is in units of 1/16, further divide by 16. Put this
4498          * factor in the numerator rather than the denominator to avoid
4499          * integer overflow
4500          */
4501
4502         if (dsc)
4503                 return DIV_ROUND_UP_ULL(mul_u32_u32(clock * (bpp / 16), 64 * 1006),
4504                                         8 * 54 * 1000 * 1000);
4505
4506         return DIV_ROUND_UP_ULL(mul_u32_u32(clock * bpp, 64 * 1006),
4507                                 8 * 54 * 1000 * 1000);
4508 }
4509 EXPORT_SYMBOL(drm_dp_calc_pbn_mode);
4510
4511 /* we want to kick the TX after we've ack the up/down IRQs. */
4512 static void drm_dp_mst_kick_tx(struct drm_dp_mst_topology_mgr *mgr)
4513 {
4514         queue_work(system_long_wq, &mgr->tx_work);
4515 }
4516
4517 static void drm_dp_mst_dump_mstb(struct seq_file *m,
4518                                  struct drm_dp_mst_branch *mstb)
4519 {
4520         struct drm_dp_mst_port *port;
4521         int tabs = mstb->lct;
4522         char prefix[10];
4523         int i;
4524
4525         for (i = 0; i < tabs; i++)
4526                 prefix[i] = '\t';
4527         prefix[i] = '\0';
4528
4529         seq_printf(m, "%smst: %p, %d\n", prefix, mstb, mstb->num_ports);
4530         list_for_each_entry(port, &mstb->ports, next) {
4531                 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);
4532                 if (port->mstb)
4533                         drm_dp_mst_dump_mstb(m, port->mstb);
4534         }
4535 }
4536
4537 #define DP_PAYLOAD_TABLE_SIZE           64
4538
4539 static bool dump_dp_payload_table(struct drm_dp_mst_topology_mgr *mgr,
4540                                   char *buf)
4541 {
4542         int i;
4543
4544         for (i = 0; i < DP_PAYLOAD_TABLE_SIZE; i += 16) {
4545                 if (drm_dp_dpcd_read(mgr->aux,
4546                                      DP_PAYLOAD_TABLE_UPDATE_STATUS + i,
4547                                      &buf[i], 16) != 16)
4548                         return false;
4549         }
4550         return true;
4551 }
4552
4553 static void fetch_monitor_name(struct drm_dp_mst_topology_mgr *mgr,
4554                                struct drm_dp_mst_port *port, char *name,
4555                                int namelen)
4556 {
4557         struct edid *mst_edid;
4558
4559         mst_edid = drm_dp_mst_get_edid(port->connector, mgr, port);
4560         drm_edid_get_monitor_name(mst_edid, name, namelen);
4561 }
4562
4563 /**
4564  * drm_dp_mst_dump_topology(): dump topology to seq file.
4565  * @m: seq_file to dump output to
4566  * @mgr: manager to dump current topology for.
4567  *
4568  * helper to dump MST topology to a seq file for debugfs.
4569  */
4570 void drm_dp_mst_dump_topology(struct seq_file *m,
4571                               struct drm_dp_mst_topology_mgr *mgr)
4572 {
4573         int i;
4574         struct drm_dp_mst_port *port;
4575
4576         mutex_lock(&mgr->lock);
4577         if (mgr->mst_primary)
4578                 drm_dp_mst_dump_mstb(m, mgr->mst_primary);
4579
4580         /* dump VCPIs */
4581         mutex_unlock(&mgr->lock);
4582
4583         mutex_lock(&mgr->payload_lock);
4584         seq_printf(m, "vcpi: %lx %lx %d\n", mgr->payload_mask, mgr->vcpi_mask,
4585                 mgr->max_payloads);
4586
4587         for (i = 0; i < mgr->max_payloads; i++) {
4588                 if (mgr->proposed_vcpis[i]) {
4589                         char name[14];
4590
4591                         port = container_of(mgr->proposed_vcpis[i], struct drm_dp_mst_port, vcpi);
4592                         fetch_monitor_name(mgr, port, name, sizeof(name));
4593                         seq_printf(m, "vcpi %d: %d %d %d sink name: %s\n", i,
4594                                    port->port_num, port->vcpi.vcpi,
4595                                    port->vcpi.num_slots,
4596                                    (*name != 0) ? name :  "Unknown");
4597                 } else
4598                         seq_printf(m, "vcpi %d:unused\n", i);
4599         }
4600         for (i = 0; i < mgr->max_payloads; i++) {
4601                 seq_printf(m, "payload %d: %d, %d, %d\n",
4602                            i,
4603                            mgr->payloads[i].payload_state,
4604                            mgr->payloads[i].start_slot,
4605                            mgr->payloads[i].num_slots);
4606
4607
4608         }
4609         mutex_unlock(&mgr->payload_lock);
4610
4611         mutex_lock(&mgr->lock);
4612         if (mgr->mst_primary) {
4613                 u8 buf[DP_PAYLOAD_TABLE_SIZE];
4614                 int ret;
4615
4616                 ret = drm_dp_dpcd_read(mgr->aux, DP_DPCD_REV, buf, DP_RECEIVER_CAP_SIZE);
4617                 if (ret) {
4618                         seq_printf(m, "dpcd read failed\n");
4619                         goto out;
4620                 }
4621                 seq_printf(m, "dpcd: %*ph\n", DP_RECEIVER_CAP_SIZE, buf);
4622
4623                 ret = drm_dp_dpcd_read(mgr->aux, DP_FAUX_CAP, buf, 2);
4624                 if (ret) {
4625                         seq_printf(m, "faux/mst read failed\n");
4626                         goto out;
4627                 }
4628                 seq_printf(m, "faux/mst: %*ph\n", 2, buf);
4629
4630                 ret = drm_dp_dpcd_read(mgr->aux, DP_MSTM_CTRL, buf, 1);
4631                 if (ret) {
4632                         seq_printf(m, "mst ctrl read failed\n");
4633                         goto out;
4634                 }
4635                 seq_printf(m, "mst ctrl: %*ph\n", 1, buf);
4636
4637                 /* dump the standard OUI branch header */
4638                 ret = drm_dp_dpcd_read(mgr->aux, DP_BRANCH_OUI, buf, DP_BRANCH_OUI_HEADER_SIZE);
4639                 if (ret) {
4640                         seq_printf(m, "branch oui read failed\n");
4641                         goto out;
4642                 }
4643                 seq_printf(m, "branch oui: %*phN devid: ", 3, buf);
4644
4645                 for (i = 0x3; i < 0x8 && buf[i]; i++)
4646                         seq_printf(m, "%c", buf[i]);
4647                 seq_printf(m, " revision: hw: %x.%x sw: %x.%x\n",
4648                            buf[0x9] >> 4, buf[0x9] & 0xf, buf[0xa], buf[0xb]);
4649                 if (dump_dp_payload_table(mgr, buf))
4650                         seq_printf(m, "payload table: %*ph\n", DP_PAYLOAD_TABLE_SIZE, buf);
4651         }
4652
4653 out:
4654         mutex_unlock(&mgr->lock);
4655
4656 }
4657 EXPORT_SYMBOL(drm_dp_mst_dump_topology);
4658
4659 static void drm_dp_tx_work(struct work_struct *work)
4660 {
4661         struct drm_dp_mst_topology_mgr *mgr = container_of(work, struct drm_dp_mst_topology_mgr, tx_work);
4662
4663         mutex_lock(&mgr->qlock);
4664         if (!list_empty(&mgr->tx_msg_downq))
4665                 process_single_down_tx_qlock(mgr);
4666         mutex_unlock(&mgr->qlock);
4667 }
4668
4669 static inline void
4670 drm_dp_delayed_destroy_port(struct drm_dp_mst_port *port)
4671 {
4672         drm_dp_port_set_pdt(port, DP_PEER_DEVICE_NONE, port->mcs);
4673
4674         if (port->connector) {
4675                 drm_connector_unregister(port->connector);
4676                 drm_connector_put(port->connector);
4677         }
4678
4679         drm_dp_mst_put_port_malloc(port);
4680 }
4681
4682 static inline void
4683 drm_dp_delayed_destroy_mstb(struct drm_dp_mst_branch *mstb)
4684 {
4685         struct drm_dp_mst_topology_mgr *mgr = mstb->mgr;
4686         struct drm_dp_mst_port *port, *port_tmp;
4687         struct drm_dp_sideband_msg_tx *txmsg, *txmsg_tmp;
4688         bool wake_tx = false;
4689
4690         mutex_lock(&mgr->lock);
4691         list_for_each_entry_safe(port, port_tmp, &mstb->ports, next) {
4692                 list_del(&port->next);
4693                 drm_dp_mst_topology_put_port(port);
4694         }
4695         mutex_unlock(&mgr->lock);
4696
4697         /* drop any tx slot msg */
4698         mutex_lock(&mstb->mgr->qlock);
4699         list_for_each_entry_safe(txmsg, txmsg_tmp, &mgr->tx_msg_downq, next) {
4700                 if (txmsg->dst != mstb)
4701                         continue;
4702
4703                 txmsg->state = DRM_DP_SIDEBAND_TX_TIMEOUT;
4704                 list_del(&txmsg->next);
4705                 wake_tx = true;
4706         }
4707         mutex_unlock(&mstb->mgr->qlock);
4708
4709         if (wake_tx)
4710                 wake_up_all(&mstb->mgr->tx_waitq);
4711
4712         drm_dp_mst_put_mstb_malloc(mstb);
4713 }
4714
4715 static void drm_dp_delayed_destroy_work(struct work_struct *work)
4716 {
4717         struct drm_dp_mst_topology_mgr *mgr =
4718                 container_of(work, struct drm_dp_mst_topology_mgr,
4719                              delayed_destroy_work);
4720         bool send_hotplug = false, go_again;
4721
4722         /*
4723          * Not a regular list traverse as we have to drop the destroy
4724          * connector lock before destroying the mstb/port, to avoid AB->BA
4725          * ordering between this lock and the config mutex.
4726          */
4727         do {
4728                 go_again = false;
4729
4730                 for (;;) {
4731                         struct drm_dp_mst_branch *mstb;
4732
4733                         mutex_lock(&mgr->delayed_destroy_lock);
4734                         mstb = list_first_entry_or_null(&mgr->destroy_branch_device_list,
4735                                                         struct drm_dp_mst_branch,
4736                                                         destroy_next);
4737                         if (mstb)
4738                                 list_del(&mstb->destroy_next);
4739                         mutex_unlock(&mgr->delayed_destroy_lock);
4740
4741                         if (!mstb)
4742                                 break;
4743
4744                         drm_dp_delayed_destroy_mstb(mstb);
4745                         go_again = true;
4746                 }
4747
4748                 for (;;) {
4749                         struct drm_dp_mst_port *port;
4750
4751                         mutex_lock(&mgr->delayed_destroy_lock);
4752                         port = list_first_entry_or_null(&mgr->destroy_port_list,
4753                                                         struct drm_dp_mst_port,
4754                                                         next);
4755                         if (port)
4756                                 list_del(&port->next);
4757                         mutex_unlock(&mgr->delayed_destroy_lock);
4758
4759                         if (!port)
4760                                 break;
4761
4762                         drm_dp_delayed_destroy_port(port);
4763                         send_hotplug = true;
4764                         go_again = true;
4765                 }
4766         } while (go_again);
4767
4768         if (send_hotplug)
4769                 drm_kms_helper_hotplug_event(mgr->dev);
4770 }
4771
4772 static struct drm_private_state *
4773 drm_dp_mst_duplicate_state(struct drm_private_obj *obj)
4774 {
4775         struct drm_dp_mst_topology_state *state, *old_state =
4776                 to_dp_mst_topology_state(obj->state);
4777         struct drm_dp_vcpi_allocation *pos, *vcpi;
4778
4779         state = kmemdup(old_state, sizeof(*state), GFP_KERNEL);
4780         if (!state)
4781                 return NULL;
4782
4783         __drm_atomic_helper_private_obj_duplicate_state(obj, &state->base);
4784
4785         INIT_LIST_HEAD(&state->vcpis);
4786
4787         list_for_each_entry(pos, &old_state->vcpis, next) {
4788                 /* Prune leftover freed VCPI allocations */
4789                 if (!pos->vcpi)
4790                         continue;
4791
4792                 vcpi = kmemdup(pos, sizeof(*vcpi), GFP_KERNEL);
4793                 if (!vcpi)
4794                         goto fail;
4795
4796                 drm_dp_mst_get_port_malloc(vcpi->port);
4797                 list_add(&vcpi->next, &state->vcpis);
4798         }
4799
4800         return &state->base;
4801
4802 fail:
4803         list_for_each_entry_safe(pos, vcpi, &state->vcpis, next) {
4804                 drm_dp_mst_put_port_malloc(pos->port);
4805                 kfree(pos);
4806         }
4807         kfree(state);
4808
4809         return NULL;
4810 }
4811
4812 static void drm_dp_mst_destroy_state(struct drm_private_obj *obj,
4813                                      struct drm_private_state *state)
4814 {
4815         struct drm_dp_mst_topology_state *mst_state =
4816                 to_dp_mst_topology_state(state);
4817         struct drm_dp_vcpi_allocation *pos, *tmp;
4818
4819         list_for_each_entry_safe(pos, tmp, &mst_state->vcpis, next) {
4820                 /* We only keep references to ports with non-zero VCPIs */
4821                 if (pos->vcpi)
4822                         drm_dp_mst_put_port_malloc(pos->port);
4823                 kfree(pos);
4824         }
4825
4826         kfree(mst_state);
4827 }
4828
4829 static bool drm_dp_mst_port_downstream_of_branch(struct drm_dp_mst_port *port,
4830                                                  struct drm_dp_mst_branch *branch)
4831 {
4832         while (port->parent) {
4833                 if (port->parent == branch)
4834                         return true;
4835
4836                 if (port->parent->port_parent)
4837                         port = port->parent->port_parent;
4838                 else
4839                         break;
4840         }
4841         return false;
4842 }
4843
4844 static int
4845 drm_dp_mst_atomic_check_port_bw_limit(struct drm_dp_mst_port *port,
4846                                       struct drm_dp_mst_topology_state *state);
4847
4848 static int
4849 drm_dp_mst_atomic_check_mstb_bw_limit(struct drm_dp_mst_branch *mstb,
4850                                       struct drm_dp_mst_topology_state *state)
4851 {
4852         struct drm_dp_vcpi_allocation *vcpi;
4853         struct drm_dp_mst_port *port;
4854         int pbn_used = 0, ret;
4855         bool found = false;
4856
4857         /* Check that we have at least one port in our state that's downstream
4858          * of this branch, otherwise we can skip this branch
4859          */
4860         list_for_each_entry(vcpi, &state->vcpis, next) {
4861                 if (!vcpi->pbn ||
4862                     !drm_dp_mst_port_downstream_of_branch(vcpi->port, mstb))
4863                         continue;
4864
4865                 found = true;
4866                 break;
4867         }
4868         if (!found)
4869                 return 0;
4870
4871         if (mstb->port_parent)
4872                 DRM_DEBUG_ATOMIC("[MSTB:%p] [MST PORT:%p] Checking bandwidth limits on [MSTB:%p]\n",
4873                                  mstb->port_parent->parent, mstb->port_parent,
4874                                  mstb);
4875         else
4876                 DRM_DEBUG_ATOMIC("[MSTB:%p] Checking bandwidth limits\n",
4877                                  mstb);
4878
4879         list_for_each_entry(port, &mstb->ports, next) {
4880                 ret = drm_dp_mst_atomic_check_port_bw_limit(port, state);
4881                 if (ret < 0)
4882                         return ret;
4883
4884                 pbn_used += ret;
4885         }
4886
4887         return pbn_used;
4888 }
4889
4890 static int
4891 drm_dp_mst_atomic_check_port_bw_limit(struct drm_dp_mst_port *port,
4892                                       struct drm_dp_mst_topology_state *state)
4893 {
4894         struct drm_dp_vcpi_allocation *vcpi;
4895         int pbn_used = 0;
4896
4897         if (port->pdt == DP_PEER_DEVICE_NONE)
4898                 return 0;
4899
4900         if (drm_dp_mst_is_end_device(port->pdt, port->mcs)) {
4901                 bool found = false;
4902
4903                 list_for_each_entry(vcpi, &state->vcpis, next) {
4904                         if (vcpi->port != port)
4905                                 continue;
4906                         if (!vcpi->pbn)
4907                                 return 0;
4908
4909                         found = true;
4910                         break;
4911                 }
4912                 if (!found)
4913                         return 0;
4914
4915                 /* This should never happen, as it means we tried to
4916                  * set a mode before querying the full_pbn
4917                  */
4918                 if (WARN_ON(!port->full_pbn))
4919                         return -EINVAL;
4920
4921                 pbn_used = vcpi->pbn;
4922         } else {
4923                 pbn_used = drm_dp_mst_atomic_check_mstb_bw_limit(port->mstb,
4924                                                                  state);
4925                 if (pbn_used <= 0)
4926                         return pbn_used;
4927         }
4928
4929         if (pbn_used > port->full_pbn) {
4930                 DRM_DEBUG_ATOMIC("[MSTB:%p] [MST PORT:%p] required PBN of %d exceeds port limit of %d\n",
4931                                  port->parent, port, pbn_used,
4932                                  port->full_pbn);
4933                 return -ENOSPC;
4934         }
4935
4936         DRM_DEBUG_ATOMIC("[MSTB:%p] [MST PORT:%p] uses %d out of %d PBN\n",
4937                          port->parent, port, pbn_used, port->full_pbn);
4938
4939         return pbn_used;
4940 }
4941
4942 static inline int
4943 drm_dp_mst_atomic_check_vcpi_alloc_limit(struct drm_dp_mst_topology_mgr *mgr,
4944                                          struct drm_dp_mst_topology_state *mst_state)
4945 {
4946         struct drm_dp_vcpi_allocation *vcpi;
4947         int avail_slots = 63, payload_count = 0;
4948
4949         list_for_each_entry(vcpi, &mst_state->vcpis, next) {
4950                 /* Releasing VCPI is always OK-even if the port is gone */
4951                 if (!vcpi->vcpi) {
4952                         DRM_DEBUG_ATOMIC("[MST PORT:%p] releases all VCPI slots\n",
4953                                          vcpi->port);
4954                         continue;
4955                 }
4956
4957                 DRM_DEBUG_ATOMIC("[MST PORT:%p] requires %d vcpi slots\n",
4958                                  vcpi->port, vcpi->vcpi);
4959
4960                 avail_slots -= vcpi->vcpi;
4961                 if (avail_slots < 0) {
4962                         DRM_DEBUG_ATOMIC("[MST PORT:%p] not enough VCPI slots in mst state %p (avail=%d)\n",
4963                                          vcpi->port, mst_state,
4964                                          avail_slots + vcpi->vcpi);
4965                         return -ENOSPC;
4966                 }
4967
4968                 if (++payload_count > mgr->max_payloads) {
4969                         DRM_DEBUG_ATOMIC("[MST MGR:%p] state %p has too many payloads (max=%d)\n",
4970                                          mgr, mst_state, mgr->max_payloads);
4971                         return -EINVAL;
4972                 }
4973         }
4974         DRM_DEBUG_ATOMIC("[MST MGR:%p] mst state %p VCPI avail=%d used=%d\n",
4975                          mgr, mst_state, avail_slots,
4976                          63 - avail_slots);
4977
4978         return 0;
4979 }
4980
4981 /**
4982  * drm_dp_mst_add_affected_dsc_crtcs
4983  * @state: Pointer to the new struct drm_dp_mst_topology_state
4984  * @mgr: MST topology manager
4985  *
4986  * Whenever there is a change in mst topology
4987  * DSC configuration would have to be recalculated
4988  * therefore we need to trigger modeset on all affected
4989  * CRTCs in that topology
4990  *
4991  * See also:
4992  * drm_dp_mst_atomic_enable_dsc()
4993  */
4994 int drm_dp_mst_add_affected_dsc_crtcs(struct drm_atomic_state *state, struct drm_dp_mst_topology_mgr *mgr)
4995 {
4996         struct drm_dp_mst_topology_state *mst_state;
4997         struct drm_dp_vcpi_allocation *pos;
4998         struct drm_connector *connector;
4999         struct drm_connector_state *conn_state;
5000         struct drm_crtc *crtc;
5001         struct drm_crtc_state *crtc_state;
5002
5003         mst_state = drm_atomic_get_mst_topology_state(state, mgr);
5004
5005         if (IS_ERR(mst_state))
5006                 return -EINVAL;
5007
5008         list_for_each_entry(pos, &mst_state->vcpis, next) {
5009
5010                 connector = pos->port->connector;
5011
5012                 if (!connector)
5013                         return -EINVAL;
5014
5015                 conn_state = drm_atomic_get_connector_state(state, connector);
5016
5017                 if (IS_ERR(conn_state))
5018                         return PTR_ERR(conn_state);
5019
5020                 crtc = conn_state->crtc;
5021
5022                 if (WARN_ON(!crtc))
5023                         return -EINVAL;
5024
5025                 if (!drm_dp_mst_dsc_aux_for_port(pos->port))
5026                         continue;
5027
5028                 crtc_state = drm_atomic_get_crtc_state(mst_state->base.state, crtc);
5029
5030                 if (IS_ERR(crtc_state))
5031                         return PTR_ERR(crtc_state);
5032
5033                 DRM_DEBUG_ATOMIC("[MST MGR:%p] Setting mode_changed flag on CRTC %p\n",
5034                                  mgr, crtc);
5035
5036                 crtc_state->mode_changed = true;
5037         }
5038         return 0;
5039 }
5040 EXPORT_SYMBOL(drm_dp_mst_add_affected_dsc_crtcs);
5041
5042 /**
5043  * drm_dp_mst_atomic_enable_dsc - Set DSC Enable Flag to On/Off
5044  * @state: Pointer to the new drm_atomic_state
5045  * @port: Pointer to the affected MST Port
5046  * @pbn: Newly recalculated bw required for link with DSC enabled
5047  * @pbn_div: Divider to calculate correct number of pbn per slot
5048  * @enable: Boolean flag to enable or disable DSC on the port
5049  *
5050  * This function enables DSC on the given Port
5051  * by recalculating its vcpi from pbn provided
5052  * and sets dsc_enable flag to keep track of which
5053  * ports have DSC enabled
5054  *
5055  */
5056 int drm_dp_mst_atomic_enable_dsc(struct drm_atomic_state *state,
5057                                  struct drm_dp_mst_port *port,
5058                                  int pbn, int pbn_div,
5059                                  bool enable)
5060 {
5061         struct drm_dp_mst_topology_state *mst_state;
5062         struct drm_dp_vcpi_allocation *pos;
5063         bool found = false;
5064         int vcpi = 0;
5065
5066         mst_state = drm_atomic_get_mst_topology_state(state, port->mgr);
5067
5068         if (IS_ERR(mst_state))
5069                 return PTR_ERR(mst_state);
5070
5071         list_for_each_entry(pos, &mst_state->vcpis, next) {
5072                 if (pos->port == port) {
5073                         found = true;
5074                         break;
5075                 }
5076         }
5077
5078         if (!found) {
5079                 DRM_DEBUG_ATOMIC("[MST PORT:%p] Couldn't find VCPI allocation in mst state %p\n",
5080                                  port, mst_state);
5081                 return -EINVAL;
5082         }
5083
5084         if (pos->dsc_enabled == enable) {
5085                 DRM_DEBUG_ATOMIC("[MST PORT:%p] DSC flag is already set to %d, returning %d VCPI slots\n",
5086                                  port, enable, pos->vcpi);
5087                 vcpi = pos->vcpi;
5088         }
5089
5090         if (enable) {
5091                 vcpi = drm_dp_atomic_find_vcpi_slots(state, port->mgr, port, pbn, pbn_div);
5092                 DRM_DEBUG_ATOMIC("[MST PORT:%p] Enabling DSC flag, reallocating %d VCPI slots on the port\n",
5093                                  port, vcpi);
5094                 if (vcpi < 0)
5095                         return -EINVAL;
5096         }
5097
5098         pos->dsc_enabled = enable;
5099
5100         return vcpi;
5101 }
5102 EXPORT_SYMBOL(drm_dp_mst_atomic_enable_dsc);
5103 /**
5104  * drm_dp_mst_atomic_check - Check that the new state of an MST topology in an
5105  * atomic update is valid
5106  * @state: Pointer to the new &struct drm_dp_mst_topology_state
5107  *
5108  * Checks the given topology state for an atomic update to ensure that it's
5109  * valid. This includes checking whether there's enough bandwidth to support
5110  * the new VCPI allocations in the atomic update.
5111  *
5112  * Any atomic drivers supporting DP MST must make sure to call this after
5113  * checking the rest of their state in their
5114  * &drm_mode_config_funcs.atomic_check() callback.
5115  *
5116  * See also:
5117  * drm_dp_atomic_find_vcpi_slots()
5118  * drm_dp_atomic_release_vcpi_slots()
5119  *
5120  * Returns:
5121  *
5122  * 0 if the new state is valid, negative error code otherwise.
5123  */
5124 int drm_dp_mst_atomic_check(struct drm_atomic_state *state)
5125 {
5126         struct drm_dp_mst_topology_mgr *mgr;
5127         struct drm_dp_mst_topology_state *mst_state;
5128         int i, ret = 0;
5129
5130         for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
5131                 if (!mgr->mst_state)
5132                         continue;
5133
5134                 ret = drm_dp_mst_atomic_check_vcpi_alloc_limit(mgr, mst_state);
5135                 if (ret)
5136                         break;
5137
5138                 mutex_lock(&mgr->lock);
5139                 ret = drm_dp_mst_atomic_check_mstb_bw_limit(mgr->mst_primary,
5140                                                             mst_state);
5141                 mutex_unlock(&mgr->lock);
5142                 if (ret < 0)
5143                         break;
5144                 else
5145                         ret = 0;
5146         }
5147
5148         return ret;
5149 }
5150 EXPORT_SYMBOL(drm_dp_mst_atomic_check);
5151
5152 const struct drm_private_state_funcs drm_dp_mst_topology_state_funcs = {
5153         .atomic_duplicate_state = drm_dp_mst_duplicate_state,
5154         .atomic_destroy_state = drm_dp_mst_destroy_state,
5155 };
5156 EXPORT_SYMBOL(drm_dp_mst_topology_state_funcs);
5157
5158 /**
5159  * drm_atomic_get_mst_topology_state: get MST topology state
5160  *
5161  * @state: global atomic state
5162  * @mgr: MST topology manager, also the private object in this case
5163  *
5164  * This function wraps drm_atomic_get_priv_obj_state() passing in the MST atomic
5165  * state vtable so that the private object state returned is that of a MST
5166  * topology object. Also, drm_atomic_get_private_obj_state() expects the caller
5167  * to care of the locking, so warn if don't hold the connection_mutex.
5168  *
5169  * RETURNS:
5170  *
5171  * The MST topology state or error pointer.
5172  */
5173 struct drm_dp_mst_topology_state *drm_atomic_get_mst_topology_state(struct drm_atomic_state *state,
5174                                                                     struct drm_dp_mst_topology_mgr *mgr)
5175 {
5176         return to_dp_mst_topology_state(drm_atomic_get_private_obj_state(state, &mgr->base));
5177 }
5178 EXPORT_SYMBOL(drm_atomic_get_mst_topology_state);
5179
5180 /**
5181  * drm_dp_mst_topology_mgr_init - initialise a topology manager
5182  * @mgr: manager struct to initialise
5183  * @dev: device providing this structure - for i2c addition.
5184  * @aux: DP helper aux channel to talk to this device
5185  * @max_dpcd_transaction_bytes: hw specific DPCD transaction limit
5186  * @max_payloads: maximum number of payloads this GPU can source
5187  * @conn_base_id: the connector object ID the MST device is connected to.
5188  *
5189  * Return 0 for success, or negative error code on failure
5190  */
5191 int drm_dp_mst_topology_mgr_init(struct drm_dp_mst_topology_mgr *mgr,
5192                                  struct drm_device *dev, struct drm_dp_aux *aux,
5193                                  int max_dpcd_transaction_bytes,
5194                                  int max_payloads, int conn_base_id)
5195 {
5196         struct drm_dp_mst_topology_state *mst_state;
5197
5198         mutex_init(&mgr->lock);
5199         mutex_init(&mgr->qlock);
5200         mutex_init(&mgr->payload_lock);
5201         mutex_init(&mgr->delayed_destroy_lock);
5202         mutex_init(&mgr->up_req_lock);
5203         mutex_init(&mgr->probe_lock);
5204 #if IS_ENABLED(CONFIG_DRM_DEBUG_DP_MST_TOPOLOGY_REFS)
5205         mutex_init(&mgr->topology_ref_history_lock);
5206 #endif
5207         INIT_LIST_HEAD(&mgr->tx_msg_downq);
5208         INIT_LIST_HEAD(&mgr->destroy_port_list);
5209         INIT_LIST_HEAD(&mgr->destroy_branch_device_list);
5210         INIT_LIST_HEAD(&mgr->up_req_list);
5211
5212         /*
5213          * delayed_destroy_work will be queued on a dedicated WQ, so that any
5214          * requeuing will be also flushed when deiniting the topology manager.
5215          */
5216         mgr->delayed_destroy_wq = alloc_ordered_workqueue("drm_dp_mst_wq", 0);
5217         if (mgr->delayed_destroy_wq == NULL)
5218                 return -ENOMEM;
5219
5220         INIT_WORK(&mgr->work, drm_dp_mst_link_probe_work);
5221         INIT_WORK(&mgr->tx_work, drm_dp_tx_work);
5222         INIT_WORK(&mgr->delayed_destroy_work, drm_dp_delayed_destroy_work);
5223         INIT_WORK(&mgr->up_req_work, drm_dp_mst_up_req_work);
5224         init_waitqueue_head(&mgr->tx_waitq);
5225         mgr->dev = dev;
5226         mgr->aux = aux;
5227         mgr->max_dpcd_transaction_bytes = max_dpcd_transaction_bytes;
5228         mgr->max_payloads = max_payloads;
5229         mgr->conn_base_id = conn_base_id;
5230         if (max_payloads + 1 > sizeof(mgr->payload_mask) * 8 ||
5231             max_payloads + 1 > sizeof(mgr->vcpi_mask) * 8)
5232                 return -EINVAL;
5233         mgr->payloads = kcalloc(max_payloads, sizeof(struct drm_dp_payload), GFP_KERNEL);
5234         if (!mgr->payloads)
5235                 return -ENOMEM;
5236         mgr->proposed_vcpis = kcalloc(max_payloads, sizeof(struct drm_dp_vcpi *), GFP_KERNEL);
5237         if (!mgr->proposed_vcpis)
5238                 return -ENOMEM;
5239         set_bit(0, &mgr->payload_mask);
5240
5241         mst_state = kzalloc(sizeof(*mst_state), GFP_KERNEL);
5242         if (mst_state == NULL)
5243                 return -ENOMEM;
5244
5245         mst_state->mgr = mgr;
5246         INIT_LIST_HEAD(&mst_state->vcpis);
5247
5248         drm_atomic_private_obj_init(dev, &mgr->base,
5249                                     &mst_state->base,
5250                                     &drm_dp_mst_topology_state_funcs);
5251
5252         return 0;
5253 }
5254 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_init);
5255
5256 /**
5257  * drm_dp_mst_topology_mgr_destroy() - destroy topology manager.
5258  * @mgr: manager to destroy
5259  */
5260 void drm_dp_mst_topology_mgr_destroy(struct drm_dp_mst_topology_mgr *mgr)
5261 {
5262         drm_dp_mst_topology_mgr_set_mst(mgr, false);
5263         flush_work(&mgr->work);
5264         /* The following will also drain any requeued work on the WQ. */
5265         if (mgr->delayed_destroy_wq) {
5266                 destroy_workqueue(mgr->delayed_destroy_wq);
5267                 mgr->delayed_destroy_wq = NULL;
5268         }
5269         mutex_lock(&mgr->payload_lock);
5270         kfree(mgr->payloads);
5271         mgr->payloads = NULL;
5272         kfree(mgr->proposed_vcpis);
5273         mgr->proposed_vcpis = NULL;
5274         mutex_unlock(&mgr->payload_lock);
5275         mgr->dev = NULL;
5276         mgr->aux = NULL;
5277         drm_atomic_private_obj_fini(&mgr->base);
5278         mgr->funcs = NULL;
5279
5280         mutex_destroy(&mgr->delayed_destroy_lock);
5281         mutex_destroy(&mgr->payload_lock);
5282         mutex_destroy(&mgr->qlock);
5283         mutex_destroy(&mgr->lock);
5284         mutex_destroy(&mgr->up_req_lock);
5285         mutex_destroy(&mgr->probe_lock);
5286 #if IS_ENABLED(CONFIG_DRM_DEBUG_DP_MST_TOPOLOGY_REFS)
5287         mutex_destroy(&mgr->topology_ref_history_lock);
5288 #endif
5289 }
5290 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_destroy);
5291
5292 static bool remote_i2c_read_ok(const struct i2c_msg msgs[], int num)
5293 {
5294         int i;
5295
5296         if (num - 1 > DP_REMOTE_I2C_READ_MAX_TRANSACTIONS)
5297                 return false;
5298
5299         for (i = 0; i < num - 1; i++) {
5300                 if (msgs[i].flags & I2C_M_RD ||
5301                     msgs[i].len > 0xff)
5302                         return false;
5303         }
5304
5305         return msgs[num - 1].flags & I2C_M_RD &&
5306                 msgs[num - 1].len <= 0xff;
5307 }
5308
5309 /* I2C device */
5310 static int drm_dp_mst_i2c_xfer(struct i2c_adapter *adapter, struct i2c_msg *msgs,
5311                                int num)
5312 {
5313         struct drm_dp_aux *aux = adapter->algo_data;
5314         struct drm_dp_mst_port *port = container_of(aux, struct drm_dp_mst_port, aux);
5315         struct drm_dp_mst_branch *mstb;
5316         struct drm_dp_mst_topology_mgr *mgr = port->mgr;
5317         unsigned int i;
5318         struct drm_dp_sideband_msg_req_body msg;
5319         struct drm_dp_sideband_msg_tx *txmsg = NULL;
5320         int ret;
5321
5322         mstb = drm_dp_mst_topology_get_mstb_validated(mgr, port->parent);
5323         if (!mstb)
5324                 return -EREMOTEIO;
5325
5326         if (!remote_i2c_read_ok(msgs, num)) {
5327                 DRM_DEBUG_KMS("Unsupported I2C transaction for MST device\n");
5328                 ret = -EIO;
5329                 goto out;
5330         }
5331
5332         memset(&msg, 0, sizeof(msg));
5333         msg.req_type = DP_REMOTE_I2C_READ;
5334         msg.u.i2c_read.num_transactions = num - 1;
5335         msg.u.i2c_read.port_number = port->port_num;
5336         for (i = 0; i < num - 1; i++) {
5337                 msg.u.i2c_read.transactions[i].i2c_dev_id = msgs[i].addr;
5338                 msg.u.i2c_read.transactions[i].num_bytes = msgs[i].len;
5339                 msg.u.i2c_read.transactions[i].bytes = msgs[i].buf;
5340                 msg.u.i2c_read.transactions[i].no_stop_bit = !(msgs[i].flags & I2C_M_STOP);
5341         }
5342         msg.u.i2c_read.read_i2c_device_id = msgs[num - 1].addr;
5343         msg.u.i2c_read.num_bytes_read = msgs[num - 1].len;
5344
5345         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
5346         if (!txmsg) {
5347                 ret = -ENOMEM;
5348                 goto out;
5349         }
5350
5351         txmsg->dst = mstb;
5352         drm_dp_encode_sideband_req(&msg, txmsg);
5353
5354         drm_dp_queue_down_tx(mgr, txmsg);
5355
5356         ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
5357         if (ret > 0) {
5358
5359                 if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK) {
5360                         ret = -EREMOTEIO;
5361                         goto out;
5362                 }
5363                 if (txmsg->reply.u.remote_i2c_read_ack.num_bytes != msgs[num - 1].len) {
5364                         ret = -EIO;
5365                         goto out;
5366                 }
5367                 memcpy(msgs[num - 1].buf, txmsg->reply.u.remote_i2c_read_ack.bytes, msgs[num - 1].len);
5368                 ret = num;
5369         }
5370 out:
5371         kfree(txmsg);
5372         drm_dp_mst_topology_put_mstb(mstb);
5373         return ret;
5374 }
5375
5376 static u32 drm_dp_mst_i2c_functionality(struct i2c_adapter *adapter)
5377 {
5378         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
5379                I2C_FUNC_SMBUS_READ_BLOCK_DATA |
5380                I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
5381                I2C_FUNC_10BIT_ADDR;
5382 }
5383
5384 static const struct i2c_algorithm drm_dp_mst_i2c_algo = {
5385         .functionality = drm_dp_mst_i2c_functionality,
5386         .master_xfer = drm_dp_mst_i2c_xfer,
5387 };
5388
5389 /**
5390  * drm_dp_mst_register_i2c_bus() - register an I2C adapter for I2C-over-AUX
5391  * @port: The port to add the I2C bus on
5392  *
5393  * Returns 0 on success or a negative error code on failure.
5394  */
5395 static int drm_dp_mst_register_i2c_bus(struct drm_dp_mst_port *port)
5396 {
5397         struct drm_dp_aux *aux = &port->aux;
5398         struct device *parent_dev = port->mgr->dev->dev;
5399
5400         aux->ddc.algo = &drm_dp_mst_i2c_algo;
5401         aux->ddc.algo_data = aux;
5402         aux->ddc.retries = 3;
5403
5404         aux->ddc.class = I2C_CLASS_DDC;
5405         aux->ddc.owner = THIS_MODULE;
5406         /* FIXME: set the kdev of the port's connector as parent */
5407         aux->ddc.dev.parent = parent_dev;
5408         aux->ddc.dev.of_node = parent_dev->of_node;
5409
5410         strlcpy(aux->ddc.name, aux->name ? aux->name : dev_name(parent_dev),
5411                 sizeof(aux->ddc.name));
5412
5413         return i2c_add_adapter(&aux->ddc);
5414 }
5415
5416 /**
5417  * drm_dp_mst_unregister_i2c_bus() - unregister an I2C-over-AUX adapter
5418  * @port: The port to remove the I2C bus from
5419  */
5420 static void drm_dp_mst_unregister_i2c_bus(struct drm_dp_mst_port *port)
5421 {
5422         i2c_del_adapter(&port->aux.ddc);
5423 }
5424
5425 /**
5426  * drm_dp_mst_is_virtual_dpcd() - Is the given port a virtual DP Peer Device
5427  * @port: The port to check
5428  *
5429  * A single physical MST hub object can be represented in the topology
5430  * by multiple branches, with virtual ports between those branches.
5431  *
5432  * As of DP1.4, An MST hub with internal (virtual) ports must expose
5433  * certain DPCD registers over those ports. See sections 2.6.1.1.1
5434  * and 2.6.1.1.2 of Display Port specification v1.4 for details.
5435  *
5436  * May acquire mgr->lock
5437  *
5438  * Returns:
5439  * true if the port is a virtual DP peer device, false otherwise
5440  */
5441 static bool drm_dp_mst_is_virtual_dpcd(struct drm_dp_mst_port *port)
5442 {
5443         struct drm_dp_mst_port *downstream_port;
5444
5445         if (!port || port->dpcd_rev < DP_DPCD_REV_14)
5446                 return false;
5447
5448         /* Virtual DP Sink (Internal Display Panel) */
5449         if (port->port_num >= 8)
5450                 return true;
5451
5452         /* DP-to-HDMI Protocol Converter */
5453         if (port->pdt == DP_PEER_DEVICE_DP_LEGACY_CONV &&
5454             !port->mcs &&
5455             port->ldps)
5456                 return true;
5457
5458         /* DP-to-DP */
5459         mutex_lock(&port->mgr->lock);
5460         if (port->pdt == DP_PEER_DEVICE_MST_BRANCHING &&
5461             port->mstb &&
5462             port->mstb->num_ports == 2) {
5463                 list_for_each_entry(downstream_port, &port->mstb->ports, next) {
5464                         if (downstream_port->pdt == DP_PEER_DEVICE_SST_SINK &&
5465                             !downstream_port->input) {
5466                                 mutex_unlock(&port->mgr->lock);
5467                                 return true;
5468                         }
5469                 }
5470         }
5471         mutex_unlock(&port->mgr->lock);
5472
5473         return false;
5474 }
5475
5476 /**
5477  * drm_dp_mst_dsc_aux_for_port() - Find the correct aux for DSC
5478  * @port: The port to check. A leaf of the MST tree with an attached display.
5479  *
5480  * Depending on the situation, DSC may be enabled via the endpoint aux,
5481  * the immediately upstream aux, or the connector's physical aux.
5482  *
5483  * This is both the correct aux to read DSC_CAPABILITY and the
5484  * correct aux to write DSC_ENABLED.
5485  *
5486  * This operation can be expensive (up to four aux reads), so
5487  * the caller should cache the return.
5488  *
5489  * Returns:
5490  * NULL if DSC cannot be enabled on this port, otherwise the aux device
5491  */
5492 struct drm_dp_aux *drm_dp_mst_dsc_aux_for_port(struct drm_dp_mst_port *port)
5493 {
5494         struct drm_dp_mst_port *immediate_upstream_port;
5495         struct drm_dp_mst_port *fec_port;
5496         struct drm_dp_desc desc = {};
5497         u8 endpoint_fec;
5498         u8 endpoint_dsc;
5499
5500         if (!port)
5501                 return NULL;
5502
5503         if (port->parent->port_parent)
5504                 immediate_upstream_port = port->parent->port_parent;
5505         else
5506                 immediate_upstream_port = NULL;
5507
5508         fec_port = immediate_upstream_port;
5509         while (fec_port) {
5510                 /*
5511                  * Each physical link (i.e. not a virtual port) between the
5512                  * output and the primary device must support FEC
5513                  */
5514                 if (!drm_dp_mst_is_virtual_dpcd(fec_port) &&
5515                     !fec_port->fec_capable)
5516                         return NULL;
5517
5518                 fec_port = fec_port->parent->port_parent;
5519         }
5520
5521         /* DP-to-DP peer device */
5522         if (drm_dp_mst_is_virtual_dpcd(immediate_upstream_port)) {
5523                 u8 upstream_dsc;
5524
5525                 if (drm_dp_dpcd_read(&port->aux,
5526                                      DP_DSC_SUPPORT, &endpoint_dsc, 1) != 1)
5527                         return NULL;
5528                 if (drm_dp_dpcd_read(&port->aux,
5529                                      DP_FEC_CAPABILITY, &endpoint_fec, 1) != 1)
5530                         return NULL;
5531                 if (drm_dp_dpcd_read(&immediate_upstream_port->aux,
5532                                      DP_DSC_SUPPORT, &upstream_dsc, 1) != 1)
5533                         return NULL;
5534
5535                 /* Enpoint decompression with DP-to-DP peer device */
5536                 if ((endpoint_dsc & DP_DSC_DECOMPRESSION_IS_SUPPORTED) &&
5537                     (endpoint_fec & DP_FEC_CAPABLE) &&
5538                     (upstream_dsc & 0x2) /* DSC passthrough */)
5539                         return &port->aux;
5540
5541                 /* Virtual DPCD decompression with DP-to-DP peer device */
5542                 return &immediate_upstream_port->aux;
5543         }
5544
5545         /* Virtual DPCD decompression with DP-to-HDMI or Virtual DP Sink */
5546         if (drm_dp_mst_is_virtual_dpcd(port))
5547                 return &port->aux;
5548
5549         /*
5550          * Synaptics quirk
5551          * Applies to ports for which:
5552          * - Physical aux has Synaptics OUI
5553          * - DPv1.4 or higher
5554          * - Port is on primary branch device
5555          * - Not a VGA adapter (DP_DWN_STRM_PORT_TYPE_ANALOG)
5556          */
5557         if (drm_dp_read_desc(port->mgr->aux, &desc, true))
5558                 return NULL;
5559
5560         if (drm_dp_has_quirk(&desc, 0,
5561                              DP_DPCD_QUIRK_DSC_WITHOUT_VIRTUAL_DPCD) &&
5562             port->mgr->dpcd[DP_DPCD_REV] >= DP_DPCD_REV_14 &&
5563             port->parent == port->mgr->mst_primary) {
5564                 u8 downstreamport;
5565
5566                 if (drm_dp_dpcd_read(&port->aux, DP_DOWNSTREAMPORT_PRESENT,
5567                                      &downstreamport, 1) < 0)
5568                         return NULL;
5569
5570                 if ((downstreamport & DP_DWN_STRM_PORT_PRESENT) &&
5571                    ((downstreamport & DP_DWN_STRM_PORT_TYPE_MASK)
5572                      != DP_DWN_STRM_PORT_TYPE_ANALOG))
5573                         return port->mgr->aux;
5574         }
5575
5576         /*
5577          * The check below verifies if the MST sink
5578          * connected to the GPU is capable of DSC -
5579          * therefore the endpoint needs to be
5580          * both DSC and FEC capable.
5581          */
5582         if (drm_dp_dpcd_read(&port->aux,
5583            DP_DSC_SUPPORT, &endpoint_dsc, 1) != 1)
5584                 return NULL;
5585         if (drm_dp_dpcd_read(&port->aux,
5586            DP_FEC_CAPABILITY, &endpoint_fec, 1) != 1)
5587                 return NULL;
5588         if ((endpoint_dsc & DP_DSC_DECOMPRESSION_IS_SUPPORTED) &&
5589            (endpoint_fec & DP_FEC_CAPABLE))
5590                 return &port->aux;
5591
5592         return NULL;
5593 }
5594 EXPORT_SYMBOL(drm_dp_mst_dsc_aux_for_port);