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