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