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