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