]> Git Repo - J-linux.git/blob - drivers/gpu/drm/drm_dp_mst_topology.c
Merge drm/drm-next into drm-intel-next-queued
[J-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/delay.h>
24 #include <linux/errno.h>
25 #include <linux/i2c.h>
26 #include <linux/init.h>
27 #include <linux/kernel.h>
28 #include <linux/sched.h>
29 #include <linux/seq_file.h>
30
31 #include <drm/drm_atomic.h>
32 #include <drm/drm_atomic_helper.h>
33 #include <drm/drm_dp_mst_helper.h>
34 #include <drm/drm_drv.h>
35 #include <drm/drm_print.h>
36 #include <drm/drm_probe_helper.h>
37
38 #include "drm_crtc_helper_internal.h"
39 #include "drm_dp_mst_topology_internal.h"
40
41 /**
42  * DOC: dp mst helper
43  *
44  * These functions contain parts of the DisplayPort 1.2a MultiStream Transport
45  * protocol. The helpers contain a topology manager and bandwidth manager.
46  * The helpers encapsulate the sending and received of sideband msgs.
47  */
48 static bool dump_dp_payload_table(struct drm_dp_mst_topology_mgr *mgr,
49                                   char *buf);
50
51 static void drm_dp_mst_topology_put_port(struct drm_dp_mst_port *port);
52
53 static int drm_dp_dpcd_write_payload(struct drm_dp_mst_topology_mgr *mgr,
54                                      int id,
55                                      struct drm_dp_payload *payload);
56
57 static int drm_dp_send_dpcd_read(struct drm_dp_mst_topology_mgr *mgr,
58                                  struct drm_dp_mst_port *port,
59                                  int offset, int size, u8 *bytes);
60 static int drm_dp_send_dpcd_write(struct drm_dp_mst_topology_mgr *mgr,
61                                   struct drm_dp_mst_port *port,
62                                   int offset, int size, u8 *bytes);
63
64 static void drm_dp_send_link_address(struct drm_dp_mst_topology_mgr *mgr,
65                                      struct drm_dp_mst_branch *mstb);
66 static int drm_dp_send_enum_path_resources(struct drm_dp_mst_topology_mgr *mgr,
67                                            struct drm_dp_mst_branch *mstb,
68                                            struct drm_dp_mst_port *port);
69 static bool drm_dp_validate_guid(struct drm_dp_mst_topology_mgr *mgr,
70                                  u8 *guid);
71
72 static int drm_dp_mst_register_i2c_bus(struct drm_dp_aux *aux);
73 static void drm_dp_mst_unregister_i2c_bus(struct drm_dp_aux *aux);
74 static void drm_dp_mst_kick_tx(struct drm_dp_mst_topology_mgr *mgr);
75
76 #define DBG_PREFIX "[dp_mst]"
77
78 #define DP_STR(x) [DP_ ## x] = #x
79
80 static const char *drm_dp_mst_req_type_str(u8 req_type)
81 {
82         static const char * const req_type_str[] = {
83                 DP_STR(GET_MSG_TRANSACTION_VERSION),
84                 DP_STR(LINK_ADDRESS),
85                 DP_STR(CONNECTION_STATUS_NOTIFY),
86                 DP_STR(ENUM_PATH_RESOURCES),
87                 DP_STR(ALLOCATE_PAYLOAD),
88                 DP_STR(QUERY_PAYLOAD),
89                 DP_STR(RESOURCE_STATUS_NOTIFY),
90                 DP_STR(CLEAR_PAYLOAD_ID_TABLE),
91                 DP_STR(REMOTE_DPCD_READ),
92                 DP_STR(REMOTE_DPCD_WRITE),
93                 DP_STR(REMOTE_I2C_READ),
94                 DP_STR(REMOTE_I2C_WRITE),
95                 DP_STR(POWER_UP_PHY),
96                 DP_STR(POWER_DOWN_PHY),
97                 DP_STR(SINK_EVENT_NOTIFY),
98                 DP_STR(QUERY_STREAM_ENC_STATUS),
99         };
100
101         if (req_type >= ARRAY_SIZE(req_type_str) ||
102             !req_type_str[req_type])
103                 return "unknown";
104
105         return req_type_str[req_type];
106 }
107
108 #undef DP_STR
109 #define DP_STR(x) [DP_NAK_ ## x] = #x
110
111 static const char *drm_dp_mst_nak_reason_str(u8 nak_reason)
112 {
113         static const char * const nak_reason_str[] = {
114                 DP_STR(WRITE_FAILURE),
115                 DP_STR(INVALID_READ),
116                 DP_STR(CRC_FAILURE),
117                 DP_STR(BAD_PARAM),
118                 DP_STR(DEFER),
119                 DP_STR(LINK_FAILURE),
120                 DP_STR(NO_RESOURCES),
121                 DP_STR(DPCD_FAIL),
122                 DP_STR(I2C_NAK),
123                 DP_STR(ALLOCATE_FAIL),
124         };
125
126         if (nak_reason >= ARRAY_SIZE(nak_reason_str) ||
127             !nak_reason_str[nak_reason])
128                 return "unknown";
129
130         return nak_reason_str[nak_reason];
131 }
132
133 #undef DP_STR
134 #define DP_STR(x) [DRM_DP_SIDEBAND_TX_ ## x] = #x
135
136 static const char *drm_dp_mst_sideband_tx_state_str(int state)
137 {
138         static const char * const sideband_reason_str[] = {
139                 DP_STR(QUEUED),
140                 DP_STR(START_SEND),
141                 DP_STR(SENT),
142                 DP_STR(RX),
143                 DP_STR(TIMEOUT),
144         };
145
146         if (state >= ARRAY_SIZE(sideband_reason_str) ||
147             !sideband_reason_str[state])
148                 return "unknown";
149
150         return sideband_reason_str[state];
151 }
152
153 static int
154 drm_dp_mst_rad_to_str(const u8 rad[8], u8 lct, char *out, size_t len)
155 {
156         int i;
157         u8 unpacked_rad[16];
158
159         for (i = 0; i < lct; i++) {
160                 if (i % 2)
161                         unpacked_rad[i] = rad[i / 2] >> 4;
162                 else
163                         unpacked_rad[i] = rad[i / 2] & BIT_MASK(4);
164         }
165
166         /* TODO: Eventually add something to printk so we can format the rad
167          * like this: 1.2.3
168          */
169         return snprintf(out, len, "%*phC", lct, unpacked_rad);
170 }
171
172 /* sideband msg handling */
173 static u8 drm_dp_msg_header_crc4(const uint8_t *data, size_t num_nibbles)
174 {
175         u8 bitmask = 0x80;
176         u8 bitshift = 7;
177         u8 array_index = 0;
178         int number_of_bits = num_nibbles * 4;
179         u8 remainder = 0;
180
181         while (number_of_bits != 0) {
182                 number_of_bits--;
183                 remainder <<= 1;
184                 remainder |= (data[array_index] & bitmask) >> bitshift;
185                 bitmask >>= 1;
186                 bitshift--;
187                 if (bitmask == 0) {
188                         bitmask = 0x80;
189                         bitshift = 7;
190                         array_index++;
191                 }
192                 if ((remainder & 0x10) == 0x10)
193                         remainder ^= 0x13;
194         }
195
196         number_of_bits = 4;
197         while (number_of_bits != 0) {
198                 number_of_bits--;
199                 remainder <<= 1;
200                 if ((remainder & 0x10) != 0)
201                         remainder ^= 0x13;
202         }
203
204         return remainder;
205 }
206
207 static u8 drm_dp_msg_data_crc4(const uint8_t *data, u8 number_of_bytes)
208 {
209         u8 bitmask = 0x80;
210         u8 bitshift = 7;
211         u8 array_index = 0;
212         int number_of_bits = number_of_bytes * 8;
213         u16 remainder = 0;
214
215         while (number_of_bits != 0) {
216                 number_of_bits--;
217                 remainder <<= 1;
218                 remainder |= (data[array_index] & bitmask) >> bitshift;
219                 bitmask >>= 1;
220                 bitshift--;
221                 if (bitmask == 0) {
222                         bitmask = 0x80;
223                         bitshift = 7;
224                         array_index++;
225                 }
226                 if ((remainder & 0x100) == 0x100)
227                         remainder ^= 0xd5;
228         }
229
230         number_of_bits = 8;
231         while (number_of_bits != 0) {
232                 number_of_bits--;
233                 remainder <<= 1;
234                 if ((remainder & 0x100) != 0)
235                         remainder ^= 0xd5;
236         }
237
238         return remainder & 0xff;
239 }
240 static inline u8 drm_dp_calc_sb_hdr_size(struct drm_dp_sideband_msg_hdr *hdr)
241 {
242         u8 size = 3;
243         size += (hdr->lct / 2);
244         return size;
245 }
246
247 static void drm_dp_encode_sideband_msg_hdr(struct drm_dp_sideband_msg_hdr *hdr,
248                                            u8 *buf, int *len)
249 {
250         int idx = 0;
251         int i;
252         u8 crc4;
253         buf[idx++] = ((hdr->lct & 0xf) << 4) | (hdr->lcr & 0xf);
254         for (i = 0; i < (hdr->lct / 2); i++)
255                 buf[idx++] = hdr->rad[i];
256         buf[idx++] = (hdr->broadcast << 7) | (hdr->path_msg << 6) |
257                 (hdr->msg_len & 0x3f);
258         buf[idx++] = (hdr->somt << 7) | (hdr->eomt << 6) | (hdr->seqno << 4);
259
260         crc4 = drm_dp_msg_header_crc4(buf, (idx * 2) - 1);
261         buf[idx - 1] |= (crc4 & 0xf);
262
263         *len = idx;
264 }
265
266 static bool drm_dp_decode_sideband_msg_hdr(struct drm_dp_sideband_msg_hdr *hdr,
267                                            u8 *buf, int buflen, u8 *hdrlen)
268 {
269         u8 crc4;
270         u8 len;
271         int i;
272         u8 idx;
273         if (buf[0] == 0)
274                 return false;
275         len = 3;
276         len += ((buf[0] & 0xf0) >> 4) / 2;
277         if (len > buflen)
278                 return false;
279         crc4 = drm_dp_msg_header_crc4(buf, (len * 2) - 1);
280
281         if ((crc4 & 0xf) != (buf[len - 1] & 0xf)) {
282                 DRM_DEBUG_KMS("crc4 mismatch 0x%x 0x%x\n", crc4, buf[len - 1]);
283                 return false;
284         }
285
286         hdr->lct = (buf[0] & 0xf0) >> 4;
287         hdr->lcr = (buf[0] & 0xf);
288         idx = 1;
289         for (i = 0; i < (hdr->lct / 2); i++)
290                 hdr->rad[i] = buf[idx++];
291         hdr->broadcast = (buf[idx] >> 7) & 0x1;
292         hdr->path_msg = (buf[idx] >> 6) & 0x1;
293         hdr->msg_len = buf[idx] & 0x3f;
294         idx++;
295         hdr->somt = (buf[idx] >> 7) & 0x1;
296         hdr->eomt = (buf[idx] >> 6) & 0x1;
297         hdr->seqno = (buf[idx] >> 4) & 0x1;
298         idx++;
299         *hdrlen = idx;
300         return true;
301 }
302
303 void
304 drm_dp_encode_sideband_req(const struct drm_dp_sideband_msg_req_body *req,
305                            struct drm_dp_sideband_msg_tx *raw)
306 {
307         int idx = 0;
308         int i;
309         u8 *buf = raw->msg;
310         buf[idx++] = req->req_type & 0x7f;
311
312         switch (req->req_type) {
313         case DP_ENUM_PATH_RESOURCES:
314         case DP_POWER_DOWN_PHY:
315         case DP_POWER_UP_PHY:
316                 buf[idx] = (req->u.port_num.port_number & 0xf) << 4;
317                 idx++;
318                 break;
319         case DP_ALLOCATE_PAYLOAD:
320                 buf[idx] = (req->u.allocate_payload.port_number & 0xf) << 4 |
321                         (req->u.allocate_payload.number_sdp_streams & 0xf);
322                 idx++;
323                 buf[idx] = (req->u.allocate_payload.vcpi & 0x7f);
324                 idx++;
325                 buf[idx] = (req->u.allocate_payload.pbn >> 8);
326                 idx++;
327                 buf[idx] = (req->u.allocate_payload.pbn & 0xff);
328                 idx++;
329                 for (i = 0; i < req->u.allocate_payload.number_sdp_streams / 2; i++) {
330                         buf[idx] = ((req->u.allocate_payload.sdp_stream_sink[i * 2] & 0xf) << 4) |
331                                 (req->u.allocate_payload.sdp_stream_sink[i * 2 + 1] & 0xf);
332                         idx++;
333                 }
334                 if (req->u.allocate_payload.number_sdp_streams & 1) {
335                         i = req->u.allocate_payload.number_sdp_streams - 1;
336                         buf[idx] = (req->u.allocate_payload.sdp_stream_sink[i] & 0xf) << 4;
337                         idx++;
338                 }
339                 break;
340         case DP_QUERY_PAYLOAD:
341                 buf[idx] = (req->u.query_payload.port_number & 0xf) << 4;
342                 idx++;
343                 buf[idx] = (req->u.query_payload.vcpi & 0x7f);
344                 idx++;
345                 break;
346         case DP_REMOTE_DPCD_READ:
347                 buf[idx] = (req->u.dpcd_read.port_number & 0xf) << 4;
348                 buf[idx] |= ((req->u.dpcd_read.dpcd_address & 0xf0000) >> 16) & 0xf;
349                 idx++;
350                 buf[idx] = (req->u.dpcd_read.dpcd_address & 0xff00) >> 8;
351                 idx++;
352                 buf[idx] = (req->u.dpcd_read.dpcd_address & 0xff);
353                 idx++;
354                 buf[idx] = (req->u.dpcd_read.num_bytes);
355                 idx++;
356                 break;
357
358         case DP_REMOTE_DPCD_WRITE:
359                 buf[idx] = (req->u.dpcd_write.port_number & 0xf) << 4;
360                 buf[idx] |= ((req->u.dpcd_write.dpcd_address & 0xf0000) >> 16) & 0xf;
361                 idx++;
362                 buf[idx] = (req->u.dpcd_write.dpcd_address & 0xff00) >> 8;
363                 idx++;
364                 buf[idx] = (req->u.dpcd_write.dpcd_address & 0xff);
365                 idx++;
366                 buf[idx] = (req->u.dpcd_write.num_bytes);
367                 idx++;
368                 memcpy(&buf[idx], req->u.dpcd_write.bytes, req->u.dpcd_write.num_bytes);
369                 idx += req->u.dpcd_write.num_bytes;
370                 break;
371         case DP_REMOTE_I2C_READ:
372                 buf[idx] = (req->u.i2c_read.port_number & 0xf) << 4;
373                 buf[idx] |= (req->u.i2c_read.num_transactions & 0x3);
374                 idx++;
375                 for (i = 0; i < (req->u.i2c_read.num_transactions & 0x3); i++) {
376                         buf[idx] = req->u.i2c_read.transactions[i].i2c_dev_id & 0x7f;
377                         idx++;
378                         buf[idx] = req->u.i2c_read.transactions[i].num_bytes;
379                         idx++;
380                         memcpy(&buf[idx], req->u.i2c_read.transactions[i].bytes, req->u.i2c_read.transactions[i].num_bytes);
381                         idx += req->u.i2c_read.transactions[i].num_bytes;
382
383                         buf[idx] = (req->u.i2c_read.transactions[i].no_stop_bit & 0x1) << 5;
384                         buf[idx] |= (req->u.i2c_read.transactions[i].i2c_transaction_delay & 0xf);
385                         idx++;
386                 }
387                 buf[idx] = (req->u.i2c_read.read_i2c_device_id) & 0x7f;
388                 idx++;
389                 buf[idx] = (req->u.i2c_read.num_bytes_read);
390                 idx++;
391                 break;
392
393         case DP_REMOTE_I2C_WRITE:
394                 buf[idx] = (req->u.i2c_write.port_number & 0xf) << 4;
395                 idx++;
396                 buf[idx] = (req->u.i2c_write.write_i2c_device_id) & 0x7f;
397                 idx++;
398                 buf[idx] = (req->u.i2c_write.num_bytes);
399                 idx++;
400                 memcpy(&buf[idx], req->u.i2c_write.bytes, req->u.i2c_write.num_bytes);
401                 idx += req->u.i2c_write.num_bytes;
402                 break;
403         }
404         raw->cur_len = idx;
405 }
406 EXPORT_SYMBOL_FOR_TESTS_ONLY(drm_dp_encode_sideband_req);
407
408 /* Decode a sideband request we've encoded, mainly used for debugging */
409 int
410 drm_dp_decode_sideband_req(const struct drm_dp_sideband_msg_tx *raw,
411                            struct drm_dp_sideband_msg_req_body *req)
412 {
413         const u8 *buf = raw->msg;
414         int i, idx = 0;
415
416         req->req_type = buf[idx++] & 0x7f;
417         switch (req->req_type) {
418         case DP_ENUM_PATH_RESOURCES:
419         case DP_POWER_DOWN_PHY:
420         case DP_POWER_UP_PHY:
421                 req->u.port_num.port_number = (buf[idx] >> 4) & 0xf;
422                 break;
423         case DP_ALLOCATE_PAYLOAD:
424                 {
425                         struct drm_dp_allocate_payload *a =
426                                 &req->u.allocate_payload;
427
428                         a->number_sdp_streams = buf[idx] & 0xf;
429                         a->port_number = (buf[idx] >> 4) & 0xf;
430
431                         WARN_ON(buf[++idx] & 0x80);
432                         a->vcpi = buf[idx] & 0x7f;
433
434                         a->pbn = buf[++idx] << 8;
435                         a->pbn |= buf[++idx];
436
437                         idx++;
438                         for (i = 0; i < a->number_sdp_streams; i++) {
439                                 a->sdp_stream_sink[i] =
440                                         (buf[idx + (i / 2)] >> ((i % 2) ? 0 : 4)) & 0xf;
441                         }
442                 }
443                 break;
444         case DP_QUERY_PAYLOAD:
445                 req->u.query_payload.port_number = (buf[idx] >> 4) & 0xf;
446                 WARN_ON(buf[++idx] & 0x80);
447                 req->u.query_payload.vcpi = buf[idx] & 0x7f;
448                 break;
449         case DP_REMOTE_DPCD_READ:
450                 {
451                         struct drm_dp_remote_dpcd_read *r = &req->u.dpcd_read;
452
453                         r->port_number = (buf[idx] >> 4) & 0xf;
454
455                         r->dpcd_address = (buf[idx] << 16) & 0xf0000;
456                         r->dpcd_address |= (buf[++idx] << 8) & 0xff00;
457                         r->dpcd_address |= buf[++idx] & 0xff;
458
459                         r->num_bytes = buf[++idx];
460                 }
461                 break;
462         case DP_REMOTE_DPCD_WRITE:
463                 {
464                         struct drm_dp_remote_dpcd_write *w =
465                                 &req->u.dpcd_write;
466
467                         w->port_number = (buf[idx] >> 4) & 0xf;
468
469                         w->dpcd_address = (buf[idx] << 16) & 0xf0000;
470                         w->dpcd_address |= (buf[++idx] << 8) & 0xff00;
471                         w->dpcd_address |= buf[++idx] & 0xff;
472
473                         w->num_bytes = buf[++idx];
474
475                         w->bytes = kmemdup(&buf[++idx], w->num_bytes,
476                                            GFP_KERNEL);
477                         if (!w->bytes)
478                                 return -ENOMEM;
479                 }
480                 break;
481         case DP_REMOTE_I2C_READ:
482                 {
483                         struct drm_dp_remote_i2c_read *r = &req->u.i2c_read;
484                         struct drm_dp_remote_i2c_read_tx *tx;
485                         bool failed = false;
486
487                         r->num_transactions = buf[idx] & 0x3;
488                         r->port_number = (buf[idx] >> 4) & 0xf;
489                         for (i = 0; i < r->num_transactions; i++) {
490                                 tx = &r->transactions[i];
491
492                                 tx->i2c_dev_id = buf[++idx] & 0x7f;
493                                 tx->num_bytes = buf[++idx];
494                                 tx->bytes = kmemdup(&buf[++idx],
495                                                     tx->num_bytes,
496                                                     GFP_KERNEL);
497                                 if (!tx->bytes) {
498                                         failed = true;
499                                         break;
500                                 }
501                                 idx += tx->num_bytes;
502                                 tx->no_stop_bit = (buf[idx] >> 5) & 0x1;
503                                 tx->i2c_transaction_delay = buf[idx] & 0xf;
504                         }
505
506                         if (failed) {
507                                 for (i = 0; i < r->num_transactions; i++)
508                                         kfree(tx->bytes);
509                                 return -ENOMEM;
510                         }
511
512                         r->read_i2c_device_id = buf[++idx] & 0x7f;
513                         r->num_bytes_read = buf[++idx];
514                 }
515                 break;
516         case DP_REMOTE_I2C_WRITE:
517                 {
518                         struct drm_dp_remote_i2c_write *w = &req->u.i2c_write;
519
520                         w->port_number = (buf[idx] >> 4) & 0xf;
521                         w->write_i2c_device_id = buf[++idx] & 0x7f;
522                         w->num_bytes = buf[++idx];
523                         w->bytes = kmemdup(&buf[++idx], w->num_bytes,
524                                            GFP_KERNEL);
525                         if (!w->bytes)
526                                 return -ENOMEM;
527                 }
528                 break;
529         }
530
531         return 0;
532 }
533 EXPORT_SYMBOL_FOR_TESTS_ONLY(drm_dp_decode_sideband_req);
534
535 void
536 drm_dp_dump_sideband_msg_req_body(const struct drm_dp_sideband_msg_req_body *req,
537                                   int indent, struct drm_printer *printer)
538 {
539         int i;
540
541 #define P(f, ...) drm_printf_indent(printer, indent, f, ##__VA_ARGS__)
542         if (req->req_type == DP_LINK_ADDRESS) {
543                 /* No contents to print */
544                 P("type=%s\n", drm_dp_mst_req_type_str(req->req_type));
545                 return;
546         }
547
548         P("type=%s contents:\n", drm_dp_mst_req_type_str(req->req_type));
549         indent++;
550
551         switch (req->req_type) {
552         case DP_ENUM_PATH_RESOURCES:
553         case DP_POWER_DOWN_PHY:
554         case DP_POWER_UP_PHY:
555                 P("port=%d\n", req->u.port_num.port_number);
556                 break;
557         case DP_ALLOCATE_PAYLOAD:
558                 P("port=%d vcpi=%d pbn=%d sdp_streams=%d %*ph\n",
559                   req->u.allocate_payload.port_number,
560                   req->u.allocate_payload.vcpi, req->u.allocate_payload.pbn,
561                   req->u.allocate_payload.number_sdp_streams,
562                   req->u.allocate_payload.number_sdp_streams,
563                   req->u.allocate_payload.sdp_stream_sink);
564                 break;
565         case DP_QUERY_PAYLOAD:
566                 P("port=%d vcpi=%d\n",
567                   req->u.query_payload.port_number,
568                   req->u.query_payload.vcpi);
569                 break;
570         case DP_REMOTE_DPCD_READ:
571                 P("port=%d dpcd_addr=%05x len=%d\n",
572                   req->u.dpcd_read.port_number, req->u.dpcd_read.dpcd_address,
573                   req->u.dpcd_read.num_bytes);
574                 break;
575         case DP_REMOTE_DPCD_WRITE:
576                 P("port=%d addr=%05x len=%d: %*ph\n",
577                   req->u.dpcd_write.port_number,
578                   req->u.dpcd_write.dpcd_address,
579                   req->u.dpcd_write.num_bytes, req->u.dpcd_write.num_bytes,
580                   req->u.dpcd_write.bytes);
581                 break;
582         case DP_REMOTE_I2C_READ:
583                 P("port=%d num_tx=%d id=%d size=%d:\n",
584                   req->u.i2c_read.port_number,
585                   req->u.i2c_read.num_transactions,
586                   req->u.i2c_read.read_i2c_device_id,
587                   req->u.i2c_read.num_bytes_read);
588
589                 indent++;
590                 for (i = 0; i < req->u.i2c_read.num_transactions; i++) {
591                         const struct drm_dp_remote_i2c_read_tx *rtx =
592                                 &req->u.i2c_read.transactions[i];
593
594                         P("%d: id=%03d size=%03d no_stop_bit=%d tx_delay=%03d: %*ph\n",
595                           i, rtx->i2c_dev_id, rtx->num_bytes,
596                           rtx->no_stop_bit, rtx->i2c_transaction_delay,
597                           rtx->num_bytes, rtx->bytes);
598                 }
599                 break;
600         case DP_REMOTE_I2C_WRITE:
601                 P("port=%d id=%d size=%d: %*ph\n",
602                   req->u.i2c_write.port_number,
603                   req->u.i2c_write.write_i2c_device_id,
604                   req->u.i2c_write.num_bytes, req->u.i2c_write.num_bytes,
605                   req->u.i2c_write.bytes);
606                 break;
607         default:
608                 P("???\n");
609                 break;
610         }
611 #undef P
612 }
613 EXPORT_SYMBOL_FOR_TESTS_ONLY(drm_dp_dump_sideband_msg_req_body);
614
615 static inline void
616 drm_dp_mst_dump_sideband_msg_tx(struct drm_printer *p,
617                                 const struct drm_dp_sideband_msg_tx *txmsg)
618 {
619         struct drm_dp_sideband_msg_req_body req;
620         char buf[64];
621         int ret;
622         int i;
623
624         drm_dp_mst_rad_to_str(txmsg->dst->rad, txmsg->dst->lct, buf,
625                               sizeof(buf));
626         drm_printf(p, "txmsg cur_offset=%x cur_len=%x seqno=%x state=%s path_msg=%d dst=%s\n",
627                    txmsg->cur_offset, txmsg->cur_len, txmsg->seqno,
628                    drm_dp_mst_sideband_tx_state_str(txmsg->state),
629                    txmsg->path_msg, buf);
630
631         ret = drm_dp_decode_sideband_req(txmsg, &req);
632         if (ret) {
633                 drm_printf(p, "<failed to decode sideband req: %d>\n", ret);
634                 return;
635         }
636         drm_dp_dump_sideband_msg_req_body(&req, 1, p);
637
638         switch (req.req_type) {
639         case DP_REMOTE_DPCD_WRITE:
640                 kfree(req.u.dpcd_write.bytes);
641                 break;
642         case DP_REMOTE_I2C_READ:
643                 for (i = 0; i < req.u.i2c_read.num_transactions; i++)
644                         kfree(req.u.i2c_read.transactions[i].bytes);
645                 break;
646         case DP_REMOTE_I2C_WRITE:
647                 kfree(req.u.i2c_write.bytes);
648                 break;
649         }
650 }
651
652 static void drm_dp_crc_sideband_chunk_req(u8 *msg, u8 len)
653 {
654         u8 crc4;
655         crc4 = drm_dp_msg_data_crc4(msg, len);
656         msg[len] = crc4;
657 }
658
659 static void drm_dp_encode_sideband_reply(struct drm_dp_sideband_msg_reply_body *rep,
660                                          struct drm_dp_sideband_msg_tx *raw)
661 {
662         int idx = 0;
663         u8 *buf = raw->msg;
664
665         buf[idx++] = (rep->reply_type & 0x1) << 7 | (rep->req_type & 0x7f);
666
667         raw->cur_len = idx;
668 }
669
670 /* this adds a chunk of msg to the builder to get the final msg */
671 static bool drm_dp_sideband_msg_build(struct drm_dp_sideband_msg_rx *msg,
672                                       u8 *replybuf, u8 replybuflen, bool hdr)
673 {
674         int ret;
675         u8 crc4;
676
677         if (hdr) {
678                 u8 hdrlen;
679                 struct drm_dp_sideband_msg_hdr recv_hdr;
680                 ret = drm_dp_decode_sideband_msg_hdr(&recv_hdr, replybuf, replybuflen, &hdrlen);
681                 if (ret == false) {
682                         print_hex_dump(KERN_DEBUG, "failed hdr", DUMP_PREFIX_NONE, 16, 1, replybuf, replybuflen, false);
683                         return false;
684                 }
685
686                 /*
687                  * ignore out-of-order messages or messages that are part of a
688                  * failed transaction
689                  */
690                 if (!recv_hdr.somt && !msg->have_somt)
691                         return false;
692
693                 /* get length contained in this portion */
694                 msg->curchunk_len = recv_hdr.msg_len;
695                 msg->curchunk_hdrlen = hdrlen;
696
697                 /* we have already gotten an somt - don't bother parsing */
698                 if (recv_hdr.somt && msg->have_somt)
699                         return false;
700
701                 if (recv_hdr.somt) {
702                         memcpy(&msg->initial_hdr, &recv_hdr, sizeof(struct drm_dp_sideband_msg_hdr));
703                         msg->have_somt = true;
704                 }
705                 if (recv_hdr.eomt)
706                         msg->have_eomt = true;
707
708                 /* copy the bytes for the remainder of this header chunk */
709                 msg->curchunk_idx = min(msg->curchunk_len, (u8)(replybuflen - hdrlen));
710                 memcpy(&msg->chunk[0], replybuf + hdrlen, msg->curchunk_idx);
711         } else {
712                 memcpy(&msg->chunk[msg->curchunk_idx], replybuf, replybuflen);
713                 msg->curchunk_idx += replybuflen;
714         }
715
716         if (msg->curchunk_idx >= msg->curchunk_len) {
717                 /* do CRC */
718                 crc4 = drm_dp_msg_data_crc4(msg->chunk, msg->curchunk_len - 1);
719                 /* copy chunk into bigger msg */
720                 memcpy(&msg->msg[msg->curlen], msg->chunk, msg->curchunk_len - 1);
721                 msg->curlen += msg->curchunk_len - 1;
722         }
723         return true;
724 }
725
726 static bool drm_dp_sideband_parse_link_address(struct drm_dp_sideband_msg_rx *raw,
727                                                struct drm_dp_sideband_msg_reply_body *repmsg)
728 {
729         int idx = 1;
730         int i;
731         memcpy(repmsg->u.link_addr.guid, &raw->msg[idx], 16);
732         idx += 16;
733         repmsg->u.link_addr.nports = raw->msg[idx] & 0xf;
734         idx++;
735         if (idx > raw->curlen)
736                 goto fail_len;
737         for (i = 0; i < repmsg->u.link_addr.nports; i++) {
738                 if (raw->msg[idx] & 0x80)
739                         repmsg->u.link_addr.ports[i].input_port = 1;
740
741                 repmsg->u.link_addr.ports[i].peer_device_type = (raw->msg[idx] >> 4) & 0x7;
742                 repmsg->u.link_addr.ports[i].port_number = (raw->msg[idx] & 0xf);
743
744                 idx++;
745                 if (idx > raw->curlen)
746                         goto fail_len;
747                 repmsg->u.link_addr.ports[i].mcs = (raw->msg[idx] >> 7) & 0x1;
748                 repmsg->u.link_addr.ports[i].ddps = (raw->msg[idx] >> 6) & 0x1;
749                 if (repmsg->u.link_addr.ports[i].input_port == 0)
750                         repmsg->u.link_addr.ports[i].legacy_device_plug_status = (raw->msg[idx] >> 5) & 0x1;
751                 idx++;
752                 if (idx > raw->curlen)
753                         goto fail_len;
754                 if (repmsg->u.link_addr.ports[i].input_port == 0) {
755                         repmsg->u.link_addr.ports[i].dpcd_revision = (raw->msg[idx]);
756                         idx++;
757                         if (idx > raw->curlen)
758                                 goto fail_len;
759                         memcpy(repmsg->u.link_addr.ports[i].peer_guid, &raw->msg[idx], 16);
760                         idx += 16;
761                         if (idx > raw->curlen)
762                                 goto fail_len;
763                         repmsg->u.link_addr.ports[i].num_sdp_streams = (raw->msg[idx] >> 4) & 0xf;
764                         repmsg->u.link_addr.ports[i].num_sdp_stream_sinks = (raw->msg[idx] & 0xf);
765                         idx++;
766
767                 }
768                 if (idx > raw->curlen)
769                         goto fail_len;
770         }
771
772         return true;
773 fail_len:
774         DRM_DEBUG_KMS("link address reply parse length fail %d %d\n", idx, raw->curlen);
775         return false;
776 }
777
778 static bool drm_dp_sideband_parse_remote_dpcd_read(struct drm_dp_sideband_msg_rx *raw,
779                                                    struct drm_dp_sideband_msg_reply_body *repmsg)
780 {
781         int idx = 1;
782         repmsg->u.remote_dpcd_read_ack.port_number = raw->msg[idx] & 0xf;
783         idx++;
784         if (idx > raw->curlen)
785                 goto fail_len;
786         repmsg->u.remote_dpcd_read_ack.num_bytes = raw->msg[idx];
787         idx++;
788         if (idx > raw->curlen)
789                 goto fail_len;
790
791         memcpy(repmsg->u.remote_dpcd_read_ack.bytes, &raw->msg[idx], repmsg->u.remote_dpcd_read_ack.num_bytes);
792         return true;
793 fail_len:
794         DRM_DEBUG_KMS("link address reply parse length fail %d %d\n", idx, raw->curlen);
795         return false;
796 }
797
798 static bool drm_dp_sideband_parse_remote_dpcd_write(struct drm_dp_sideband_msg_rx *raw,
799                                                       struct drm_dp_sideband_msg_reply_body *repmsg)
800 {
801         int idx = 1;
802         repmsg->u.remote_dpcd_write_ack.port_number = raw->msg[idx] & 0xf;
803         idx++;
804         if (idx > raw->curlen)
805                 goto fail_len;
806         return true;
807 fail_len:
808         DRM_DEBUG_KMS("parse length fail %d %d\n", idx, raw->curlen);
809         return false;
810 }
811
812 static bool drm_dp_sideband_parse_remote_i2c_read_ack(struct drm_dp_sideband_msg_rx *raw,
813                                                       struct drm_dp_sideband_msg_reply_body *repmsg)
814 {
815         int idx = 1;
816
817         repmsg->u.remote_i2c_read_ack.port_number = (raw->msg[idx] & 0xf);
818         idx++;
819         if (idx > raw->curlen)
820                 goto fail_len;
821         repmsg->u.remote_i2c_read_ack.num_bytes = raw->msg[idx];
822         idx++;
823         /* TODO check */
824         memcpy(repmsg->u.remote_i2c_read_ack.bytes, &raw->msg[idx], repmsg->u.remote_i2c_read_ack.num_bytes);
825         return true;
826 fail_len:
827         DRM_DEBUG_KMS("remote i2c reply parse length fail %d %d\n", idx, raw->curlen);
828         return false;
829 }
830
831 static bool drm_dp_sideband_parse_enum_path_resources_ack(struct drm_dp_sideband_msg_rx *raw,
832                                                           struct drm_dp_sideband_msg_reply_body *repmsg)
833 {
834         int idx = 1;
835         repmsg->u.path_resources.port_number = (raw->msg[idx] >> 4) & 0xf;
836         idx++;
837         if (idx > raw->curlen)
838                 goto fail_len;
839         repmsg->u.path_resources.full_payload_bw_number = (raw->msg[idx] << 8) | (raw->msg[idx+1]);
840         idx += 2;
841         if (idx > raw->curlen)
842                 goto fail_len;
843         repmsg->u.path_resources.avail_payload_bw_number = (raw->msg[idx] << 8) | (raw->msg[idx+1]);
844         idx += 2;
845         if (idx > raw->curlen)
846                 goto fail_len;
847         return true;
848 fail_len:
849         DRM_DEBUG_KMS("enum resource parse length fail %d %d\n", idx, raw->curlen);
850         return false;
851 }
852
853 static bool drm_dp_sideband_parse_allocate_payload_ack(struct drm_dp_sideband_msg_rx *raw,
854                                                           struct drm_dp_sideband_msg_reply_body *repmsg)
855 {
856         int idx = 1;
857         repmsg->u.allocate_payload.port_number = (raw->msg[idx] >> 4) & 0xf;
858         idx++;
859         if (idx > raw->curlen)
860                 goto fail_len;
861         repmsg->u.allocate_payload.vcpi = raw->msg[idx];
862         idx++;
863         if (idx > raw->curlen)
864                 goto fail_len;
865         repmsg->u.allocate_payload.allocated_pbn = (raw->msg[idx] << 8) | (raw->msg[idx+1]);
866         idx += 2;
867         if (idx > raw->curlen)
868                 goto fail_len;
869         return true;
870 fail_len:
871         DRM_DEBUG_KMS("allocate payload parse length fail %d %d\n", idx, raw->curlen);
872         return false;
873 }
874
875 static bool drm_dp_sideband_parse_query_payload_ack(struct drm_dp_sideband_msg_rx *raw,
876                                                     struct drm_dp_sideband_msg_reply_body *repmsg)
877 {
878         int idx = 1;
879         repmsg->u.query_payload.port_number = (raw->msg[idx] >> 4) & 0xf;
880         idx++;
881         if (idx > raw->curlen)
882                 goto fail_len;
883         repmsg->u.query_payload.allocated_pbn = (raw->msg[idx] << 8) | (raw->msg[idx + 1]);
884         idx += 2;
885         if (idx > raw->curlen)
886                 goto fail_len;
887         return true;
888 fail_len:
889         DRM_DEBUG_KMS("query payload parse length fail %d %d\n", idx, raw->curlen);
890         return false;
891 }
892
893 static bool drm_dp_sideband_parse_power_updown_phy_ack(struct drm_dp_sideband_msg_rx *raw,
894                                                        struct drm_dp_sideband_msg_reply_body *repmsg)
895 {
896         int idx = 1;
897
898         repmsg->u.port_number.port_number = (raw->msg[idx] >> 4) & 0xf;
899         idx++;
900         if (idx > raw->curlen) {
901                 DRM_DEBUG_KMS("power up/down phy parse length fail %d %d\n",
902                               idx, raw->curlen);
903                 return false;
904         }
905         return true;
906 }
907
908 static bool drm_dp_sideband_parse_reply(struct drm_dp_sideband_msg_rx *raw,
909                                         struct drm_dp_sideband_msg_reply_body *msg)
910 {
911         memset(msg, 0, sizeof(*msg));
912         msg->reply_type = (raw->msg[0] & 0x80) >> 7;
913         msg->req_type = (raw->msg[0] & 0x7f);
914
915         if (msg->reply_type == DP_SIDEBAND_REPLY_NAK) {
916                 memcpy(msg->u.nak.guid, &raw->msg[1], 16);
917                 msg->u.nak.reason = raw->msg[17];
918                 msg->u.nak.nak_data = raw->msg[18];
919                 return false;
920         }
921
922         switch (msg->req_type) {
923         case DP_LINK_ADDRESS:
924                 return drm_dp_sideband_parse_link_address(raw, msg);
925         case DP_QUERY_PAYLOAD:
926                 return drm_dp_sideband_parse_query_payload_ack(raw, msg);
927         case DP_REMOTE_DPCD_READ:
928                 return drm_dp_sideband_parse_remote_dpcd_read(raw, msg);
929         case DP_REMOTE_DPCD_WRITE:
930                 return drm_dp_sideband_parse_remote_dpcd_write(raw, msg);
931         case DP_REMOTE_I2C_READ:
932                 return drm_dp_sideband_parse_remote_i2c_read_ack(raw, msg);
933         case DP_ENUM_PATH_RESOURCES:
934                 return drm_dp_sideband_parse_enum_path_resources_ack(raw, msg);
935         case DP_ALLOCATE_PAYLOAD:
936                 return drm_dp_sideband_parse_allocate_payload_ack(raw, msg);
937         case DP_POWER_DOWN_PHY:
938         case DP_POWER_UP_PHY:
939                 return drm_dp_sideband_parse_power_updown_phy_ack(raw, msg);
940         default:
941                 DRM_ERROR("Got unknown reply 0x%02x (%s)\n", msg->req_type,
942                           drm_dp_mst_req_type_str(msg->req_type));
943                 return false;
944         }
945 }
946
947 static bool drm_dp_sideband_parse_connection_status_notify(struct drm_dp_sideband_msg_rx *raw,
948                                                            struct drm_dp_sideband_msg_req_body *msg)
949 {
950         int idx = 1;
951
952         msg->u.conn_stat.port_number = (raw->msg[idx] & 0xf0) >> 4;
953         idx++;
954         if (idx > raw->curlen)
955                 goto fail_len;
956
957         memcpy(msg->u.conn_stat.guid, &raw->msg[idx], 16);
958         idx += 16;
959         if (idx > raw->curlen)
960                 goto fail_len;
961
962         msg->u.conn_stat.legacy_device_plug_status = (raw->msg[idx] >> 6) & 0x1;
963         msg->u.conn_stat.displayport_device_plug_status = (raw->msg[idx] >> 5) & 0x1;
964         msg->u.conn_stat.message_capability_status = (raw->msg[idx] >> 4) & 0x1;
965         msg->u.conn_stat.input_port = (raw->msg[idx] >> 3) & 0x1;
966         msg->u.conn_stat.peer_device_type = (raw->msg[idx] & 0x7);
967         idx++;
968         return true;
969 fail_len:
970         DRM_DEBUG_KMS("connection status reply parse length fail %d %d\n", idx, raw->curlen);
971         return false;
972 }
973
974 static bool drm_dp_sideband_parse_resource_status_notify(struct drm_dp_sideband_msg_rx *raw,
975                                                            struct drm_dp_sideband_msg_req_body *msg)
976 {
977         int idx = 1;
978
979         msg->u.resource_stat.port_number = (raw->msg[idx] & 0xf0) >> 4;
980         idx++;
981         if (idx > raw->curlen)
982                 goto fail_len;
983
984         memcpy(msg->u.resource_stat.guid, &raw->msg[idx], 16);
985         idx += 16;
986         if (idx > raw->curlen)
987                 goto fail_len;
988
989         msg->u.resource_stat.available_pbn = (raw->msg[idx] << 8) | (raw->msg[idx + 1]);
990         idx++;
991         return true;
992 fail_len:
993         DRM_DEBUG_KMS("resource status reply parse length fail %d %d\n", idx, raw->curlen);
994         return false;
995 }
996
997 static bool drm_dp_sideband_parse_req(struct drm_dp_sideband_msg_rx *raw,
998                                       struct drm_dp_sideband_msg_req_body *msg)
999 {
1000         memset(msg, 0, sizeof(*msg));
1001         msg->req_type = (raw->msg[0] & 0x7f);
1002
1003         switch (msg->req_type) {
1004         case DP_CONNECTION_STATUS_NOTIFY:
1005                 return drm_dp_sideband_parse_connection_status_notify(raw, msg);
1006         case DP_RESOURCE_STATUS_NOTIFY:
1007                 return drm_dp_sideband_parse_resource_status_notify(raw, msg);
1008         default:
1009                 DRM_ERROR("Got unknown request 0x%02x (%s)\n", msg->req_type,
1010                           drm_dp_mst_req_type_str(msg->req_type));
1011                 return false;
1012         }
1013 }
1014
1015 static int build_dpcd_write(struct drm_dp_sideband_msg_tx *msg, u8 port_num, u32 offset, u8 num_bytes, u8 *bytes)
1016 {
1017         struct drm_dp_sideband_msg_req_body req;
1018
1019         req.req_type = DP_REMOTE_DPCD_WRITE;
1020         req.u.dpcd_write.port_number = port_num;
1021         req.u.dpcd_write.dpcd_address = offset;
1022         req.u.dpcd_write.num_bytes = num_bytes;
1023         req.u.dpcd_write.bytes = bytes;
1024         drm_dp_encode_sideband_req(&req, msg);
1025
1026         return 0;
1027 }
1028
1029 static int build_link_address(struct drm_dp_sideband_msg_tx *msg)
1030 {
1031         struct drm_dp_sideband_msg_req_body req;
1032
1033         req.req_type = DP_LINK_ADDRESS;
1034         drm_dp_encode_sideband_req(&req, msg);
1035         return 0;
1036 }
1037
1038 static int build_enum_path_resources(struct drm_dp_sideband_msg_tx *msg, int port_num)
1039 {
1040         struct drm_dp_sideband_msg_req_body req;
1041
1042         req.req_type = DP_ENUM_PATH_RESOURCES;
1043         req.u.port_num.port_number = port_num;
1044         drm_dp_encode_sideband_req(&req, msg);
1045         msg->path_msg = true;
1046         return 0;
1047 }
1048
1049 static int build_allocate_payload(struct drm_dp_sideband_msg_tx *msg, int port_num,
1050                                   u8 vcpi, uint16_t pbn,
1051                                   u8 number_sdp_streams,
1052                                   u8 *sdp_stream_sink)
1053 {
1054         struct drm_dp_sideband_msg_req_body req;
1055         memset(&req, 0, sizeof(req));
1056         req.req_type = DP_ALLOCATE_PAYLOAD;
1057         req.u.allocate_payload.port_number = port_num;
1058         req.u.allocate_payload.vcpi = vcpi;
1059         req.u.allocate_payload.pbn = pbn;
1060         req.u.allocate_payload.number_sdp_streams = number_sdp_streams;
1061         memcpy(req.u.allocate_payload.sdp_stream_sink, sdp_stream_sink,
1062                    number_sdp_streams);
1063         drm_dp_encode_sideband_req(&req, msg);
1064         msg->path_msg = true;
1065         return 0;
1066 }
1067
1068 static int build_power_updown_phy(struct drm_dp_sideband_msg_tx *msg,
1069                                   int port_num, bool power_up)
1070 {
1071         struct drm_dp_sideband_msg_req_body req;
1072
1073         if (power_up)
1074                 req.req_type = DP_POWER_UP_PHY;
1075         else
1076                 req.req_type = DP_POWER_DOWN_PHY;
1077
1078         req.u.port_num.port_number = port_num;
1079         drm_dp_encode_sideband_req(&req, msg);
1080         msg->path_msg = true;
1081         return 0;
1082 }
1083
1084 static int drm_dp_mst_assign_payload_id(struct drm_dp_mst_topology_mgr *mgr,
1085                                         struct drm_dp_vcpi *vcpi)
1086 {
1087         int ret, vcpi_ret;
1088
1089         mutex_lock(&mgr->payload_lock);
1090         ret = find_first_zero_bit(&mgr->payload_mask, mgr->max_payloads + 1);
1091         if (ret > mgr->max_payloads) {
1092                 ret = -EINVAL;
1093                 DRM_DEBUG_KMS("out of payload ids %d\n", ret);
1094                 goto out_unlock;
1095         }
1096
1097         vcpi_ret = find_first_zero_bit(&mgr->vcpi_mask, mgr->max_payloads + 1);
1098         if (vcpi_ret > mgr->max_payloads) {
1099                 ret = -EINVAL;
1100                 DRM_DEBUG_KMS("out of vcpi ids %d\n", ret);
1101                 goto out_unlock;
1102         }
1103
1104         set_bit(ret, &mgr->payload_mask);
1105         set_bit(vcpi_ret, &mgr->vcpi_mask);
1106         vcpi->vcpi = vcpi_ret + 1;
1107         mgr->proposed_vcpis[ret - 1] = vcpi;
1108 out_unlock:
1109         mutex_unlock(&mgr->payload_lock);
1110         return ret;
1111 }
1112
1113 static void drm_dp_mst_put_payload_id(struct drm_dp_mst_topology_mgr *mgr,
1114                                       int vcpi)
1115 {
1116         int i;
1117         if (vcpi == 0)
1118                 return;
1119
1120         mutex_lock(&mgr->payload_lock);
1121         DRM_DEBUG_KMS("putting payload %d\n", vcpi);
1122         clear_bit(vcpi - 1, &mgr->vcpi_mask);
1123
1124         for (i = 0; i < mgr->max_payloads; i++) {
1125                 if (mgr->proposed_vcpis[i] &&
1126                     mgr->proposed_vcpis[i]->vcpi == vcpi) {
1127                         mgr->proposed_vcpis[i] = NULL;
1128                         clear_bit(i + 1, &mgr->payload_mask);
1129                 }
1130         }
1131         mutex_unlock(&mgr->payload_lock);
1132 }
1133
1134 static bool check_txmsg_state(struct drm_dp_mst_topology_mgr *mgr,
1135                               struct drm_dp_sideband_msg_tx *txmsg)
1136 {
1137         unsigned int state;
1138
1139         /*
1140          * All updates to txmsg->state are protected by mgr->qlock, and the two
1141          * cases we check here are terminal states. For those the barriers
1142          * provided by the wake_up/wait_event pair are enough.
1143          */
1144         state = READ_ONCE(txmsg->state);
1145         return (state == DRM_DP_SIDEBAND_TX_RX ||
1146                 state == DRM_DP_SIDEBAND_TX_TIMEOUT);
1147 }
1148
1149 static int drm_dp_mst_wait_tx_reply(struct drm_dp_mst_branch *mstb,
1150                                     struct drm_dp_sideband_msg_tx *txmsg)
1151 {
1152         struct drm_dp_mst_topology_mgr *mgr = mstb->mgr;
1153         int ret;
1154
1155         ret = wait_event_timeout(mgr->tx_waitq,
1156                                  check_txmsg_state(mgr, txmsg),
1157                                  (4 * HZ));
1158         mutex_lock(&mstb->mgr->qlock);
1159         if (ret > 0) {
1160                 if (txmsg->state == DRM_DP_SIDEBAND_TX_TIMEOUT) {
1161                         ret = -EIO;
1162                         goto out;
1163                 }
1164         } else {
1165                 DRM_DEBUG_KMS("timedout msg send %p %d %d\n", txmsg, txmsg->state, txmsg->seqno);
1166
1167                 /* dump some state */
1168                 ret = -EIO;
1169
1170                 /* remove from q */
1171                 if (txmsg->state == DRM_DP_SIDEBAND_TX_QUEUED ||
1172                     txmsg->state == DRM_DP_SIDEBAND_TX_START_SEND) {
1173                         list_del(&txmsg->next);
1174                 }
1175
1176                 if (txmsg->state == DRM_DP_SIDEBAND_TX_START_SEND ||
1177                     txmsg->state == DRM_DP_SIDEBAND_TX_SENT) {
1178                         mstb->tx_slots[txmsg->seqno] = NULL;
1179                 }
1180         }
1181 out:
1182         if (unlikely(ret == -EIO) && drm_debug_enabled(DRM_UT_DP)) {
1183                 struct drm_printer p = drm_debug_printer(DBG_PREFIX);
1184
1185                 drm_dp_mst_dump_sideband_msg_tx(&p, txmsg);
1186         }
1187         mutex_unlock(&mgr->qlock);
1188
1189         return ret;
1190 }
1191
1192 static struct drm_dp_mst_branch *drm_dp_add_mst_branch_device(u8 lct, u8 *rad)
1193 {
1194         struct drm_dp_mst_branch *mstb;
1195
1196         mstb = kzalloc(sizeof(*mstb), GFP_KERNEL);
1197         if (!mstb)
1198                 return NULL;
1199
1200         mstb->lct = lct;
1201         if (lct > 1)
1202                 memcpy(mstb->rad, rad, lct / 2);
1203         INIT_LIST_HEAD(&mstb->ports);
1204         kref_init(&mstb->topology_kref);
1205         kref_init(&mstb->malloc_kref);
1206         return mstb;
1207 }
1208
1209 static void drm_dp_free_mst_branch_device(struct kref *kref)
1210 {
1211         struct drm_dp_mst_branch *mstb =
1212                 container_of(kref, struct drm_dp_mst_branch, malloc_kref);
1213
1214         if (mstb->port_parent)
1215                 drm_dp_mst_put_port_malloc(mstb->port_parent);
1216
1217         kfree(mstb);
1218 }
1219
1220 /**
1221  * DOC: Branch device and port refcounting
1222  *
1223  * Topology refcount overview
1224  * ~~~~~~~~~~~~~~~~~~~~~~~~~~
1225  *
1226  * The refcounting schemes for &struct drm_dp_mst_branch and &struct
1227  * drm_dp_mst_port are somewhat unusual. Both ports and branch devices have
1228  * two different kinds of refcounts: topology refcounts, and malloc refcounts.
1229  *
1230  * Topology refcounts are not exposed to drivers, and are handled internally
1231  * by the DP MST helpers. The helpers use them in order to prevent the
1232  * in-memory topology state from being changed in the middle of critical
1233  * operations like changing the internal state of payload allocations. This
1234  * means each branch and port will be considered to be connected to the rest
1235  * of the topology until its topology refcount reaches zero. Additionally,
1236  * for ports this means that their associated &struct drm_connector will stay
1237  * registered with userspace until the port's refcount reaches 0.
1238  *
1239  * Malloc refcount overview
1240  * ~~~~~~~~~~~~~~~~~~~~~~~~
1241  *
1242  * Malloc references are used to keep a &struct drm_dp_mst_port or &struct
1243  * drm_dp_mst_branch allocated even after all of its topology references have
1244  * been dropped, so that the driver or MST helpers can safely access each
1245  * branch's last known state before it was disconnected from the topology.
1246  * When the malloc refcount of a port or branch reaches 0, the memory
1247  * allocation containing the &struct drm_dp_mst_branch or &struct
1248  * drm_dp_mst_port respectively will be freed.
1249  *
1250  * For &struct drm_dp_mst_branch, malloc refcounts are not currently exposed
1251  * to drivers. As of writing this documentation, there are no drivers that
1252  * have a usecase for accessing &struct drm_dp_mst_branch outside of the MST
1253  * helpers. Exposing this API to drivers in a race-free manner would take more
1254  * tweaking of the refcounting scheme, however patches are welcome provided
1255  * there is a legitimate driver usecase for this.
1256  *
1257  * Refcount relationships in a topology
1258  * ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1259  *
1260  * Let's take a look at why the relationship between topology and malloc
1261  * refcounts is designed the way it is.
1262  *
1263  * .. kernel-figure:: dp-mst/topology-figure-1.dot
1264  *
1265  *    An example of topology and malloc refs in a DP MST topology with two
1266  *    active payloads. Topology refcount increments are indicated by solid
1267  *    lines, and malloc refcount increments are indicated by dashed lines.
1268  *    Each starts from the branch which incremented the refcount, and ends at
1269  *    the branch to which the refcount belongs to, i.e. the arrow points the
1270  *    same way as the C pointers used to reference a structure.
1271  *
1272  * As you can see in the above figure, every branch increments the topology
1273  * refcount of its children, and increments the malloc refcount of its
1274  * parent. Additionally, every payload increments the malloc refcount of its
1275  * assigned port by 1.
1276  *
1277  * So, what would happen if MSTB #3 from the above figure was unplugged from
1278  * the system, but the driver hadn't yet removed payload #2 from port #3? The
1279  * topology would start to look like the figure below.
1280  *
1281  * .. kernel-figure:: dp-mst/topology-figure-2.dot
1282  *
1283  *    Ports and branch devices which have been released from memory are
1284  *    colored grey, and references which have been removed are colored red.
1285  *
1286  * Whenever a port or branch device's topology refcount reaches zero, it will
1287  * decrement the topology refcounts of all its children, the malloc refcount
1288  * of its parent, and finally its own malloc refcount. For MSTB #4 and port
1289  * #4, this means they both have been disconnected from the topology and freed
1290  * from memory. But, because payload #2 is still holding a reference to port
1291  * #3, port #3 is removed from the topology but its &struct drm_dp_mst_port
1292  * is still accessible from memory. This also means port #3 has not yet
1293  * decremented the malloc refcount of MSTB #3, so its &struct
1294  * drm_dp_mst_branch will also stay allocated in memory until port #3's
1295  * malloc refcount reaches 0.
1296  *
1297  * This relationship is necessary because in order to release payload #2, we
1298  * need to be able to figure out the last relative of port #3 that's still
1299  * connected to the topology. In this case, we would travel up the topology as
1300  * shown below.
1301  *
1302  * .. kernel-figure:: dp-mst/topology-figure-3.dot
1303  *
1304  * And finally, remove payload #2 by communicating with port #2 through
1305  * sideband transactions.
1306  */
1307
1308 /**
1309  * drm_dp_mst_get_mstb_malloc() - Increment the malloc refcount of a branch
1310  * device
1311  * @mstb: The &struct drm_dp_mst_branch to increment the malloc refcount of
1312  *
1313  * Increments &drm_dp_mst_branch.malloc_kref. When
1314  * &drm_dp_mst_branch.malloc_kref reaches 0, the memory allocation for @mstb
1315  * will be released and @mstb may no longer be used.
1316  *
1317  * See also: drm_dp_mst_put_mstb_malloc()
1318  */
1319 static void
1320 drm_dp_mst_get_mstb_malloc(struct drm_dp_mst_branch *mstb)
1321 {
1322         kref_get(&mstb->malloc_kref);
1323         DRM_DEBUG("mstb %p (%d)\n", mstb, kref_read(&mstb->malloc_kref));
1324 }
1325
1326 /**
1327  * drm_dp_mst_put_mstb_malloc() - Decrement the malloc refcount of a branch
1328  * device
1329  * @mstb: The &struct drm_dp_mst_branch to decrement the malloc refcount of
1330  *
1331  * Decrements &drm_dp_mst_branch.malloc_kref. When
1332  * &drm_dp_mst_branch.malloc_kref reaches 0, the memory allocation for @mstb
1333  * will be released and @mstb may no longer be used.
1334  *
1335  * See also: drm_dp_mst_get_mstb_malloc()
1336  */
1337 static void
1338 drm_dp_mst_put_mstb_malloc(struct drm_dp_mst_branch *mstb)
1339 {
1340         DRM_DEBUG("mstb %p (%d)\n", mstb, kref_read(&mstb->malloc_kref) - 1);
1341         kref_put(&mstb->malloc_kref, drm_dp_free_mst_branch_device);
1342 }
1343
1344 static void drm_dp_free_mst_port(struct kref *kref)
1345 {
1346         struct drm_dp_mst_port *port =
1347                 container_of(kref, struct drm_dp_mst_port, malloc_kref);
1348
1349         drm_dp_mst_put_mstb_malloc(port->parent);
1350         kfree(port);
1351 }
1352
1353 /**
1354  * drm_dp_mst_get_port_malloc() - Increment the malloc refcount of an MST port
1355  * @port: The &struct drm_dp_mst_port to increment the malloc refcount of
1356  *
1357  * Increments &drm_dp_mst_port.malloc_kref. When &drm_dp_mst_port.malloc_kref
1358  * reaches 0, the memory allocation for @port will be released and @port may
1359  * no longer be used.
1360  *
1361  * Because @port could potentially be freed at any time by the DP MST helpers
1362  * if &drm_dp_mst_port.malloc_kref reaches 0, including during a call to this
1363  * function, drivers that which to make use of &struct drm_dp_mst_port should
1364  * ensure that they grab at least one main malloc reference to their MST ports
1365  * in &drm_dp_mst_topology_cbs.add_connector. This callback is called before
1366  * there is any chance for &drm_dp_mst_port.malloc_kref to reach 0.
1367  *
1368  * See also: drm_dp_mst_put_port_malloc()
1369  */
1370 void
1371 drm_dp_mst_get_port_malloc(struct drm_dp_mst_port *port)
1372 {
1373         kref_get(&port->malloc_kref);
1374         DRM_DEBUG("port %p (%d)\n", port, kref_read(&port->malloc_kref));
1375 }
1376 EXPORT_SYMBOL(drm_dp_mst_get_port_malloc);
1377
1378 /**
1379  * drm_dp_mst_put_port_malloc() - Decrement the malloc refcount of an MST port
1380  * @port: The &struct drm_dp_mst_port to decrement the malloc refcount of
1381  *
1382  * Decrements &drm_dp_mst_port.malloc_kref. When &drm_dp_mst_port.malloc_kref
1383  * reaches 0, the memory allocation for @port will be released and @port may
1384  * no longer be used.
1385  *
1386  * See also: drm_dp_mst_get_port_malloc()
1387  */
1388 void
1389 drm_dp_mst_put_port_malloc(struct drm_dp_mst_port *port)
1390 {
1391         DRM_DEBUG("port %p (%d)\n", port, kref_read(&port->malloc_kref) - 1);
1392         kref_put(&port->malloc_kref, drm_dp_free_mst_port);
1393 }
1394 EXPORT_SYMBOL(drm_dp_mst_put_port_malloc);
1395
1396 static void drm_dp_destroy_mst_branch_device(struct kref *kref)
1397 {
1398         struct drm_dp_mst_branch *mstb =
1399                 container_of(kref, struct drm_dp_mst_branch, topology_kref);
1400         struct drm_dp_mst_topology_mgr *mgr = mstb->mgr;
1401         struct drm_dp_mst_port *port, *tmp;
1402         bool wake_tx = false;
1403
1404         mutex_lock(&mgr->lock);
1405         list_for_each_entry_safe(port, tmp, &mstb->ports, next) {
1406                 list_del(&port->next);
1407                 drm_dp_mst_topology_put_port(port);
1408         }
1409         mutex_unlock(&mgr->lock);
1410
1411         /* drop any tx slots msg */
1412         mutex_lock(&mstb->mgr->qlock);
1413         if (mstb->tx_slots[0]) {
1414                 mstb->tx_slots[0]->state = DRM_DP_SIDEBAND_TX_TIMEOUT;
1415                 mstb->tx_slots[0] = NULL;
1416                 wake_tx = true;
1417         }
1418         if (mstb->tx_slots[1]) {
1419                 mstb->tx_slots[1]->state = DRM_DP_SIDEBAND_TX_TIMEOUT;
1420                 mstb->tx_slots[1] = NULL;
1421                 wake_tx = true;
1422         }
1423         mutex_unlock(&mstb->mgr->qlock);
1424
1425         if (wake_tx)
1426                 wake_up_all(&mstb->mgr->tx_waitq);
1427
1428         drm_dp_mst_put_mstb_malloc(mstb);
1429 }
1430
1431 /**
1432  * drm_dp_mst_topology_try_get_mstb() - Increment the topology refcount of a
1433  * branch device unless it's zero
1434  * @mstb: &struct drm_dp_mst_branch to increment the topology refcount of
1435  *
1436  * Attempts to grab a topology reference to @mstb, if it hasn't yet been
1437  * removed from the topology (e.g. &drm_dp_mst_branch.topology_kref has
1438  * reached 0). Holding a topology reference implies that a malloc reference
1439  * will be held to @mstb as long as the user holds the topology reference.
1440  *
1441  * Care should be taken to ensure that the user has at least one malloc
1442  * reference to @mstb. If you already have a topology reference to @mstb, you
1443  * should use drm_dp_mst_topology_get_mstb() instead.
1444  *
1445  * See also:
1446  * drm_dp_mst_topology_get_mstb()
1447  * drm_dp_mst_topology_put_mstb()
1448  *
1449  * Returns:
1450  * * 1: A topology reference was grabbed successfully
1451  * * 0: @port is no longer in the topology, no reference was grabbed
1452  */
1453 static int __must_check
1454 drm_dp_mst_topology_try_get_mstb(struct drm_dp_mst_branch *mstb)
1455 {
1456         int ret = kref_get_unless_zero(&mstb->topology_kref);
1457
1458         if (ret)
1459                 DRM_DEBUG("mstb %p (%d)\n", mstb,
1460                           kref_read(&mstb->topology_kref));
1461
1462         return ret;
1463 }
1464
1465 /**
1466  * drm_dp_mst_topology_get_mstb() - Increment the topology refcount of a
1467  * branch device
1468  * @mstb: The &struct drm_dp_mst_branch to increment the topology refcount of
1469  *
1470  * Increments &drm_dp_mst_branch.topology_refcount without checking whether or
1471  * not it's already reached 0. This is only valid to use in scenarios where
1472  * you are already guaranteed to have at least one active topology reference
1473  * to @mstb. Otherwise, drm_dp_mst_topology_try_get_mstb() must be used.
1474  *
1475  * See also:
1476  * drm_dp_mst_topology_try_get_mstb()
1477  * drm_dp_mst_topology_put_mstb()
1478  */
1479 static void drm_dp_mst_topology_get_mstb(struct drm_dp_mst_branch *mstb)
1480 {
1481         WARN_ON(kref_read(&mstb->topology_kref) == 0);
1482         kref_get(&mstb->topology_kref);
1483         DRM_DEBUG("mstb %p (%d)\n", mstb, kref_read(&mstb->topology_kref));
1484 }
1485
1486 /**
1487  * drm_dp_mst_topology_put_mstb() - release a topology reference to a branch
1488  * device
1489  * @mstb: The &struct drm_dp_mst_branch to release the topology reference from
1490  *
1491  * Releases a topology reference from @mstb by decrementing
1492  * &drm_dp_mst_branch.topology_kref.
1493  *
1494  * See also:
1495  * drm_dp_mst_topology_try_get_mstb()
1496  * drm_dp_mst_topology_get_mstb()
1497  */
1498 static void
1499 drm_dp_mst_topology_put_mstb(struct drm_dp_mst_branch *mstb)
1500 {
1501         DRM_DEBUG("mstb %p (%d)\n",
1502                   mstb, kref_read(&mstb->topology_kref) - 1);
1503         kref_put(&mstb->topology_kref, drm_dp_destroy_mst_branch_device);
1504 }
1505
1506 static void drm_dp_port_teardown_pdt(struct drm_dp_mst_port *port, int old_pdt)
1507 {
1508         struct drm_dp_mst_branch *mstb;
1509
1510         switch (old_pdt) {
1511         case DP_PEER_DEVICE_DP_LEGACY_CONV:
1512         case DP_PEER_DEVICE_SST_SINK:
1513                 /* remove i2c over sideband */
1514                 drm_dp_mst_unregister_i2c_bus(&port->aux);
1515                 break;
1516         case DP_PEER_DEVICE_MST_BRANCHING:
1517                 mstb = port->mstb;
1518                 port->mstb = NULL;
1519                 drm_dp_mst_topology_put_mstb(mstb);
1520                 break;
1521         }
1522 }
1523
1524 static void drm_dp_destroy_port(struct kref *kref)
1525 {
1526         struct drm_dp_mst_port *port =
1527                 container_of(kref, struct drm_dp_mst_port, topology_kref);
1528         struct drm_dp_mst_topology_mgr *mgr = port->mgr;
1529
1530         if (!port->input) {
1531                 kfree(port->cached_edid);
1532
1533                 /*
1534                  * The only time we don't have a connector
1535                  * on an output port is if the connector init
1536                  * fails.
1537                  */
1538                 if (port->connector) {
1539                         /* we can't destroy the connector here, as
1540                          * we might be holding the mode_config.mutex
1541                          * from an EDID retrieval */
1542
1543                         mutex_lock(&mgr->destroy_connector_lock);
1544                         list_add(&port->next, &mgr->destroy_connector_list);
1545                         mutex_unlock(&mgr->destroy_connector_lock);
1546                         schedule_work(&mgr->destroy_connector_work);
1547                         return;
1548                 }
1549                 /* no need to clean up vcpi
1550                  * as if we have no connector we never setup a vcpi */
1551                 drm_dp_port_teardown_pdt(port, port->pdt);
1552                 port->pdt = DP_PEER_DEVICE_NONE;
1553         }
1554         drm_dp_mst_put_port_malloc(port);
1555 }
1556
1557 /**
1558  * drm_dp_mst_topology_try_get_port() - Increment the topology refcount of a
1559  * port unless it's zero
1560  * @port: &struct drm_dp_mst_port to increment the topology refcount of
1561  *
1562  * Attempts to grab a topology reference to @port, if it hasn't yet been
1563  * removed from the topology (e.g. &drm_dp_mst_port.topology_kref has reached
1564  * 0). Holding a topology reference implies that a malloc reference will be
1565  * held to @port as long as the user holds the topology reference.
1566  *
1567  * Care should be taken to ensure that the user has at least one malloc
1568  * reference to @port. If you already have a topology reference to @port, you
1569  * should use drm_dp_mst_topology_get_port() instead.
1570  *
1571  * See also:
1572  * drm_dp_mst_topology_get_port()
1573  * drm_dp_mst_topology_put_port()
1574  *
1575  * Returns:
1576  * * 1: A topology reference was grabbed successfully
1577  * * 0: @port is no longer in the topology, no reference was grabbed
1578  */
1579 static int __must_check
1580 drm_dp_mst_topology_try_get_port(struct drm_dp_mst_port *port)
1581 {
1582         int ret = kref_get_unless_zero(&port->topology_kref);
1583
1584         if (ret)
1585                 DRM_DEBUG("port %p (%d)\n", port,
1586                           kref_read(&port->topology_kref));
1587
1588         return ret;
1589 }
1590
1591 /**
1592  * drm_dp_mst_topology_get_port() - Increment the topology refcount of a port
1593  * @port: The &struct drm_dp_mst_port to increment the topology refcount of
1594  *
1595  * Increments &drm_dp_mst_port.topology_refcount without checking whether or
1596  * not it's already reached 0. This is only valid to use in scenarios where
1597  * you are already guaranteed to have at least one active topology reference
1598  * to @port. Otherwise, drm_dp_mst_topology_try_get_port() must be used.
1599  *
1600  * See also:
1601  * drm_dp_mst_topology_try_get_port()
1602  * drm_dp_mst_topology_put_port()
1603  */
1604 static void drm_dp_mst_topology_get_port(struct drm_dp_mst_port *port)
1605 {
1606         WARN_ON(kref_read(&port->topology_kref) == 0);
1607         kref_get(&port->topology_kref);
1608         DRM_DEBUG("port %p (%d)\n", port, kref_read(&port->topology_kref));
1609 }
1610
1611 /**
1612  * drm_dp_mst_topology_put_port() - release a topology reference to a port
1613  * @port: The &struct drm_dp_mst_port to release the topology reference from
1614  *
1615  * Releases a topology reference from @port by decrementing
1616  * &drm_dp_mst_port.topology_kref.
1617  *
1618  * See also:
1619  * drm_dp_mst_topology_try_get_port()
1620  * drm_dp_mst_topology_get_port()
1621  */
1622 static void drm_dp_mst_topology_put_port(struct drm_dp_mst_port *port)
1623 {
1624         DRM_DEBUG("port %p (%d)\n",
1625                   port, kref_read(&port->topology_kref) - 1);
1626         kref_put(&port->topology_kref, drm_dp_destroy_port);
1627 }
1628
1629 static struct drm_dp_mst_branch *
1630 drm_dp_mst_topology_get_mstb_validated_locked(struct drm_dp_mst_branch *mstb,
1631                                               struct drm_dp_mst_branch *to_find)
1632 {
1633         struct drm_dp_mst_port *port;
1634         struct drm_dp_mst_branch *rmstb;
1635
1636         if (to_find == mstb)
1637                 return mstb;
1638
1639         list_for_each_entry(port, &mstb->ports, next) {
1640                 if (port->mstb) {
1641                         rmstb = drm_dp_mst_topology_get_mstb_validated_locked(
1642                             port->mstb, to_find);
1643                         if (rmstb)
1644                                 return rmstb;
1645                 }
1646         }
1647         return NULL;
1648 }
1649
1650 static struct drm_dp_mst_branch *
1651 drm_dp_mst_topology_get_mstb_validated(struct drm_dp_mst_topology_mgr *mgr,
1652                                        struct drm_dp_mst_branch *mstb)
1653 {
1654         struct drm_dp_mst_branch *rmstb = NULL;
1655
1656         mutex_lock(&mgr->lock);
1657         if (mgr->mst_primary) {
1658                 rmstb = drm_dp_mst_topology_get_mstb_validated_locked(
1659                     mgr->mst_primary, mstb);
1660
1661                 if (rmstb && !drm_dp_mst_topology_try_get_mstb(rmstb))
1662                         rmstb = NULL;
1663         }
1664         mutex_unlock(&mgr->lock);
1665         return rmstb;
1666 }
1667
1668 static struct drm_dp_mst_port *
1669 drm_dp_mst_topology_get_port_validated_locked(struct drm_dp_mst_branch *mstb,
1670                                               struct drm_dp_mst_port *to_find)
1671 {
1672         struct drm_dp_mst_port *port, *mport;
1673
1674         list_for_each_entry(port, &mstb->ports, next) {
1675                 if (port == to_find)
1676                         return port;
1677
1678                 if (port->mstb) {
1679                         mport = drm_dp_mst_topology_get_port_validated_locked(
1680                             port->mstb, to_find);
1681                         if (mport)
1682                                 return mport;
1683                 }
1684         }
1685         return NULL;
1686 }
1687
1688 static struct drm_dp_mst_port *
1689 drm_dp_mst_topology_get_port_validated(struct drm_dp_mst_topology_mgr *mgr,
1690                                        struct drm_dp_mst_port *port)
1691 {
1692         struct drm_dp_mst_port *rport = NULL;
1693
1694         mutex_lock(&mgr->lock);
1695         if (mgr->mst_primary) {
1696                 rport = drm_dp_mst_topology_get_port_validated_locked(
1697                     mgr->mst_primary, port);
1698
1699                 if (rport && !drm_dp_mst_topology_try_get_port(rport))
1700                         rport = NULL;
1701         }
1702         mutex_unlock(&mgr->lock);
1703         return rport;
1704 }
1705
1706 static struct drm_dp_mst_port *drm_dp_get_port(struct drm_dp_mst_branch *mstb, u8 port_num)
1707 {
1708         struct drm_dp_mst_port *port;
1709         int ret;
1710
1711         list_for_each_entry(port, &mstb->ports, next) {
1712                 if (port->port_num == port_num) {
1713                         ret = drm_dp_mst_topology_try_get_port(port);
1714                         return ret ? port : NULL;
1715                 }
1716         }
1717
1718         return NULL;
1719 }
1720
1721 /*
1722  * calculate a new RAD for this MST branch device
1723  * if parent has an LCT of 2 then it has 1 nibble of RAD,
1724  * if parent has an LCT of 3 then it has 2 nibbles of RAD,
1725  */
1726 static u8 drm_dp_calculate_rad(struct drm_dp_mst_port *port,
1727                                  u8 *rad)
1728 {
1729         int parent_lct = port->parent->lct;
1730         int shift = 4;
1731         int idx = (parent_lct - 1) / 2;
1732         if (parent_lct > 1) {
1733                 memcpy(rad, port->parent->rad, idx + 1);
1734                 shift = (parent_lct % 2) ? 4 : 0;
1735         } else
1736                 rad[0] = 0;
1737
1738         rad[idx] |= port->port_num << shift;
1739         return parent_lct + 1;
1740 }
1741
1742 /*
1743  * return sends link address for new mstb
1744  */
1745 static bool drm_dp_port_setup_pdt(struct drm_dp_mst_port *port)
1746 {
1747         int ret;
1748         u8 rad[6], lct;
1749         bool send_link = false;
1750         switch (port->pdt) {
1751         case DP_PEER_DEVICE_DP_LEGACY_CONV:
1752         case DP_PEER_DEVICE_SST_SINK:
1753                 /* add i2c over sideband */
1754                 ret = drm_dp_mst_register_i2c_bus(&port->aux);
1755                 break;
1756         case DP_PEER_DEVICE_MST_BRANCHING:
1757                 lct = drm_dp_calculate_rad(port, rad);
1758
1759                 port->mstb = drm_dp_add_mst_branch_device(lct, rad);
1760                 if (port->mstb) {
1761                         port->mstb->mgr = port->mgr;
1762                         port->mstb->port_parent = port;
1763                         /*
1764                          * Make sure this port's memory allocation stays
1765                          * around until its child MSTB releases it
1766                          */
1767                         drm_dp_mst_get_port_malloc(port);
1768
1769                         send_link = true;
1770                 }
1771                 break;
1772         }
1773         return send_link;
1774 }
1775
1776 /**
1777  * drm_dp_mst_dpcd_read() - read a series of bytes from the DPCD via sideband
1778  * @aux: Fake sideband AUX CH
1779  * @offset: address of the (first) register to read
1780  * @buffer: buffer to store the register values
1781  * @size: number of bytes in @buffer
1782  *
1783  * Performs the same functionality for remote devices via
1784  * sideband messaging as drm_dp_dpcd_read() does for local
1785  * devices via actual AUX CH.
1786  *
1787  * Return: Number of bytes read, or negative error code on failure.
1788  */
1789 ssize_t drm_dp_mst_dpcd_read(struct drm_dp_aux *aux,
1790                              unsigned int offset, void *buffer, size_t size)
1791 {
1792         struct drm_dp_mst_port *port = container_of(aux, struct drm_dp_mst_port,
1793                                                     aux);
1794
1795         return drm_dp_send_dpcd_read(port->mgr, port,
1796                                      offset, size, buffer);
1797 }
1798
1799 /**
1800  * drm_dp_mst_dpcd_write() - write a series of bytes to the DPCD via sideband
1801  * @aux: Fake sideband AUX CH
1802  * @offset: address of the (first) register to write
1803  * @buffer: buffer containing the values to write
1804  * @size: number of bytes in @buffer
1805  *
1806  * Performs the same functionality for remote devices via
1807  * sideband messaging as drm_dp_dpcd_write() does for local
1808  * devices via actual AUX CH.
1809  *
1810  * Return: 0 on success, negative error code on failure.
1811  */
1812 ssize_t drm_dp_mst_dpcd_write(struct drm_dp_aux *aux,
1813                               unsigned int offset, void *buffer, size_t size)
1814 {
1815         struct drm_dp_mst_port *port = container_of(aux, struct drm_dp_mst_port,
1816                                                     aux);
1817
1818         return drm_dp_send_dpcd_write(port->mgr, port,
1819                                       offset, size, buffer);
1820 }
1821
1822 static void drm_dp_check_mstb_guid(struct drm_dp_mst_branch *mstb, u8 *guid)
1823 {
1824         int ret;
1825
1826         memcpy(mstb->guid, guid, 16);
1827
1828         if (!drm_dp_validate_guid(mstb->mgr, mstb->guid)) {
1829                 if (mstb->port_parent) {
1830                         ret = drm_dp_send_dpcd_write(
1831                                         mstb->mgr,
1832                                         mstb->port_parent,
1833                                         DP_GUID,
1834                                         16,
1835                                         mstb->guid);
1836                 } else {
1837
1838                         ret = drm_dp_dpcd_write(
1839                                         mstb->mgr->aux,
1840                                         DP_GUID,
1841                                         mstb->guid,
1842                                         16);
1843                 }
1844         }
1845 }
1846
1847 static void build_mst_prop_path(const struct drm_dp_mst_branch *mstb,
1848                                 int pnum,
1849                                 char *proppath,
1850                                 size_t proppath_size)
1851 {
1852         int i;
1853         char temp[8];
1854         snprintf(proppath, proppath_size, "mst:%d", mstb->mgr->conn_base_id);
1855         for (i = 0; i < (mstb->lct - 1); i++) {
1856                 int shift = (i % 2) ? 0 : 4;
1857                 int port_num = (mstb->rad[i / 2] >> shift) & 0xf;
1858                 snprintf(temp, sizeof(temp), "-%d", port_num);
1859                 strlcat(proppath, temp, proppath_size);
1860         }
1861         snprintf(temp, sizeof(temp), "-%d", pnum);
1862         strlcat(proppath, temp, proppath_size);
1863 }
1864
1865 /**
1866  * drm_dp_mst_connector_late_register() - Late MST connector registration
1867  * @connector: The MST connector
1868  * @port: The MST port for this connector
1869  *
1870  * Helper to register the remote aux device for this MST port. Drivers should
1871  * call this from their mst connector's late_register hook to enable MST aux
1872  * devices.
1873  *
1874  * Return: 0 on success, negative error code on failure.
1875  */
1876 int drm_dp_mst_connector_late_register(struct drm_connector *connector,
1877                                        struct drm_dp_mst_port *port)
1878 {
1879         DRM_DEBUG_KMS("registering %s remote bus for %s\n",
1880                       port->aux.name, connector->kdev->kobj.name);
1881
1882         port->aux.dev = connector->kdev;
1883         return drm_dp_aux_register_devnode(&port->aux);
1884 }
1885 EXPORT_SYMBOL(drm_dp_mst_connector_late_register);
1886
1887 /**
1888  * drm_dp_mst_connector_early_unregister() - Early MST connector unregistration
1889  * @connector: The MST connector
1890  * @port: The MST port for this connector
1891  *
1892  * Helper to unregister the remote aux device for this MST port, registered by
1893  * drm_dp_mst_connector_late_register(). Drivers should call this from their mst
1894  * connector's early_unregister hook.
1895  */
1896 void drm_dp_mst_connector_early_unregister(struct drm_connector *connector,
1897                                            struct drm_dp_mst_port *port)
1898 {
1899         DRM_DEBUG_KMS("unregistering %s remote bus for %s\n",
1900                       port->aux.name, connector->kdev->kobj.name);
1901         drm_dp_aux_unregister_devnode(&port->aux);
1902 }
1903 EXPORT_SYMBOL(drm_dp_mst_connector_early_unregister);
1904
1905 static void
1906 drm_dp_mst_handle_link_address_port(struct drm_dp_mst_branch *mstb,
1907                                     struct drm_device *dev,
1908                                     struct drm_dp_link_addr_reply_port *port_msg)
1909 {
1910         struct drm_dp_mst_port *port;
1911         bool ret;
1912         bool created = false;
1913         int old_pdt = 0;
1914         int old_ddps = 0;
1915
1916         port = drm_dp_get_port(mstb, port_msg->port_number);
1917         if (!port) {
1918                 port = kzalloc(sizeof(*port), GFP_KERNEL);
1919                 if (!port)
1920                         return;
1921                 kref_init(&port->topology_kref);
1922                 kref_init(&port->malloc_kref);
1923                 port->parent = mstb;
1924                 port->port_num = port_msg->port_number;
1925                 port->mgr = mstb->mgr;
1926                 port->aux.name = "DPMST";
1927                 port->aux.dev = dev->dev;
1928                 port->aux.is_remote = true;
1929
1930                 /*
1931                  * Make sure the memory allocation for our parent branch stays
1932                  * around until our own memory allocation is released
1933                  */
1934                 drm_dp_mst_get_mstb_malloc(mstb);
1935
1936                 created = true;
1937         } else {
1938                 old_pdt = port->pdt;
1939                 old_ddps = port->ddps;
1940         }
1941
1942         port->pdt = port_msg->peer_device_type;
1943         port->input = port_msg->input_port;
1944         port->mcs = port_msg->mcs;
1945         port->ddps = port_msg->ddps;
1946         port->ldps = port_msg->legacy_device_plug_status;
1947         port->dpcd_rev = port_msg->dpcd_revision;
1948         port->num_sdp_streams = port_msg->num_sdp_streams;
1949         port->num_sdp_stream_sinks = port_msg->num_sdp_stream_sinks;
1950
1951         /* manage mstb port lists with mgr lock - take a reference
1952            for this list */
1953         if (created) {
1954                 mutex_lock(&mstb->mgr->lock);
1955                 drm_dp_mst_topology_get_port(port);
1956                 list_add(&port->next, &mstb->ports);
1957                 mutex_unlock(&mstb->mgr->lock);
1958         }
1959
1960         if (old_ddps != port->ddps) {
1961                 if (port->ddps) {
1962                         if (!port->input) {
1963                                 drm_dp_send_enum_path_resources(mstb->mgr,
1964                                                                 mstb, port);
1965                         }
1966                 } else {
1967                         port->available_pbn = 0;
1968                 }
1969         }
1970
1971         if (old_pdt != port->pdt && !port->input) {
1972                 drm_dp_port_teardown_pdt(port, old_pdt);
1973
1974                 ret = drm_dp_port_setup_pdt(port);
1975                 if (ret == true)
1976                         drm_dp_send_link_address(mstb->mgr, port->mstb);
1977         }
1978
1979         if (created && !port->input) {
1980                 char proppath[255];
1981
1982                 build_mst_prop_path(mstb, port->port_num, proppath,
1983                                     sizeof(proppath));
1984                 port->connector = (*mstb->mgr->cbs->add_connector)(mstb->mgr,
1985                                                                    port,
1986                                                                    proppath);
1987                 if (!port->connector) {
1988                         /* remove it from the port list */
1989                         mutex_lock(&mstb->mgr->lock);
1990                         list_del(&port->next);
1991                         mutex_unlock(&mstb->mgr->lock);
1992                         /* drop port list reference */
1993                         drm_dp_mst_topology_put_port(port);
1994                         goto out;
1995                 }
1996                 if ((port->pdt == DP_PEER_DEVICE_DP_LEGACY_CONV ||
1997                      port->pdt == DP_PEER_DEVICE_SST_SINK) &&
1998                     port->port_num >= DP_MST_LOGICAL_PORT_0) {
1999                         port->cached_edid = drm_get_edid(port->connector,
2000                                                          &port->aux.ddc);
2001                         drm_connector_set_tile_property(port->connector);
2002                 }
2003                 (*mstb->mgr->cbs->register_connector)(port->connector);
2004         }
2005
2006 out:
2007         /* put reference to this port */
2008         drm_dp_mst_topology_put_port(port);
2009 }
2010
2011 static void
2012 drm_dp_mst_handle_conn_stat(struct drm_dp_mst_branch *mstb,
2013                             struct drm_dp_connection_status_notify *conn_stat)
2014 {
2015         struct drm_dp_mst_port *port;
2016         int old_pdt;
2017         int old_ddps;
2018         bool dowork = false;
2019         port = drm_dp_get_port(mstb, conn_stat->port_number);
2020         if (!port)
2021                 return;
2022
2023         old_ddps = port->ddps;
2024         old_pdt = port->pdt;
2025         port->pdt = conn_stat->peer_device_type;
2026         port->mcs = conn_stat->message_capability_status;
2027         port->ldps = conn_stat->legacy_device_plug_status;
2028         port->ddps = conn_stat->displayport_device_plug_status;
2029
2030         if (old_ddps != port->ddps) {
2031                 if (port->ddps) {
2032                         dowork = true;
2033                 } else {
2034                         port->available_pbn = 0;
2035                 }
2036         }
2037         if (old_pdt != port->pdt && !port->input) {
2038                 drm_dp_port_teardown_pdt(port, old_pdt);
2039
2040                 if (drm_dp_port_setup_pdt(port))
2041                         dowork = true;
2042         }
2043
2044         drm_dp_mst_topology_put_port(port);
2045         if (dowork)
2046                 queue_work(system_long_wq, &mstb->mgr->work);
2047
2048 }
2049
2050 static struct drm_dp_mst_branch *drm_dp_get_mst_branch_device(struct drm_dp_mst_topology_mgr *mgr,
2051                                                                u8 lct, u8 *rad)
2052 {
2053         struct drm_dp_mst_branch *mstb;
2054         struct drm_dp_mst_port *port;
2055         int i, ret;
2056         /* find the port by iterating down */
2057
2058         mutex_lock(&mgr->lock);
2059         mstb = mgr->mst_primary;
2060
2061         if (!mstb)
2062                 goto out;
2063
2064         for (i = 0; i < lct - 1; i++) {
2065                 int shift = (i % 2) ? 0 : 4;
2066                 int port_num = (rad[i / 2] >> shift) & 0xf;
2067
2068                 list_for_each_entry(port, &mstb->ports, next) {
2069                         if (port->port_num == port_num) {
2070                                 mstb = port->mstb;
2071                                 if (!mstb) {
2072                                         DRM_ERROR("failed to lookup MSTB with lct %d, rad %02x\n", lct, rad[0]);
2073                                         goto out;
2074                                 }
2075
2076                                 break;
2077                         }
2078                 }
2079         }
2080         ret = drm_dp_mst_topology_try_get_mstb(mstb);
2081         if (!ret)
2082                 mstb = NULL;
2083 out:
2084         mutex_unlock(&mgr->lock);
2085         return mstb;
2086 }
2087
2088 static struct drm_dp_mst_branch *get_mst_branch_device_by_guid_helper(
2089         struct drm_dp_mst_branch *mstb,
2090         const uint8_t *guid)
2091 {
2092         struct drm_dp_mst_branch *found_mstb;
2093         struct drm_dp_mst_port *port;
2094
2095         if (memcmp(mstb->guid, guid, 16) == 0)
2096                 return mstb;
2097
2098
2099         list_for_each_entry(port, &mstb->ports, next) {
2100                 if (!port->mstb)
2101                         continue;
2102
2103                 found_mstb = get_mst_branch_device_by_guid_helper(port->mstb, guid);
2104
2105                 if (found_mstb)
2106                         return found_mstb;
2107         }
2108
2109         return NULL;
2110 }
2111
2112 static struct drm_dp_mst_branch *
2113 drm_dp_get_mst_branch_device_by_guid(struct drm_dp_mst_topology_mgr *mgr,
2114                                      const uint8_t *guid)
2115 {
2116         struct drm_dp_mst_branch *mstb;
2117         int ret;
2118
2119         /* find the port by iterating down */
2120         mutex_lock(&mgr->lock);
2121
2122         mstb = get_mst_branch_device_by_guid_helper(mgr->mst_primary, guid);
2123         if (mstb) {
2124                 ret = drm_dp_mst_topology_try_get_mstb(mstb);
2125                 if (!ret)
2126                         mstb = NULL;
2127         }
2128
2129         mutex_unlock(&mgr->lock);
2130         return mstb;
2131 }
2132
2133 static void drm_dp_check_and_send_link_address(struct drm_dp_mst_topology_mgr *mgr,
2134                                                struct drm_dp_mst_branch *mstb)
2135 {
2136         struct drm_dp_mst_port *port;
2137         struct drm_dp_mst_branch *mstb_child;
2138         if (!mstb->link_address_sent)
2139                 drm_dp_send_link_address(mgr, mstb);
2140
2141         list_for_each_entry(port, &mstb->ports, next) {
2142                 if (port->input)
2143                         continue;
2144
2145                 if (!port->ddps)
2146                         continue;
2147
2148                 if (!port->available_pbn)
2149                         drm_dp_send_enum_path_resources(mgr, mstb, port);
2150
2151                 if (port->mstb) {
2152                         mstb_child = drm_dp_mst_topology_get_mstb_validated(
2153                             mgr, port->mstb);
2154                         if (mstb_child) {
2155                                 drm_dp_check_and_send_link_address(mgr, mstb_child);
2156                                 drm_dp_mst_topology_put_mstb(mstb_child);
2157                         }
2158                 }
2159         }
2160 }
2161
2162 static void drm_dp_mst_link_probe_work(struct work_struct *work)
2163 {
2164         struct drm_dp_mst_topology_mgr *mgr = container_of(work, struct drm_dp_mst_topology_mgr, work);
2165         struct drm_dp_mst_branch *mstb;
2166         int ret;
2167
2168         mutex_lock(&mgr->lock);
2169         mstb = mgr->mst_primary;
2170         if (mstb) {
2171                 ret = drm_dp_mst_topology_try_get_mstb(mstb);
2172                 if (!ret)
2173                         mstb = NULL;
2174         }
2175         mutex_unlock(&mgr->lock);
2176         if (mstb) {
2177                 drm_dp_check_and_send_link_address(mgr, mstb);
2178                 drm_dp_mst_topology_put_mstb(mstb);
2179         }
2180 }
2181
2182 static bool drm_dp_validate_guid(struct drm_dp_mst_topology_mgr *mgr,
2183                                  u8 *guid)
2184 {
2185         u64 salt;
2186
2187         if (memchr_inv(guid, 0, 16))
2188                 return true;
2189
2190         salt = get_jiffies_64();
2191
2192         memcpy(&guid[0], &salt, sizeof(u64));
2193         memcpy(&guid[8], &salt, sizeof(u64));
2194
2195         return false;
2196 }
2197
2198 static int build_dpcd_read(struct drm_dp_sideband_msg_tx *msg, u8 port_num, u32 offset, u8 num_bytes)
2199 {
2200         struct drm_dp_sideband_msg_req_body req;
2201
2202         req.req_type = DP_REMOTE_DPCD_READ;
2203         req.u.dpcd_read.port_number = port_num;
2204         req.u.dpcd_read.dpcd_address = offset;
2205         req.u.dpcd_read.num_bytes = num_bytes;
2206         drm_dp_encode_sideband_req(&req, msg);
2207
2208         return 0;
2209 }
2210
2211 static int drm_dp_send_sideband_msg(struct drm_dp_mst_topology_mgr *mgr,
2212                                     bool up, u8 *msg, int len)
2213 {
2214         int ret;
2215         int regbase = up ? DP_SIDEBAND_MSG_UP_REP_BASE : DP_SIDEBAND_MSG_DOWN_REQ_BASE;
2216         int tosend, total, offset;
2217         int retries = 0;
2218
2219 retry:
2220         total = len;
2221         offset = 0;
2222         do {
2223                 tosend = min3(mgr->max_dpcd_transaction_bytes, 16, total);
2224
2225                 ret = drm_dp_dpcd_write(mgr->aux, regbase + offset,
2226                                         &msg[offset],
2227                                         tosend);
2228                 if (ret != tosend) {
2229                         if (ret == -EIO && retries < 5) {
2230                                 retries++;
2231                                 goto retry;
2232                         }
2233                         DRM_DEBUG_KMS("failed to dpcd write %d %d\n", tosend, ret);
2234
2235                         return -EIO;
2236                 }
2237                 offset += tosend;
2238                 total -= tosend;
2239         } while (total > 0);
2240         return 0;
2241 }
2242
2243 static int set_hdr_from_dst_qlock(struct drm_dp_sideband_msg_hdr *hdr,
2244                                   struct drm_dp_sideband_msg_tx *txmsg)
2245 {
2246         struct drm_dp_mst_branch *mstb = txmsg->dst;
2247         u8 req_type;
2248
2249         /* both msg slots are full */
2250         if (txmsg->seqno == -1) {
2251                 if (mstb->tx_slots[0] && mstb->tx_slots[1]) {
2252                         DRM_DEBUG_KMS("%s: failed to find slot\n", __func__);
2253                         return -EAGAIN;
2254                 }
2255                 if (mstb->tx_slots[0] == NULL && mstb->tx_slots[1] == NULL) {
2256                         txmsg->seqno = mstb->last_seqno;
2257                         mstb->last_seqno ^= 1;
2258                 } else if (mstb->tx_slots[0] == NULL)
2259                         txmsg->seqno = 0;
2260                 else
2261                         txmsg->seqno = 1;
2262                 mstb->tx_slots[txmsg->seqno] = txmsg;
2263         }
2264
2265         req_type = txmsg->msg[0] & 0x7f;
2266         if (req_type == DP_CONNECTION_STATUS_NOTIFY ||
2267                 req_type == DP_RESOURCE_STATUS_NOTIFY)
2268                 hdr->broadcast = 1;
2269         else
2270                 hdr->broadcast = 0;
2271         hdr->path_msg = txmsg->path_msg;
2272         hdr->lct = mstb->lct;
2273         hdr->lcr = mstb->lct - 1;
2274         if (mstb->lct > 1)
2275                 memcpy(hdr->rad, mstb->rad, mstb->lct / 2);
2276         hdr->seqno = txmsg->seqno;
2277         return 0;
2278 }
2279 /*
2280  * process a single block of the next message in the sideband queue
2281  */
2282 static int process_single_tx_qlock(struct drm_dp_mst_topology_mgr *mgr,
2283                                    struct drm_dp_sideband_msg_tx *txmsg,
2284                                    bool up)
2285 {
2286         u8 chunk[48];
2287         struct drm_dp_sideband_msg_hdr hdr;
2288         int len, space, idx, tosend;
2289         int ret;
2290
2291         memset(&hdr, 0, sizeof(struct drm_dp_sideband_msg_hdr));
2292
2293         if (txmsg->state == DRM_DP_SIDEBAND_TX_QUEUED) {
2294                 txmsg->seqno = -1;
2295                 txmsg->state = DRM_DP_SIDEBAND_TX_START_SEND;
2296         }
2297
2298         /* make hdr from dst mst - for replies use seqno
2299            otherwise assign one */
2300         ret = set_hdr_from_dst_qlock(&hdr, txmsg);
2301         if (ret < 0)
2302                 return ret;
2303
2304         /* amount left to send in this message */
2305         len = txmsg->cur_len - txmsg->cur_offset;
2306
2307         /* 48 - sideband msg size - 1 byte for data CRC, x header bytes */
2308         space = 48 - 1 - drm_dp_calc_sb_hdr_size(&hdr);
2309
2310         tosend = min(len, space);
2311         if (len == txmsg->cur_len)
2312                 hdr.somt = 1;
2313         if (space >= len)
2314                 hdr.eomt = 1;
2315
2316
2317         hdr.msg_len = tosend + 1;
2318         drm_dp_encode_sideband_msg_hdr(&hdr, chunk, &idx);
2319         memcpy(&chunk[idx], &txmsg->msg[txmsg->cur_offset], tosend);
2320         /* add crc at end */
2321         drm_dp_crc_sideband_chunk_req(&chunk[idx], tosend);
2322         idx += tosend + 1;
2323
2324         ret = drm_dp_send_sideband_msg(mgr, up, chunk, idx);
2325         if (unlikely(ret) && drm_debug_enabled(DRM_UT_DP)) {
2326                 struct drm_printer p = drm_debug_printer(DBG_PREFIX);
2327
2328                 drm_printf(&p, "sideband msg failed to send\n");
2329                 drm_dp_mst_dump_sideband_msg_tx(&p, txmsg);
2330                 return ret;
2331         }
2332
2333         txmsg->cur_offset += tosend;
2334         if (txmsg->cur_offset == txmsg->cur_len) {
2335                 txmsg->state = DRM_DP_SIDEBAND_TX_SENT;
2336                 return 1;
2337         }
2338         return 0;
2339 }
2340
2341 static void process_single_down_tx_qlock(struct drm_dp_mst_topology_mgr *mgr)
2342 {
2343         struct drm_dp_sideband_msg_tx *txmsg;
2344         int ret;
2345
2346         WARN_ON(!mutex_is_locked(&mgr->qlock));
2347
2348         /* construct a chunk from the first msg in the tx_msg queue */
2349         if (list_empty(&mgr->tx_msg_downq))
2350                 return;
2351
2352         txmsg = list_first_entry(&mgr->tx_msg_downq, struct drm_dp_sideband_msg_tx, next);
2353         ret = process_single_tx_qlock(mgr, txmsg, false);
2354         if (ret == 1) {
2355                 /* txmsg is sent it should be in the slots now */
2356                 list_del(&txmsg->next);
2357         } else if (ret) {
2358                 DRM_DEBUG_KMS("failed to send msg in q %d\n", ret);
2359                 list_del(&txmsg->next);
2360                 if (txmsg->seqno != -1)
2361                         txmsg->dst->tx_slots[txmsg->seqno] = NULL;
2362                 txmsg->state = DRM_DP_SIDEBAND_TX_TIMEOUT;
2363                 wake_up_all(&mgr->tx_waitq);
2364         }
2365 }
2366
2367 /* called holding qlock */
2368 static void process_single_up_tx_qlock(struct drm_dp_mst_topology_mgr *mgr,
2369                                        struct drm_dp_sideband_msg_tx *txmsg)
2370 {
2371         int ret;
2372
2373         /* construct a chunk from the first msg in the tx_msg queue */
2374         ret = process_single_tx_qlock(mgr, txmsg, true);
2375
2376         if (ret != 1)
2377                 DRM_DEBUG_KMS("failed to send msg in q %d\n", ret);
2378
2379         if (txmsg->seqno != -1) {
2380                 WARN_ON((unsigned int)txmsg->seqno >
2381                         ARRAY_SIZE(txmsg->dst->tx_slots));
2382                 txmsg->dst->tx_slots[txmsg->seqno] = NULL;
2383         }
2384 }
2385
2386 static void drm_dp_queue_down_tx(struct drm_dp_mst_topology_mgr *mgr,
2387                                  struct drm_dp_sideband_msg_tx *txmsg)
2388 {
2389         mutex_lock(&mgr->qlock);
2390         list_add_tail(&txmsg->next, &mgr->tx_msg_downq);
2391
2392         if (drm_debug_enabled(DRM_UT_DP)) {
2393                 struct drm_printer p = drm_debug_printer(DBG_PREFIX);
2394
2395                 drm_dp_mst_dump_sideband_msg_tx(&p, txmsg);
2396         }
2397
2398         if (list_is_singular(&mgr->tx_msg_downq))
2399                 process_single_down_tx_qlock(mgr);
2400         mutex_unlock(&mgr->qlock);
2401 }
2402
2403 static void
2404 drm_dp_dump_link_address(struct drm_dp_link_address_ack_reply *reply)
2405 {
2406         struct drm_dp_link_addr_reply_port *port_reply;
2407         int i;
2408
2409         for (i = 0; i < reply->nports; i++) {
2410                 port_reply = &reply->ports[i];
2411                 DRM_DEBUG_KMS("port %d: input %d, pdt: %d, pn: %d, dpcd_rev: %02x, mcs: %d, ddps: %d, ldps %d, sdp %d/%d\n",
2412                               i,
2413                               port_reply->input_port,
2414                               port_reply->peer_device_type,
2415                               port_reply->port_number,
2416                               port_reply->dpcd_revision,
2417                               port_reply->mcs,
2418                               port_reply->ddps,
2419                               port_reply->legacy_device_plug_status,
2420                               port_reply->num_sdp_streams,
2421                               port_reply->num_sdp_stream_sinks);
2422         }
2423 }
2424
2425 static void drm_dp_send_link_address(struct drm_dp_mst_topology_mgr *mgr,
2426                                      struct drm_dp_mst_branch *mstb)
2427 {
2428         struct drm_dp_sideband_msg_tx *txmsg;
2429         struct drm_dp_link_address_ack_reply *reply;
2430         int i, len, ret;
2431
2432         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
2433         if (!txmsg)
2434                 return;
2435
2436         txmsg->dst = mstb;
2437         len = build_link_address(txmsg);
2438
2439         mstb->link_address_sent = true;
2440         drm_dp_queue_down_tx(mgr, txmsg);
2441
2442         /* FIXME: Actually do some real error handling here */
2443         ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
2444         if (ret <= 0) {
2445                 DRM_ERROR("Sending link address failed with %d\n", ret);
2446                 goto out;
2447         }
2448         if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK) {
2449                 DRM_ERROR("link address NAK received\n");
2450                 ret = -EIO;
2451                 goto out;
2452         }
2453
2454         reply = &txmsg->reply.u.link_addr;
2455         DRM_DEBUG_KMS("link address reply: %d\n", reply->nports);
2456         drm_dp_dump_link_address(reply);
2457
2458         drm_dp_check_mstb_guid(mstb, reply->guid);
2459
2460         for (i = 0; i < reply->nports; i++)
2461                 drm_dp_mst_handle_link_address_port(mstb, mgr->dev,
2462                                                     &reply->ports[i]);
2463
2464         drm_kms_helper_hotplug_event(mgr->dev);
2465
2466 out:
2467         if (ret <= 0)
2468                 mstb->link_address_sent = false;
2469         kfree(txmsg);
2470 }
2471
2472 static int
2473 drm_dp_send_enum_path_resources(struct drm_dp_mst_topology_mgr *mgr,
2474                                 struct drm_dp_mst_branch *mstb,
2475                                 struct drm_dp_mst_port *port)
2476 {
2477         struct drm_dp_enum_path_resources_ack_reply *path_res;
2478         struct drm_dp_sideband_msg_tx *txmsg;
2479         int len;
2480         int ret;
2481
2482         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
2483         if (!txmsg)
2484                 return -ENOMEM;
2485
2486         txmsg->dst = mstb;
2487         len = build_enum_path_resources(txmsg, port->port_num);
2488
2489         drm_dp_queue_down_tx(mgr, txmsg);
2490
2491         ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
2492         if (ret > 0) {
2493                 path_res = &txmsg->reply.u.path_resources;
2494
2495                 if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK) {
2496                         DRM_DEBUG_KMS("enum path resources nak received\n");
2497                 } else {
2498                         if (port->port_num != path_res->port_number)
2499                                 DRM_ERROR("got incorrect port in response\n");
2500
2501                         DRM_DEBUG_KMS("enum path resources %d: %d %d\n",
2502                                       path_res->port_number,
2503                                       path_res->full_payload_bw_number,
2504                                       path_res->avail_payload_bw_number);
2505                         port->available_pbn =
2506                                 path_res->avail_payload_bw_number;
2507                 }
2508         }
2509
2510         kfree(txmsg);
2511         return 0;
2512 }
2513
2514 static struct drm_dp_mst_port *drm_dp_get_last_connected_port_to_mstb(struct drm_dp_mst_branch *mstb)
2515 {
2516         if (!mstb->port_parent)
2517                 return NULL;
2518
2519         if (mstb->port_parent->mstb != mstb)
2520                 return mstb->port_parent;
2521
2522         return drm_dp_get_last_connected_port_to_mstb(mstb->port_parent->parent);
2523 }
2524
2525 /*
2526  * Searches upwards in the topology starting from mstb to try to find the
2527  * closest available parent of mstb that's still connected to the rest of the
2528  * topology. This can be used in order to perform operations like releasing
2529  * payloads, where the branch device which owned the payload may no longer be
2530  * around and thus would require that the payload on the last living relative
2531  * be freed instead.
2532  */
2533 static struct drm_dp_mst_branch *
2534 drm_dp_get_last_connected_port_and_mstb(struct drm_dp_mst_topology_mgr *mgr,
2535                                         struct drm_dp_mst_branch *mstb,
2536                                         int *port_num)
2537 {
2538         struct drm_dp_mst_branch *rmstb = NULL;
2539         struct drm_dp_mst_port *found_port;
2540
2541         mutex_lock(&mgr->lock);
2542         if (!mgr->mst_primary)
2543                 goto out;
2544
2545         do {
2546                 found_port = drm_dp_get_last_connected_port_to_mstb(mstb);
2547                 if (!found_port)
2548                         break;
2549
2550                 if (drm_dp_mst_topology_try_get_mstb(found_port->parent)) {
2551                         rmstb = found_port->parent;
2552                         *port_num = found_port->port_num;
2553                 } else {
2554                         /* Search again, starting from this parent */
2555                         mstb = found_port->parent;
2556                 }
2557         } while (!rmstb);
2558 out:
2559         mutex_unlock(&mgr->lock);
2560         return rmstb;
2561 }
2562
2563 static int drm_dp_payload_send_msg(struct drm_dp_mst_topology_mgr *mgr,
2564                                    struct drm_dp_mst_port *port,
2565                                    int id,
2566                                    int pbn)
2567 {
2568         struct drm_dp_sideband_msg_tx *txmsg;
2569         struct drm_dp_mst_branch *mstb;
2570         int len, ret, port_num;
2571         u8 sinks[DRM_DP_MAX_SDP_STREAMS];
2572         int i;
2573
2574         port_num = port->port_num;
2575         mstb = drm_dp_mst_topology_get_mstb_validated(mgr, port->parent);
2576         if (!mstb) {
2577                 mstb = drm_dp_get_last_connected_port_and_mstb(mgr,
2578                                                                port->parent,
2579                                                                &port_num);
2580
2581                 if (!mstb)
2582                         return -EINVAL;
2583         }
2584
2585         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
2586         if (!txmsg) {
2587                 ret = -ENOMEM;
2588                 goto fail_put;
2589         }
2590
2591         for (i = 0; i < port->num_sdp_streams; i++)
2592                 sinks[i] = i;
2593
2594         txmsg->dst = mstb;
2595         len = build_allocate_payload(txmsg, port_num,
2596                                      id,
2597                                      pbn, port->num_sdp_streams, sinks);
2598
2599         drm_dp_queue_down_tx(mgr, txmsg);
2600
2601         /*
2602          * FIXME: there is a small chance that between getting the last
2603          * connected mstb and sending the payload message, the last connected
2604          * mstb could also be removed from the topology. In the future, this
2605          * needs to be fixed by restarting the
2606          * drm_dp_get_last_connected_port_and_mstb() search in the event of a
2607          * timeout if the topology is still connected to the system.
2608          */
2609         ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
2610         if (ret > 0) {
2611                 if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK)
2612                         ret = -EINVAL;
2613                 else
2614                         ret = 0;
2615         }
2616         kfree(txmsg);
2617 fail_put:
2618         drm_dp_mst_topology_put_mstb(mstb);
2619         return ret;
2620 }
2621
2622 int drm_dp_send_power_updown_phy(struct drm_dp_mst_topology_mgr *mgr,
2623                                  struct drm_dp_mst_port *port, bool power_up)
2624 {
2625         struct drm_dp_sideband_msg_tx *txmsg;
2626         int len, ret;
2627
2628         port = drm_dp_mst_topology_get_port_validated(mgr, port);
2629         if (!port)
2630                 return -EINVAL;
2631
2632         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
2633         if (!txmsg) {
2634                 drm_dp_mst_topology_put_port(port);
2635                 return -ENOMEM;
2636         }
2637
2638         txmsg->dst = port->parent;
2639         len = build_power_updown_phy(txmsg, port->port_num, power_up);
2640         drm_dp_queue_down_tx(mgr, txmsg);
2641
2642         ret = drm_dp_mst_wait_tx_reply(port->parent, txmsg);
2643         if (ret > 0) {
2644                 if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK)
2645                         ret = -EINVAL;
2646                 else
2647                         ret = 0;
2648         }
2649         kfree(txmsg);
2650         drm_dp_mst_topology_put_port(port);
2651
2652         return ret;
2653 }
2654 EXPORT_SYMBOL(drm_dp_send_power_updown_phy);
2655
2656 static int drm_dp_create_payload_step1(struct drm_dp_mst_topology_mgr *mgr,
2657                                        int id,
2658                                        struct drm_dp_payload *payload)
2659 {
2660         int ret;
2661
2662         ret = drm_dp_dpcd_write_payload(mgr, id, payload);
2663         if (ret < 0) {
2664                 payload->payload_state = 0;
2665                 return ret;
2666         }
2667         payload->payload_state = DP_PAYLOAD_LOCAL;
2668         return 0;
2669 }
2670
2671 static int drm_dp_create_payload_step2(struct drm_dp_mst_topology_mgr *mgr,
2672                                        struct drm_dp_mst_port *port,
2673                                        int id,
2674                                        struct drm_dp_payload *payload)
2675 {
2676         int ret;
2677         ret = drm_dp_payload_send_msg(mgr, port, id, port->vcpi.pbn);
2678         if (ret < 0)
2679                 return ret;
2680         payload->payload_state = DP_PAYLOAD_REMOTE;
2681         return ret;
2682 }
2683
2684 static int drm_dp_destroy_payload_step1(struct drm_dp_mst_topology_mgr *mgr,
2685                                         struct drm_dp_mst_port *port,
2686                                         int id,
2687                                         struct drm_dp_payload *payload)
2688 {
2689         DRM_DEBUG_KMS("\n");
2690         /* it's okay for these to fail */
2691         if (port) {
2692                 drm_dp_payload_send_msg(mgr, port, id, 0);
2693         }
2694
2695         drm_dp_dpcd_write_payload(mgr, id, payload);
2696         payload->payload_state = DP_PAYLOAD_DELETE_LOCAL;
2697         return 0;
2698 }
2699
2700 static int drm_dp_destroy_payload_step2(struct drm_dp_mst_topology_mgr *mgr,
2701                                         int id,
2702                                         struct drm_dp_payload *payload)
2703 {
2704         payload->payload_state = 0;
2705         return 0;
2706 }
2707
2708 /**
2709  * drm_dp_update_payload_part1() - Execute payload update part 1
2710  * @mgr: manager to use.
2711  *
2712  * This iterates over all proposed virtual channels, and tries to
2713  * allocate space in the link for them. For 0->slots transitions,
2714  * this step just writes the VCPI to the MST device. For slots->0
2715  * transitions, this writes the updated VCPIs and removes the
2716  * remote VC payloads.
2717  *
2718  * after calling this the driver should generate ACT and payload
2719  * packets.
2720  */
2721 int drm_dp_update_payload_part1(struct drm_dp_mst_topology_mgr *mgr)
2722 {
2723         struct drm_dp_payload req_payload;
2724         struct drm_dp_mst_port *port;
2725         int i, j;
2726         int cur_slots = 1;
2727
2728         mutex_lock(&mgr->payload_lock);
2729         for (i = 0; i < mgr->max_payloads; i++) {
2730                 struct drm_dp_vcpi *vcpi = mgr->proposed_vcpis[i];
2731                 struct drm_dp_payload *payload = &mgr->payloads[i];
2732                 bool put_port = false;
2733
2734                 /* solve the current payloads - compare to the hw ones
2735                    - update the hw view */
2736                 req_payload.start_slot = cur_slots;
2737                 if (vcpi) {
2738                         port = container_of(vcpi, struct drm_dp_mst_port,
2739                                             vcpi);
2740
2741                         /* Validated ports don't matter if we're releasing
2742                          * VCPI
2743                          */
2744                         if (vcpi->num_slots) {
2745                                 port = drm_dp_mst_topology_get_port_validated(
2746                                     mgr, port);
2747                                 if (!port) {
2748                                         mutex_unlock(&mgr->payload_lock);
2749                                         return -EINVAL;
2750                                 }
2751                                 put_port = true;
2752                         }
2753
2754                         req_payload.num_slots = vcpi->num_slots;
2755                         req_payload.vcpi = vcpi->vcpi;
2756                 } else {
2757                         port = NULL;
2758                         req_payload.num_slots = 0;
2759                 }
2760
2761                 payload->start_slot = req_payload.start_slot;
2762                 /* work out what is required to happen with this payload */
2763                 if (payload->num_slots != req_payload.num_slots) {
2764
2765                         /* need to push an update for this payload */
2766                         if (req_payload.num_slots) {
2767                                 drm_dp_create_payload_step1(mgr, vcpi->vcpi,
2768                                                             &req_payload);
2769                                 payload->num_slots = req_payload.num_slots;
2770                                 payload->vcpi = req_payload.vcpi;
2771
2772                         } else if (payload->num_slots) {
2773                                 payload->num_slots = 0;
2774                                 drm_dp_destroy_payload_step1(mgr, port,
2775                                                              payload->vcpi,
2776                                                              payload);
2777                                 req_payload.payload_state =
2778                                         payload->payload_state;
2779                                 payload->start_slot = 0;
2780                         }
2781                         payload->payload_state = req_payload.payload_state;
2782                 }
2783                 cur_slots += req_payload.num_slots;
2784
2785                 if (put_port)
2786                         drm_dp_mst_topology_put_port(port);
2787         }
2788
2789         for (i = 0; i < mgr->max_payloads; i++) {
2790                 if (mgr->payloads[i].payload_state != DP_PAYLOAD_DELETE_LOCAL)
2791                         continue;
2792
2793                 DRM_DEBUG_KMS("removing payload %d\n", i);
2794                 for (j = i; j < mgr->max_payloads - 1; j++) {
2795                         mgr->payloads[j] = mgr->payloads[j + 1];
2796                         mgr->proposed_vcpis[j] = mgr->proposed_vcpis[j + 1];
2797
2798                         if (mgr->proposed_vcpis[j] &&
2799                             mgr->proposed_vcpis[j]->num_slots) {
2800                                 set_bit(j + 1, &mgr->payload_mask);
2801                         } else {
2802                                 clear_bit(j + 1, &mgr->payload_mask);
2803                         }
2804                 }
2805
2806                 memset(&mgr->payloads[mgr->max_payloads - 1], 0,
2807                        sizeof(struct drm_dp_payload));
2808                 mgr->proposed_vcpis[mgr->max_payloads - 1] = NULL;
2809                 clear_bit(mgr->max_payloads, &mgr->payload_mask);
2810         }
2811         mutex_unlock(&mgr->payload_lock);
2812
2813         return 0;
2814 }
2815 EXPORT_SYMBOL(drm_dp_update_payload_part1);
2816
2817 /**
2818  * drm_dp_update_payload_part2() - Execute payload update part 2
2819  * @mgr: manager to use.
2820  *
2821  * This iterates over all proposed virtual channels, and tries to
2822  * allocate space in the link for them. For 0->slots transitions,
2823  * this step writes the remote VC payload commands. For slots->0
2824  * this just resets some internal state.
2825  */
2826 int drm_dp_update_payload_part2(struct drm_dp_mst_topology_mgr *mgr)
2827 {
2828         struct drm_dp_mst_port *port;
2829         int i;
2830         int ret = 0;
2831         mutex_lock(&mgr->payload_lock);
2832         for (i = 0; i < mgr->max_payloads; i++) {
2833
2834                 if (!mgr->proposed_vcpis[i])
2835                         continue;
2836
2837                 port = container_of(mgr->proposed_vcpis[i], struct drm_dp_mst_port, vcpi);
2838
2839                 DRM_DEBUG_KMS("payload %d %d\n", i, mgr->payloads[i].payload_state);
2840                 if (mgr->payloads[i].payload_state == DP_PAYLOAD_LOCAL) {
2841                         ret = drm_dp_create_payload_step2(mgr, port, mgr->proposed_vcpis[i]->vcpi, &mgr->payloads[i]);
2842                 } else if (mgr->payloads[i].payload_state == DP_PAYLOAD_DELETE_LOCAL) {
2843                         ret = drm_dp_destroy_payload_step2(mgr, mgr->proposed_vcpis[i]->vcpi, &mgr->payloads[i]);
2844                 }
2845                 if (ret) {
2846                         mutex_unlock(&mgr->payload_lock);
2847                         return ret;
2848                 }
2849         }
2850         mutex_unlock(&mgr->payload_lock);
2851         return 0;
2852 }
2853 EXPORT_SYMBOL(drm_dp_update_payload_part2);
2854
2855 static int drm_dp_send_dpcd_read(struct drm_dp_mst_topology_mgr *mgr,
2856                                  struct drm_dp_mst_port *port,
2857                                  int offset, int size, u8 *bytes)
2858 {
2859         int len;
2860         int ret = 0;
2861         struct drm_dp_sideband_msg_tx *txmsg;
2862         struct drm_dp_mst_branch *mstb;
2863
2864         mstb = drm_dp_mst_topology_get_mstb_validated(mgr, port->parent);
2865         if (!mstb)
2866                 return -EINVAL;
2867
2868         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
2869         if (!txmsg) {
2870                 ret = -ENOMEM;
2871                 goto fail_put;
2872         }
2873
2874         len = build_dpcd_read(txmsg, port->port_num, offset, size);
2875         txmsg->dst = port->parent;
2876
2877         drm_dp_queue_down_tx(mgr, txmsg);
2878
2879         ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
2880         if (ret < 0)
2881                 goto fail_free;
2882
2883         /* DPCD read should never be NACKed */
2884         if (txmsg->reply.reply_type == 1) {
2885                 DRM_ERROR("mstb %p port %d: DPCD read on addr 0x%x for %d bytes NAKed\n",
2886                           mstb, port->port_num, offset, size);
2887                 ret = -EIO;
2888                 goto fail_free;
2889         }
2890
2891         if (txmsg->reply.u.remote_dpcd_read_ack.num_bytes != size) {
2892                 ret = -EPROTO;
2893                 goto fail_free;
2894         }
2895
2896         ret = min_t(size_t, txmsg->reply.u.remote_dpcd_read_ack.num_bytes,
2897                     size);
2898         memcpy(bytes, txmsg->reply.u.remote_dpcd_read_ack.bytes, ret);
2899
2900 fail_free:
2901         kfree(txmsg);
2902 fail_put:
2903         drm_dp_mst_topology_put_mstb(mstb);
2904
2905         return ret;
2906 }
2907
2908 static int drm_dp_send_dpcd_write(struct drm_dp_mst_topology_mgr *mgr,
2909                                   struct drm_dp_mst_port *port,
2910                                   int offset, int size, u8 *bytes)
2911 {
2912         int len;
2913         int ret;
2914         struct drm_dp_sideband_msg_tx *txmsg;
2915         struct drm_dp_mst_branch *mstb;
2916
2917         mstb = drm_dp_mst_topology_get_mstb_validated(mgr, port->parent);
2918         if (!mstb)
2919                 return -EINVAL;
2920
2921         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
2922         if (!txmsg) {
2923                 ret = -ENOMEM;
2924                 goto fail_put;
2925         }
2926
2927         len = build_dpcd_write(txmsg, port->port_num, offset, size, bytes);
2928         txmsg->dst = mstb;
2929
2930         drm_dp_queue_down_tx(mgr, txmsg);
2931
2932         ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
2933         if (ret > 0) {
2934                 if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK)
2935                         ret = -EIO;
2936                 else
2937                         ret = 0;
2938         }
2939         kfree(txmsg);
2940 fail_put:
2941         drm_dp_mst_topology_put_mstb(mstb);
2942         return ret;
2943 }
2944
2945 static int drm_dp_encode_up_ack_reply(struct drm_dp_sideband_msg_tx *msg, u8 req_type)
2946 {
2947         struct drm_dp_sideband_msg_reply_body reply;
2948
2949         reply.reply_type = DP_SIDEBAND_REPLY_ACK;
2950         reply.req_type = req_type;
2951         drm_dp_encode_sideband_reply(&reply, msg);
2952         return 0;
2953 }
2954
2955 static int drm_dp_send_up_ack_reply(struct drm_dp_mst_topology_mgr *mgr,
2956                                     struct drm_dp_mst_branch *mstb,
2957                                     int req_type, int seqno, bool broadcast)
2958 {
2959         struct drm_dp_sideband_msg_tx *txmsg;
2960
2961         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
2962         if (!txmsg)
2963                 return -ENOMEM;
2964
2965         txmsg->dst = mstb;
2966         txmsg->seqno = seqno;
2967         drm_dp_encode_up_ack_reply(txmsg, req_type);
2968
2969         mutex_lock(&mgr->qlock);
2970
2971         process_single_up_tx_qlock(mgr, txmsg);
2972
2973         mutex_unlock(&mgr->qlock);
2974
2975         kfree(txmsg);
2976         return 0;
2977 }
2978
2979 static int drm_dp_get_vc_payload_bw(u8 dp_link_bw, u8  dp_link_count)
2980 {
2981         if (dp_link_bw == 0 || dp_link_count == 0)
2982                 DRM_DEBUG_KMS("invalid link bandwidth in DPCD: %x (link count: %d)\n",
2983                               dp_link_bw, dp_link_count);
2984
2985         return dp_link_bw * dp_link_count / 2;
2986 }
2987
2988 /**
2989  * drm_dp_mst_topology_mgr_set_mst() - Set the MST state for a topology manager
2990  * @mgr: manager to set state for
2991  * @mst_state: true to enable MST on this connector - false to disable.
2992  *
2993  * This is called by the driver when it detects an MST capable device plugged
2994  * into a DP MST capable port, or when a DP MST capable device is unplugged.
2995  */
2996 int drm_dp_mst_topology_mgr_set_mst(struct drm_dp_mst_topology_mgr *mgr, bool mst_state)
2997 {
2998         int ret = 0;
2999         struct drm_dp_mst_branch *mstb = NULL;
3000
3001         mutex_lock(&mgr->lock);
3002         if (mst_state == mgr->mst_state)
3003                 goto out_unlock;
3004
3005         mgr->mst_state = mst_state;
3006         /* set the device into MST mode */
3007         if (mst_state) {
3008                 WARN_ON(mgr->mst_primary);
3009
3010                 /* get dpcd info */
3011                 ret = drm_dp_dpcd_read(mgr->aux, DP_DPCD_REV, mgr->dpcd, DP_RECEIVER_CAP_SIZE);
3012                 if (ret != DP_RECEIVER_CAP_SIZE) {
3013                         DRM_DEBUG_KMS("failed to read DPCD\n");
3014                         goto out_unlock;
3015                 }
3016
3017                 mgr->pbn_div = drm_dp_get_vc_payload_bw(mgr->dpcd[1],
3018                                                         mgr->dpcd[2] & DP_MAX_LANE_COUNT_MASK);
3019                 if (mgr->pbn_div == 0) {
3020                         ret = -EINVAL;
3021                         goto out_unlock;
3022                 }
3023
3024                 /* add initial branch device at LCT 1 */
3025                 mstb = drm_dp_add_mst_branch_device(1, NULL);
3026                 if (mstb == NULL) {
3027                         ret = -ENOMEM;
3028                         goto out_unlock;
3029                 }
3030                 mstb->mgr = mgr;
3031
3032                 /* give this the main reference */
3033                 mgr->mst_primary = mstb;
3034                 drm_dp_mst_topology_get_mstb(mgr->mst_primary);
3035
3036                 ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3037                                                          DP_MST_EN | DP_UP_REQ_EN | DP_UPSTREAM_IS_SRC);
3038                 if (ret < 0) {
3039                         goto out_unlock;
3040                 }
3041
3042                 {
3043                         struct drm_dp_payload reset_pay;
3044                         reset_pay.start_slot = 0;
3045                         reset_pay.num_slots = 0x3f;
3046                         drm_dp_dpcd_write_payload(mgr, 0, &reset_pay);
3047                 }
3048
3049                 queue_work(system_long_wq, &mgr->work);
3050
3051                 ret = 0;
3052         } else {
3053                 /* disable MST on the device */
3054                 mstb = mgr->mst_primary;
3055                 mgr->mst_primary = NULL;
3056                 /* this can fail if the device is gone */
3057                 drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL, 0);
3058                 ret = 0;
3059                 memset(mgr->payloads, 0, mgr->max_payloads * sizeof(struct drm_dp_payload));
3060                 mgr->payload_mask = 0;
3061                 set_bit(0, &mgr->payload_mask);
3062                 mgr->vcpi_mask = 0;
3063         }
3064
3065 out_unlock:
3066         mutex_unlock(&mgr->lock);
3067         if (mstb)
3068                 drm_dp_mst_topology_put_mstb(mstb);
3069         return ret;
3070
3071 }
3072 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_set_mst);
3073
3074 /**
3075  * drm_dp_mst_topology_mgr_suspend() - suspend the MST manager
3076  * @mgr: manager to suspend
3077  *
3078  * This function tells the MST device that we can't handle UP messages
3079  * anymore. This should stop it from sending any since we are suspended.
3080  */
3081 void drm_dp_mst_topology_mgr_suspend(struct drm_dp_mst_topology_mgr *mgr)
3082 {
3083         mutex_lock(&mgr->lock);
3084         drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3085                            DP_MST_EN | DP_UPSTREAM_IS_SRC);
3086         mutex_unlock(&mgr->lock);
3087         flush_work(&mgr->work);
3088         flush_work(&mgr->destroy_connector_work);
3089 }
3090 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_suspend);
3091
3092 /**
3093  * drm_dp_mst_topology_mgr_resume() - resume the MST manager
3094  * @mgr: manager to resume
3095  *
3096  * This will fetch DPCD and see if the device is still there,
3097  * if it is, it will rewrite the MSTM control bits, and return.
3098  *
3099  * if the device fails this returns -1, and the driver should do
3100  * a full MST reprobe, in case we were undocked.
3101  */
3102 int drm_dp_mst_topology_mgr_resume(struct drm_dp_mst_topology_mgr *mgr)
3103 {
3104         int ret = 0;
3105
3106         mutex_lock(&mgr->lock);
3107
3108         if (mgr->mst_primary) {
3109                 int sret;
3110                 u8 guid[16];
3111
3112                 sret = drm_dp_dpcd_read(mgr->aux, DP_DPCD_REV, mgr->dpcd, DP_RECEIVER_CAP_SIZE);
3113                 if (sret != DP_RECEIVER_CAP_SIZE) {
3114                         DRM_DEBUG_KMS("dpcd read failed - undocked during suspend?\n");
3115                         ret = -1;
3116                         goto out_unlock;
3117                 }
3118
3119                 ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
3120                                          DP_MST_EN | DP_UP_REQ_EN | DP_UPSTREAM_IS_SRC);
3121                 if (ret < 0) {
3122                         DRM_DEBUG_KMS("mst write failed - undocked during suspend?\n");
3123                         ret = -1;
3124                         goto out_unlock;
3125                 }
3126
3127                 /* Some hubs forget their guids after they resume */
3128                 sret = drm_dp_dpcd_read(mgr->aux, DP_GUID, guid, 16);
3129                 if (sret != 16) {
3130                         DRM_DEBUG_KMS("dpcd read failed - undocked during suspend?\n");
3131                         ret = -1;
3132                         goto out_unlock;
3133                 }
3134                 drm_dp_check_mstb_guid(mgr->mst_primary, guid);
3135
3136                 ret = 0;
3137         } else
3138                 ret = -1;
3139
3140 out_unlock:
3141         mutex_unlock(&mgr->lock);
3142         return ret;
3143 }
3144 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_resume);
3145
3146 static bool drm_dp_get_one_sb_msg(struct drm_dp_mst_topology_mgr *mgr, bool up)
3147 {
3148         int len;
3149         u8 replyblock[32];
3150         int replylen, origlen, curreply;
3151         int ret;
3152         struct drm_dp_sideband_msg_rx *msg;
3153         int basereg = up ? DP_SIDEBAND_MSG_UP_REQ_BASE : DP_SIDEBAND_MSG_DOWN_REP_BASE;
3154         msg = up ? &mgr->up_req_recv : &mgr->down_rep_recv;
3155
3156         len = min(mgr->max_dpcd_transaction_bytes, 16);
3157         ret = drm_dp_dpcd_read(mgr->aux, basereg,
3158                                replyblock, len);
3159         if (ret != len) {
3160                 DRM_DEBUG_KMS("failed to read DPCD down rep %d %d\n", len, ret);
3161                 return false;
3162         }
3163         ret = drm_dp_sideband_msg_build(msg, replyblock, len, true);
3164         if (!ret) {
3165                 DRM_DEBUG_KMS("sideband msg build failed %d\n", replyblock[0]);
3166                 return false;
3167         }
3168         replylen = msg->curchunk_len + msg->curchunk_hdrlen;
3169
3170         origlen = replylen;
3171         replylen -= len;
3172         curreply = len;
3173         while (replylen > 0) {
3174                 len = min3(replylen, mgr->max_dpcd_transaction_bytes, 16);
3175                 ret = drm_dp_dpcd_read(mgr->aux, basereg + curreply,
3176                                     replyblock, len);
3177                 if (ret != len) {
3178                         DRM_DEBUG_KMS("failed to read a chunk (len %d, ret %d)\n",
3179                                       len, ret);
3180                         return false;
3181                 }
3182
3183                 ret = drm_dp_sideband_msg_build(msg, replyblock, len, false);
3184                 if (!ret) {
3185                         DRM_DEBUG_KMS("failed to build sideband msg\n");
3186                         return false;
3187                 }
3188
3189                 curreply += len;
3190                 replylen -= len;
3191         }
3192         return true;
3193 }
3194
3195 static int drm_dp_mst_handle_down_rep(struct drm_dp_mst_topology_mgr *mgr)
3196 {
3197         struct drm_dp_sideband_msg_tx *txmsg;
3198         struct drm_dp_mst_branch *mstb;
3199         struct drm_dp_sideband_msg_hdr *hdr = &mgr->down_rep_recv.initial_hdr;
3200         int slot = -1;
3201
3202         if (!drm_dp_get_one_sb_msg(mgr, false))
3203                 goto clear_down_rep_recv;
3204
3205         if (!mgr->down_rep_recv.have_eomt)
3206                 return 0;
3207
3208         mstb = drm_dp_get_mst_branch_device(mgr, hdr->lct, hdr->rad);
3209         if (!mstb) {
3210                 DRM_DEBUG_KMS("Got MST reply from unknown device %d\n",
3211                               hdr->lct);
3212                 goto clear_down_rep_recv;
3213         }
3214
3215         /* find the message */
3216         slot = hdr->seqno;
3217         mutex_lock(&mgr->qlock);
3218         txmsg = mstb->tx_slots[slot];
3219         /* remove from slots */
3220         mutex_unlock(&mgr->qlock);
3221
3222         if (!txmsg) {
3223                 DRM_DEBUG_KMS("Got MST reply with no msg %p %d %d %02x %02x\n",
3224                               mstb, hdr->seqno, hdr->lct, hdr->rad[0],
3225                               mgr->down_rep_recv.msg[0]);
3226                 goto no_msg;
3227         }
3228
3229         drm_dp_sideband_parse_reply(&mgr->down_rep_recv, &txmsg->reply);
3230
3231         if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK)
3232                 DRM_DEBUG_KMS("Got NAK reply: req 0x%02x (%s), reason 0x%02x (%s), nak data 0x%02x\n",
3233                               txmsg->reply.req_type,
3234                               drm_dp_mst_req_type_str(txmsg->reply.req_type),
3235                               txmsg->reply.u.nak.reason,
3236                               drm_dp_mst_nak_reason_str(txmsg->reply.u.nak.reason),
3237                               txmsg->reply.u.nak.nak_data);
3238
3239         memset(&mgr->down_rep_recv, 0, sizeof(struct drm_dp_sideband_msg_rx));
3240         drm_dp_mst_topology_put_mstb(mstb);
3241
3242         mutex_lock(&mgr->qlock);
3243         txmsg->state = DRM_DP_SIDEBAND_TX_RX;
3244         mstb->tx_slots[slot] = NULL;
3245         mutex_unlock(&mgr->qlock);
3246
3247         wake_up_all(&mgr->tx_waitq);
3248
3249         return 0;
3250
3251 no_msg:
3252         drm_dp_mst_topology_put_mstb(mstb);
3253 clear_down_rep_recv:
3254         memset(&mgr->down_rep_recv, 0, sizeof(struct drm_dp_sideband_msg_rx));
3255
3256         return 0;
3257 }
3258
3259 static int drm_dp_mst_handle_up_req(struct drm_dp_mst_topology_mgr *mgr)
3260 {
3261         struct drm_dp_sideband_msg_req_body msg;
3262         struct drm_dp_sideband_msg_hdr *hdr = &mgr->up_req_recv.initial_hdr;
3263         struct drm_dp_mst_branch *mstb = NULL;
3264         const u8 *guid;
3265         bool seqno;
3266
3267         if (!drm_dp_get_one_sb_msg(mgr, true))
3268                 goto out;
3269
3270         if (!mgr->up_req_recv.have_eomt)
3271                 return 0;
3272
3273         if (!hdr->broadcast) {
3274                 mstb = drm_dp_get_mst_branch_device(mgr, hdr->lct, hdr->rad);
3275                 if (!mstb) {
3276                         DRM_DEBUG_KMS("Got MST reply from unknown device %d\n",
3277                                       hdr->lct);
3278                         goto out;
3279                 }
3280         }
3281
3282         seqno = hdr->seqno;
3283         drm_dp_sideband_parse_req(&mgr->up_req_recv, &msg);
3284
3285         if (msg.req_type == DP_CONNECTION_STATUS_NOTIFY)
3286                 guid = msg.u.conn_stat.guid;
3287         else if (msg.req_type == DP_RESOURCE_STATUS_NOTIFY)
3288                 guid = msg.u.resource_stat.guid;
3289         else
3290                 goto out;
3291
3292         drm_dp_send_up_ack_reply(mgr, mgr->mst_primary, msg.req_type, seqno,
3293                                  false);
3294
3295         if (!mstb) {
3296                 mstb = drm_dp_get_mst_branch_device_by_guid(mgr, guid);
3297                 if (!mstb) {
3298                         DRM_DEBUG_KMS("Got MST reply from unknown device %d\n",
3299                                       hdr->lct);
3300                         goto out;
3301                 }
3302         }
3303
3304         if (msg.req_type == DP_CONNECTION_STATUS_NOTIFY) {
3305                 drm_dp_mst_handle_conn_stat(mstb, &msg.u.conn_stat);
3306
3307                 DRM_DEBUG_KMS("Got CSN: pn: %d ldps:%d ddps: %d mcs: %d ip: %d pdt: %d\n",
3308                               msg.u.conn_stat.port_number,
3309                               msg.u.conn_stat.legacy_device_plug_status,
3310                               msg.u.conn_stat.displayport_device_plug_status,
3311                               msg.u.conn_stat.message_capability_status,
3312                               msg.u.conn_stat.input_port,
3313                               msg.u.conn_stat.peer_device_type);
3314
3315                 drm_kms_helper_hotplug_event(mgr->dev);
3316         } else if (msg.req_type == DP_RESOURCE_STATUS_NOTIFY) {
3317                 DRM_DEBUG_KMS("Got RSN: pn: %d avail_pbn %d\n",
3318                               msg.u.resource_stat.port_number,
3319                               msg.u.resource_stat.available_pbn);
3320         }
3321
3322         drm_dp_mst_topology_put_mstb(mstb);
3323 out:
3324         memset(&mgr->up_req_recv, 0, sizeof(struct drm_dp_sideband_msg_rx));
3325         return 0;
3326 }
3327
3328 /**
3329  * drm_dp_mst_hpd_irq() - MST hotplug IRQ notify
3330  * @mgr: manager to notify irq for.
3331  * @esi: 4 bytes from SINK_COUNT_ESI
3332  * @handled: whether the hpd interrupt was consumed or not
3333  *
3334  * This should be called from the driver when it detects a short IRQ,
3335  * along with the value of the DEVICE_SERVICE_IRQ_VECTOR_ESI0. The
3336  * topology manager will process the sideband messages received as a result
3337  * of this.
3338  */
3339 int drm_dp_mst_hpd_irq(struct drm_dp_mst_topology_mgr *mgr, u8 *esi, bool *handled)
3340 {
3341         int ret = 0;
3342         int sc;
3343         *handled = false;
3344         sc = esi[0] & 0x3f;
3345
3346         if (sc != mgr->sink_count) {
3347                 mgr->sink_count = sc;
3348                 *handled = true;
3349         }
3350
3351         if (esi[1] & DP_DOWN_REP_MSG_RDY) {
3352                 ret = drm_dp_mst_handle_down_rep(mgr);
3353                 *handled = true;
3354         }
3355
3356         if (esi[1] & DP_UP_REQ_MSG_RDY) {
3357                 ret |= drm_dp_mst_handle_up_req(mgr);
3358                 *handled = true;
3359         }
3360
3361         drm_dp_mst_kick_tx(mgr);
3362         return ret;
3363 }
3364 EXPORT_SYMBOL(drm_dp_mst_hpd_irq);
3365
3366 /**
3367  * drm_dp_mst_detect_port() - get connection status for an MST port
3368  * @connector: DRM connector for this port
3369  * @mgr: manager for this port
3370  * @port: unverified pointer to a port
3371  *
3372  * This returns the current connection state for a port. It validates the
3373  * port pointer still exists so the caller doesn't require a reference
3374  */
3375 enum drm_connector_status drm_dp_mst_detect_port(struct drm_connector *connector,
3376                                                  struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
3377 {
3378         enum drm_connector_status status = connector_status_disconnected;
3379
3380         /* we need to search for the port in the mgr in case it's gone */
3381         port = drm_dp_mst_topology_get_port_validated(mgr, port);
3382         if (!port)
3383                 return connector_status_disconnected;
3384
3385         if (!port->ddps)
3386                 goto out;
3387
3388         switch (port->pdt) {
3389         case DP_PEER_DEVICE_NONE:
3390         case DP_PEER_DEVICE_MST_BRANCHING:
3391                 break;
3392
3393         case DP_PEER_DEVICE_SST_SINK:
3394                 status = connector_status_connected;
3395                 /* for logical ports - cache the EDID */
3396                 if (port->port_num >= 8 && !port->cached_edid) {
3397                         port->cached_edid = drm_get_edid(connector, &port->aux.ddc);
3398                 }
3399                 break;
3400         case DP_PEER_DEVICE_DP_LEGACY_CONV:
3401                 if (port->ldps)
3402                         status = connector_status_connected;
3403                 break;
3404         }
3405 out:
3406         drm_dp_mst_topology_put_port(port);
3407         return status;
3408 }
3409 EXPORT_SYMBOL(drm_dp_mst_detect_port);
3410
3411 /**
3412  * drm_dp_mst_port_has_audio() - Check whether port has audio capability or not
3413  * @mgr: manager for this port
3414  * @port: unverified pointer to a port.
3415  *
3416  * This returns whether the port supports audio or not.
3417  */
3418 bool drm_dp_mst_port_has_audio(struct drm_dp_mst_topology_mgr *mgr,
3419                                         struct drm_dp_mst_port *port)
3420 {
3421         bool ret = false;
3422
3423         port = drm_dp_mst_topology_get_port_validated(mgr, port);
3424         if (!port)
3425                 return ret;
3426         ret = port->has_audio;
3427         drm_dp_mst_topology_put_port(port);
3428         return ret;
3429 }
3430 EXPORT_SYMBOL(drm_dp_mst_port_has_audio);
3431
3432 /**
3433  * drm_dp_mst_get_edid() - get EDID for an MST port
3434  * @connector: toplevel connector to get EDID for
3435  * @mgr: manager for this port
3436  * @port: unverified pointer to a port.
3437  *
3438  * This returns an EDID for the port connected to a connector,
3439  * It validates the pointer still exists so the caller doesn't require a
3440  * reference.
3441  */
3442 struct edid *drm_dp_mst_get_edid(struct drm_connector *connector, struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
3443 {
3444         struct edid *edid = NULL;
3445
3446         /* we need to search for the port in the mgr in case it's gone */
3447         port = drm_dp_mst_topology_get_port_validated(mgr, port);
3448         if (!port)
3449                 return NULL;
3450
3451         if (port->cached_edid)
3452                 edid = drm_edid_duplicate(port->cached_edid);
3453         else {
3454                 edid = drm_get_edid(connector, &port->aux.ddc);
3455         }
3456         port->has_audio = drm_detect_monitor_audio(edid);
3457         drm_dp_mst_topology_put_port(port);
3458         return edid;
3459 }
3460 EXPORT_SYMBOL(drm_dp_mst_get_edid);
3461
3462 /**
3463  * drm_dp_find_vcpi_slots() - Find VCPI slots for this PBN value
3464  * @mgr: manager to use
3465  * @pbn: payload bandwidth to convert into slots.
3466  *
3467  * Calculate the number of VCPI slots that will be required for the given PBN
3468  * value. This function is deprecated, and should not be used in atomic
3469  * drivers.
3470  *
3471  * RETURNS:
3472  * The total slots required for this port, or error.
3473  */
3474 int drm_dp_find_vcpi_slots(struct drm_dp_mst_topology_mgr *mgr,
3475                            int pbn)
3476 {
3477         int num_slots;
3478
3479         num_slots = DIV_ROUND_UP(pbn, mgr->pbn_div);
3480
3481         /* max. time slots - one slot for MTP header */
3482         if (num_slots > 63)
3483                 return -ENOSPC;
3484         return num_slots;
3485 }
3486 EXPORT_SYMBOL(drm_dp_find_vcpi_slots);
3487
3488 static int drm_dp_init_vcpi(struct drm_dp_mst_topology_mgr *mgr,
3489                             struct drm_dp_vcpi *vcpi, int pbn, int slots)
3490 {
3491         int ret;
3492
3493         /* max. time slots - one slot for MTP header */
3494         if (slots > 63)
3495                 return -ENOSPC;
3496
3497         vcpi->pbn = pbn;
3498         vcpi->aligned_pbn = slots * mgr->pbn_div;
3499         vcpi->num_slots = slots;
3500
3501         ret = drm_dp_mst_assign_payload_id(mgr, vcpi);
3502         if (ret < 0)
3503                 return ret;
3504         return 0;
3505 }
3506
3507 /**
3508  * drm_dp_atomic_find_vcpi_slots() - Find and add VCPI slots to the state
3509  * @state: global atomic state
3510  * @mgr: MST topology manager for the port
3511  * @port: port to find vcpi slots for
3512  * @pbn: bandwidth required for the mode in PBN
3513  *
3514  * Allocates VCPI slots to @port, replacing any previous VCPI allocations it
3515  * may have had. Any atomic drivers which support MST must call this function
3516  * in their &drm_encoder_helper_funcs.atomic_check() callback to change the
3517  * current VCPI allocation for the new state, but only when
3518  * &drm_crtc_state.mode_changed or &drm_crtc_state.connectors_changed is set
3519  * to ensure compatibility with userspace applications that still use the
3520  * legacy modesetting UAPI.
3521  *
3522  * Allocations set by this function are not checked against the bandwidth
3523  * restraints of @mgr until the driver calls drm_dp_mst_atomic_check().
3524  *
3525  * Additionally, it is OK to call this function multiple times on the same
3526  * @port as needed. It is not OK however, to call this function and
3527  * drm_dp_atomic_release_vcpi_slots() in the same atomic check phase.
3528  *
3529  * See also:
3530  * drm_dp_atomic_release_vcpi_slots()
3531  * drm_dp_mst_atomic_check()
3532  *
3533  * Returns:
3534  * Total slots in the atomic state assigned for this port, or a negative error
3535  * code if the port no longer exists
3536  */
3537 int drm_dp_atomic_find_vcpi_slots(struct drm_atomic_state *state,
3538                                   struct drm_dp_mst_topology_mgr *mgr,
3539                                   struct drm_dp_mst_port *port, int pbn)
3540 {
3541         struct drm_dp_mst_topology_state *topology_state;
3542         struct drm_dp_vcpi_allocation *pos, *vcpi = NULL;
3543         int prev_slots, req_slots, ret;
3544
3545         topology_state = drm_atomic_get_mst_topology_state(state, mgr);
3546         if (IS_ERR(topology_state))
3547                 return PTR_ERR(topology_state);
3548
3549         /* Find the current allocation for this port, if any */
3550         list_for_each_entry(pos, &topology_state->vcpis, next) {
3551                 if (pos->port == port) {
3552                         vcpi = pos;
3553                         prev_slots = vcpi->vcpi;
3554
3555                         /*
3556                          * This should never happen, unless the driver tries
3557                          * releasing and allocating the same VCPI allocation,
3558                          * which is an error
3559                          */
3560                         if (WARN_ON(!prev_slots)) {
3561                                 DRM_ERROR("cannot allocate and release VCPI on [MST PORT:%p] in the same state\n",
3562                                           port);
3563                                 return -EINVAL;
3564                         }
3565
3566                         break;
3567                 }
3568         }
3569         if (!vcpi)
3570                 prev_slots = 0;
3571
3572         req_slots = DIV_ROUND_UP(pbn, mgr->pbn_div);
3573
3574         DRM_DEBUG_ATOMIC("[CONNECTOR:%d:%s] [MST PORT:%p] VCPI %d -> %d\n",
3575                          port->connector->base.id, port->connector->name,
3576                          port, prev_slots, req_slots);
3577
3578         /* Add the new allocation to the state */
3579         if (!vcpi) {
3580                 vcpi = kzalloc(sizeof(*vcpi), GFP_KERNEL);
3581                 if (!vcpi)
3582                         return -ENOMEM;
3583
3584                 drm_dp_mst_get_port_malloc(port);
3585                 vcpi->port = port;
3586                 list_add(&vcpi->next, &topology_state->vcpis);
3587         }
3588         vcpi->vcpi = req_slots;
3589
3590         ret = req_slots;
3591         return ret;
3592 }
3593 EXPORT_SYMBOL(drm_dp_atomic_find_vcpi_slots);
3594
3595 /**
3596  * drm_dp_atomic_release_vcpi_slots() - Release allocated vcpi slots
3597  * @state: global atomic state
3598  * @mgr: MST topology manager for the port
3599  * @port: The port to release the VCPI slots from
3600  *
3601  * Releases any VCPI slots that have been allocated to a port in the atomic
3602  * state. Any atomic drivers which support MST must call this function in
3603  * their &drm_connector_helper_funcs.atomic_check() callback when the
3604  * connector will no longer have VCPI allocated (e.g. because its CRTC was
3605  * removed) when it had VCPI allocated in the previous atomic state.
3606  *
3607  * It is OK to call this even if @port has been removed from the system.
3608  * Additionally, it is OK to call this function multiple times on the same
3609  * @port as needed. It is not OK however, to call this function and
3610  * drm_dp_atomic_find_vcpi_slots() on the same @port in a single atomic check
3611  * phase.
3612  *
3613  * See also:
3614  * drm_dp_atomic_find_vcpi_slots()
3615  * drm_dp_mst_atomic_check()
3616  *
3617  * Returns:
3618  * 0 if all slots for this port were added back to
3619  * &drm_dp_mst_topology_state.avail_slots or negative error code
3620  */
3621 int drm_dp_atomic_release_vcpi_slots(struct drm_atomic_state *state,
3622                                      struct drm_dp_mst_topology_mgr *mgr,
3623                                      struct drm_dp_mst_port *port)
3624 {
3625         struct drm_dp_mst_topology_state *topology_state;
3626         struct drm_dp_vcpi_allocation *pos;
3627         bool found = false;
3628
3629         topology_state = drm_atomic_get_mst_topology_state(state, mgr);
3630         if (IS_ERR(topology_state))
3631                 return PTR_ERR(topology_state);
3632
3633         list_for_each_entry(pos, &topology_state->vcpis, next) {
3634                 if (pos->port == port) {
3635                         found = true;
3636                         break;
3637                 }
3638         }
3639         if (WARN_ON(!found)) {
3640                 DRM_ERROR("no VCPI for [MST PORT:%p] found in mst state %p\n",
3641                           port, &topology_state->base);
3642                 return -EINVAL;
3643         }
3644
3645         DRM_DEBUG_ATOMIC("[MST PORT:%p] VCPI %d -> 0\n", port, pos->vcpi);
3646         if (pos->vcpi) {
3647                 drm_dp_mst_put_port_malloc(port);
3648                 pos->vcpi = 0;
3649         }
3650
3651         return 0;
3652 }
3653 EXPORT_SYMBOL(drm_dp_atomic_release_vcpi_slots);
3654
3655 /**
3656  * drm_dp_mst_allocate_vcpi() - Allocate a virtual channel
3657  * @mgr: manager for this port
3658  * @port: port to allocate a virtual channel for.
3659  * @pbn: payload bandwidth number to request
3660  * @slots: returned number of slots for this PBN.
3661  */
3662 bool drm_dp_mst_allocate_vcpi(struct drm_dp_mst_topology_mgr *mgr,
3663                               struct drm_dp_mst_port *port, int pbn, int slots)
3664 {
3665         int ret;
3666
3667         port = drm_dp_mst_topology_get_port_validated(mgr, port);
3668         if (!port)
3669                 return false;
3670
3671         if (slots < 0)
3672                 return false;
3673
3674         if (port->vcpi.vcpi > 0) {
3675                 DRM_DEBUG_KMS("payload: vcpi %d already allocated for pbn %d - requested pbn %d\n",
3676                               port->vcpi.vcpi, port->vcpi.pbn, pbn);
3677                 if (pbn == port->vcpi.pbn) {
3678                         drm_dp_mst_topology_put_port(port);
3679                         return true;
3680                 }
3681         }
3682
3683         ret = drm_dp_init_vcpi(mgr, &port->vcpi, pbn, slots);
3684         if (ret) {
3685                 DRM_DEBUG_KMS("failed to init vcpi slots=%d max=63 ret=%d\n",
3686                               DIV_ROUND_UP(pbn, mgr->pbn_div), ret);
3687                 goto out;
3688         }
3689         DRM_DEBUG_KMS("initing vcpi for pbn=%d slots=%d\n",
3690                       pbn, port->vcpi.num_slots);
3691
3692         /* Keep port allocated until its payload has been removed */
3693         drm_dp_mst_get_port_malloc(port);
3694         drm_dp_mst_topology_put_port(port);
3695         return true;
3696 out:
3697         return false;
3698 }
3699 EXPORT_SYMBOL(drm_dp_mst_allocate_vcpi);
3700
3701 int drm_dp_mst_get_vcpi_slots(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
3702 {
3703         int slots = 0;
3704         port = drm_dp_mst_topology_get_port_validated(mgr, port);
3705         if (!port)
3706                 return slots;
3707
3708         slots = port->vcpi.num_slots;
3709         drm_dp_mst_topology_put_port(port);
3710         return slots;
3711 }
3712 EXPORT_SYMBOL(drm_dp_mst_get_vcpi_slots);
3713
3714 /**
3715  * drm_dp_mst_reset_vcpi_slots() - Reset number of slots to 0 for VCPI
3716  * @mgr: manager for this port
3717  * @port: unverified pointer to a port.
3718  *
3719  * This just resets the number of slots for the ports VCPI for later programming.
3720  */
3721 void drm_dp_mst_reset_vcpi_slots(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
3722 {
3723         /*
3724          * A port with VCPI will remain allocated until its VCPI is
3725          * released, no verified ref needed
3726          */
3727
3728         port->vcpi.num_slots = 0;
3729 }
3730 EXPORT_SYMBOL(drm_dp_mst_reset_vcpi_slots);
3731
3732 /**
3733  * drm_dp_mst_deallocate_vcpi() - deallocate a VCPI
3734  * @mgr: manager for this port
3735  * @port: port to deallocate vcpi for
3736  *
3737  * This can be called unconditionally, regardless of whether
3738  * drm_dp_mst_allocate_vcpi() succeeded or not.
3739  */
3740 void drm_dp_mst_deallocate_vcpi(struct drm_dp_mst_topology_mgr *mgr,
3741                                 struct drm_dp_mst_port *port)
3742 {
3743         if (!port->vcpi.vcpi)
3744                 return;
3745
3746         drm_dp_mst_put_payload_id(mgr, port->vcpi.vcpi);
3747         port->vcpi.num_slots = 0;
3748         port->vcpi.pbn = 0;
3749         port->vcpi.aligned_pbn = 0;
3750         port->vcpi.vcpi = 0;
3751         drm_dp_mst_put_port_malloc(port);
3752 }
3753 EXPORT_SYMBOL(drm_dp_mst_deallocate_vcpi);
3754
3755 static int drm_dp_dpcd_write_payload(struct drm_dp_mst_topology_mgr *mgr,
3756                                      int id, struct drm_dp_payload *payload)
3757 {
3758         u8 payload_alloc[3], status;
3759         int ret;
3760         int retries = 0;
3761
3762         drm_dp_dpcd_writeb(mgr->aux, DP_PAYLOAD_TABLE_UPDATE_STATUS,
3763                            DP_PAYLOAD_TABLE_UPDATED);
3764
3765         payload_alloc[0] = id;
3766         payload_alloc[1] = payload->start_slot;
3767         payload_alloc[2] = payload->num_slots;
3768
3769         ret = drm_dp_dpcd_write(mgr->aux, DP_PAYLOAD_ALLOCATE_SET, payload_alloc, 3);
3770         if (ret != 3) {
3771                 DRM_DEBUG_KMS("failed to write payload allocation %d\n", ret);
3772                 goto fail;
3773         }
3774
3775 retry:
3776         ret = drm_dp_dpcd_readb(mgr->aux, DP_PAYLOAD_TABLE_UPDATE_STATUS, &status);
3777         if (ret < 0) {
3778                 DRM_DEBUG_KMS("failed to read payload table status %d\n", ret);
3779                 goto fail;
3780         }
3781
3782         if (!(status & DP_PAYLOAD_TABLE_UPDATED)) {
3783                 retries++;
3784                 if (retries < 20) {
3785                         usleep_range(10000, 20000);
3786                         goto retry;
3787                 }
3788                 DRM_DEBUG_KMS("status not set after read payload table status %d\n", status);
3789                 ret = -EINVAL;
3790                 goto fail;
3791         }
3792         ret = 0;
3793 fail:
3794         return ret;
3795 }
3796
3797
3798 /**
3799  * drm_dp_check_act_status() - Check ACT handled status.
3800  * @mgr: manager to use
3801  *
3802  * Check the payload status bits in the DPCD for ACT handled completion.
3803  */
3804 int drm_dp_check_act_status(struct drm_dp_mst_topology_mgr *mgr)
3805 {
3806         u8 status;
3807         int ret;
3808         int count = 0;
3809
3810         do {
3811                 ret = drm_dp_dpcd_readb(mgr->aux, DP_PAYLOAD_TABLE_UPDATE_STATUS, &status);
3812
3813                 if (ret < 0) {
3814                         DRM_DEBUG_KMS("failed to read payload table status %d\n", ret);
3815                         goto fail;
3816                 }
3817
3818                 if (status & DP_PAYLOAD_ACT_HANDLED)
3819                         break;
3820                 count++;
3821                 udelay(100);
3822
3823         } while (count < 30);
3824
3825         if (!(status & DP_PAYLOAD_ACT_HANDLED)) {
3826                 DRM_DEBUG_KMS("failed to get ACT bit %d after %d retries\n", status, count);
3827                 ret = -EINVAL;
3828                 goto fail;
3829         }
3830         return 0;
3831 fail:
3832         return ret;
3833 }
3834 EXPORT_SYMBOL(drm_dp_check_act_status);
3835
3836 /**
3837  * drm_dp_calc_pbn_mode() - Calculate the PBN for a mode.
3838  * @clock: dot clock for the mode
3839  * @bpp: bpp for the mode.
3840  *
3841  * This uses the formula in the spec to calculate the PBN value for a mode.
3842  */
3843 int drm_dp_calc_pbn_mode(int clock, int bpp)
3844 {
3845         /*
3846          * margin 5300ppm + 300ppm ~ 0.6% as per spec, factor is 1.006
3847          * The unit of 54/64Mbytes/sec is an arbitrary unit chosen based on
3848          * common multiplier to render an integer PBN for all link rate/lane
3849          * counts combinations
3850          * calculate
3851          * peak_kbps *= (1006/1000)
3852          * peak_kbps *= (64/54)
3853          * peak_kbps *= 8    convert to bytes
3854          */
3855         return DIV_ROUND_UP_ULL(mul_u32_u32(clock * bpp, 64 * 1006),
3856                                 8 * 54 * 1000 * 1000);
3857 }
3858 EXPORT_SYMBOL(drm_dp_calc_pbn_mode);
3859
3860 /* we want to kick the TX after we've ack the up/down IRQs. */
3861 static void drm_dp_mst_kick_tx(struct drm_dp_mst_topology_mgr *mgr)
3862 {
3863         queue_work(system_long_wq, &mgr->tx_work);
3864 }
3865
3866 static void drm_dp_mst_dump_mstb(struct seq_file *m,
3867                                  struct drm_dp_mst_branch *mstb)
3868 {
3869         struct drm_dp_mst_port *port;
3870         int tabs = mstb->lct;
3871         char prefix[10];
3872         int i;
3873
3874         for (i = 0; i < tabs; i++)
3875                 prefix[i] = '\t';
3876         prefix[i] = '\0';
3877
3878         seq_printf(m, "%smst: %p, %d\n", prefix, mstb, mstb->num_ports);
3879         list_for_each_entry(port, &mstb->ports, next) {
3880                 seq_printf(m, "%sport: %d: input: %d: pdt: %d, ddps: %d ldps: %d, sdp: %d/%d, %p, conn: %p\n", prefix, port->port_num, port->input, port->pdt, port->ddps, port->ldps, port->num_sdp_streams, port->num_sdp_stream_sinks, port, port->connector);
3881                 if (port->mstb)
3882                         drm_dp_mst_dump_mstb(m, port->mstb);
3883         }
3884 }
3885
3886 #define DP_PAYLOAD_TABLE_SIZE           64
3887
3888 static bool dump_dp_payload_table(struct drm_dp_mst_topology_mgr *mgr,
3889                                   char *buf)
3890 {
3891         int i;
3892
3893         for (i = 0; i < DP_PAYLOAD_TABLE_SIZE; i += 16) {
3894                 if (drm_dp_dpcd_read(mgr->aux,
3895                                      DP_PAYLOAD_TABLE_UPDATE_STATUS + i,
3896                                      &buf[i], 16) != 16)
3897                         return false;
3898         }
3899         return true;
3900 }
3901
3902 static void fetch_monitor_name(struct drm_dp_mst_topology_mgr *mgr,
3903                                struct drm_dp_mst_port *port, char *name,
3904                                int namelen)
3905 {
3906         struct edid *mst_edid;
3907
3908         mst_edid = drm_dp_mst_get_edid(port->connector, mgr, port);
3909         drm_edid_get_monitor_name(mst_edid, name, namelen);
3910 }
3911
3912 /**
3913  * drm_dp_mst_dump_topology(): dump topology to seq file.
3914  * @m: seq_file to dump output to
3915  * @mgr: manager to dump current topology for.
3916  *
3917  * helper to dump MST topology to a seq file for debugfs.
3918  */
3919 void drm_dp_mst_dump_topology(struct seq_file *m,
3920                               struct drm_dp_mst_topology_mgr *mgr)
3921 {
3922         int i;
3923         struct drm_dp_mst_port *port;
3924
3925         mutex_lock(&mgr->lock);
3926         if (mgr->mst_primary)
3927                 drm_dp_mst_dump_mstb(m, mgr->mst_primary);
3928
3929         /* dump VCPIs */
3930         mutex_unlock(&mgr->lock);
3931
3932         mutex_lock(&mgr->payload_lock);
3933         seq_printf(m, "vcpi: %lx %lx %d\n", mgr->payload_mask, mgr->vcpi_mask,
3934                 mgr->max_payloads);
3935
3936         for (i = 0; i < mgr->max_payloads; i++) {
3937                 if (mgr->proposed_vcpis[i]) {
3938                         char name[14];
3939
3940                         port = container_of(mgr->proposed_vcpis[i], struct drm_dp_mst_port, vcpi);
3941                         fetch_monitor_name(mgr, port, name, sizeof(name));
3942                         seq_printf(m, "vcpi %d: %d %d %d sink name: %s\n", i,
3943                                    port->port_num, port->vcpi.vcpi,
3944                                    port->vcpi.num_slots,
3945                                    (*name != 0) ? name :  "Unknown");
3946                 } else
3947                         seq_printf(m, "vcpi %d:unused\n", i);
3948         }
3949         for (i = 0; i < mgr->max_payloads; i++) {
3950                 seq_printf(m, "payload %d: %d, %d, %d\n",
3951                            i,
3952                            mgr->payloads[i].payload_state,
3953                            mgr->payloads[i].start_slot,
3954                            mgr->payloads[i].num_slots);
3955
3956
3957         }
3958         mutex_unlock(&mgr->payload_lock);
3959
3960         mutex_lock(&mgr->lock);
3961         if (mgr->mst_primary) {
3962                 u8 buf[DP_PAYLOAD_TABLE_SIZE];
3963                 int ret;
3964
3965                 ret = drm_dp_dpcd_read(mgr->aux, DP_DPCD_REV, buf, DP_RECEIVER_CAP_SIZE);
3966                 seq_printf(m, "dpcd: %*ph\n", DP_RECEIVER_CAP_SIZE, buf);
3967                 ret = drm_dp_dpcd_read(mgr->aux, DP_FAUX_CAP, buf, 2);
3968                 seq_printf(m, "faux/mst: %*ph\n", 2, buf);
3969                 ret = drm_dp_dpcd_read(mgr->aux, DP_MSTM_CTRL, buf, 1);
3970                 seq_printf(m, "mst ctrl: %*ph\n", 1, buf);
3971
3972                 /* dump the standard OUI branch header */
3973                 ret = drm_dp_dpcd_read(mgr->aux, DP_BRANCH_OUI, buf, DP_BRANCH_OUI_HEADER_SIZE);
3974                 seq_printf(m, "branch oui: %*phN devid: ", 3, buf);
3975                 for (i = 0x3; i < 0x8 && buf[i]; i++)
3976                         seq_printf(m, "%c", buf[i]);
3977                 seq_printf(m, " revision: hw: %x.%x sw: %x.%x\n",
3978                            buf[0x9] >> 4, buf[0x9] & 0xf, buf[0xa], buf[0xb]);
3979                 if (dump_dp_payload_table(mgr, buf))
3980                         seq_printf(m, "payload table: %*ph\n", DP_PAYLOAD_TABLE_SIZE, buf);
3981         }
3982
3983         mutex_unlock(&mgr->lock);
3984
3985 }
3986 EXPORT_SYMBOL(drm_dp_mst_dump_topology);
3987
3988 static void drm_dp_tx_work(struct work_struct *work)
3989 {
3990         struct drm_dp_mst_topology_mgr *mgr = container_of(work, struct drm_dp_mst_topology_mgr, tx_work);
3991
3992         mutex_lock(&mgr->qlock);
3993         if (!list_empty(&mgr->tx_msg_downq))
3994                 process_single_down_tx_qlock(mgr);
3995         mutex_unlock(&mgr->qlock);
3996 }
3997
3998 static void drm_dp_destroy_connector_work(struct work_struct *work)
3999 {
4000         struct drm_dp_mst_topology_mgr *mgr = container_of(work, struct drm_dp_mst_topology_mgr, destroy_connector_work);
4001         struct drm_dp_mst_port *port;
4002         bool send_hotplug = false;
4003         /*
4004          * Not a regular list traverse as we have to drop the destroy
4005          * connector lock before destroying the connector, to avoid AB->BA
4006          * ordering between this lock and the config mutex.
4007          */
4008         for (;;) {
4009                 mutex_lock(&mgr->destroy_connector_lock);
4010                 port = list_first_entry_or_null(&mgr->destroy_connector_list, struct drm_dp_mst_port, next);
4011                 if (!port) {
4012                         mutex_unlock(&mgr->destroy_connector_lock);
4013                         break;
4014                 }
4015                 list_del(&port->next);
4016                 mutex_unlock(&mgr->destroy_connector_lock);
4017
4018                 mgr->cbs->destroy_connector(mgr, port->connector);
4019
4020                 drm_dp_port_teardown_pdt(port, port->pdt);
4021                 port->pdt = DP_PEER_DEVICE_NONE;
4022
4023                 drm_dp_mst_put_port_malloc(port);
4024                 send_hotplug = true;
4025         }
4026         if (send_hotplug)
4027                 drm_kms_helper_hotplug_event(mgr->dev);
4028 }
4029
4030 static struct drm_private_state *
4031 drm_dp_mst_duplicate_state(struct drm_private_obj *obj)
4032 {
4033         struct drm_dp_mst_topology_state *state, *old_state =
4034                 to_dp_mst_topology_state(obj->state);
4035         struct drm_dp_vcpi_allocation *pos, *vcpi;
4036
4037         state = kmemdup(old_state, sizeof(*state), GFP_KERNEL);
4038         if (!state)
4039                 return NULL;
4040
4041         __drm_atomic_helper_private_obj_duplicate_state(obj, &state->base);
4042
4043         INIT_LIST_HEAD(&state->vcpis);
4044
4045         list_for_each_entry(pos, &old_state->vcpis, next) {
4046                 /* Prune leftover freed VCPI allocations */
4047                 if (!pos->vcpi)
4048                         continue;
4049
4050                 vcpi = kmemdup(pos, sizeof(*vcpi), GFP_KERNEL);
4051                 if (!vcpi)
4052                         goto fail;
4053
4054                 drm_dp_mst_get_port_malloc(vcpi->port);
4055                 list_add(&vcpi->next, &state->vcpis);
4056         }
4057
4058         return &state->base;
4059
4060 fail:
4061         list_for_each_entry_safe(pos, vcpi, &state->vcpis, next) {
4062                 drm_dp_mst_put_port_malloc(pos->port);
4063                 kfree(pos);
4064         }
4065         kfree(state);
4066
4067         return NULL;
4068 }
4069
4070 static void drm_dp_mst_destroy_state(struct drm_private_obj *obj,
4071                                      struct drm_private_state *state)
4072 {
4073         struct drm_dp_mst_topology_state *mst_state =
4074                 to_dp_mst_topology_state(state);
4075         struct drm_dp_vcpi_allocation *pos, *tmp;
4076
4077         list_for_each_entry_safe(pos, tmp, &mst_state->vcpis, next) {
4078                 /* We only keep references to ports with non-zero VCPIs */
4079                 if (pos->vcpi)
4080                         drm_dp_mst_put_port_malloc(pos->port);
4081                 kfree(pos);
4082         }
4083
4084         kfree(mst_state);
4085 }
4086
4087 static inline int
4088 drm_dp_mst_atomic_check_topology_state(struct drm_dp_mst_topology_mgr *mgr,
4089                                        struct drm_dp_mst_topology_state *mst_state)
4090 {
4091         struct drm_dp_vcpi_allocation *vcpi;
4092         int avail_slots = 63, payload_count = 0;
4093
4094         list_for_each_entry(vcpi, &mst_state->vcpis, next) {
4095                 /* Releasing VCPI is always OK-even if the port is gone */
4096                 if (!vcpi->vcpi) {
4097                         DRM_DEBUG_ATOMIC("[MST PORT:%p] releases all VCPI slots\n",
4098                                          vcpi->port);
4099                         continue;
4100                 }
4101
4102                 DRM_DEBUG_ATOMIC("[MST PORT:%p] requires %d vcpi slots\n",
4103                                  vcpi->port, vcpi->vcpi);
4104
4105                 avail_slots -= vcpi->vcpi;
4106                 if (avail_slots < 0) {
4107                         DRM_DEBUG_ATOMIC("[MST PORT:%p] not enough VCPI slots in mst state %p (avail=%d)\n",
4108                                          vcpi->port, mst_state,
4109                                          avail_slots + vcpi->vcpi);
4110                         return -ENOSPC;
4111                 }
4112
4113                 if (++payload_count > mgr->max_payloads) {
4114                         DRM_DEBUG_ATOMIC("[MST MGR:%p] state %p has too many payloads (max=%d)\n",
4115                                          mgr, mst_state, mgr->max_payloads);
4116                         return -EINVAL;
4117                 }
4118         }
4119         DRM_DEBUG_ATOMIC("[MST MGR:%p] mst state %p VCPI avail=%d used=%d\n",
4120                          mgr, mst_state, avail_slots,
4121                          63 - avail_slots);
4122
4123         return 0;
4124 }
4125
4126 /**
4127  * drm_dp_mst_atomic_check - Check that the new state of an MST topology in an
4128  * atomic update is valid
4129  * @state: Pointer to the new &struct drm_dp_mst_topology_state
4130  *
4131  * Checks the given topology state for an atomic update to ensure that it's
4132  * valid. This includes checking whether there's enough bandwidth to support
4133  * the new VCPI allocations in the atomic update.
4134  *
4135  * Any atomic drivers supporting DP MST must make sure to call this after
4136  * checking the rest of their state in their
4137  * &drm_mode_config_funcs.atomic_check() callback.
4138  *
4139  * See also:
4140  * drm_dp_atomic_find_vcpi_slots()
4141  * drm_dp_atomic_release_vcpi_slots()
4142  *
4143  * Returns:
4144  *
4145  * 0 if the new state is valid, negative error code otherwise.
4146  */
4147 int drm_dp_mst_atomic_check(struct drm_atomic_state *state)
4148 {
4149         struct drm_dp_mst_topology_mgr *mgr;
4150         struct drm_dp_mst_topology_state *mst_state;
4151         int i, ret = 0;
4152
4153         for_each_new_mst_mgr_in_state(state, mgr, mst_state, i) {
4154                 ret = drm_dp_mst_atomic_check_topology_state(mgr, mst_state);
4155                 if (ret)
4156                         break;
4157         }
4158
4159         return ret;
4160 }
4161 EXPORT_SYMBOL(drm_dp_mst_atomic_check);
4162
4163 const struct drm_private_state_funcs drm_dp_mst_topology_state_funcs = {
4164         .atomic_duplicate_state = drm_dp_mst_duplicate_state,
4165         .atomic_destroy_state = drm_dp_mst_destroy_state,
4166 };
4167 EXPORT_SYMBOL(drm_dp_mst_topology_state_funcs);
4168
4169 /**
4170  * drm_atomic_get_mst_topology_state: get MST topology state
4171  *
4172  * @state: global atomic state
4173  * @mgr: MST topology manager, also the private object in this case
4174  *
4175  * This function wraps drm_atomic_get_priv_obj_state() passing in the MST atomic
4176  * state vtable so that the private object state returned is that of a MST
4177  * topology object. Also, drm_atomic_get_private_obj_state() expects the caller
4178  * to care of the locking, so warn if don't hold the connection_mutex.
4179  *
4180  * RETURNS:
4181  *
4182  * The MST topology state or error pointer.
4183  */
4184 struct drm_dp_mst_topology_state *drm_atomic_get_mst_topology_state(struct drm_atomic_state *state,
4185                                                                     struct drm_dp_mst_topology_mgr *mgr)
4186 {
4187         struct drm_device *dev = mgr->dev;
4188
4189         WARN_ON(!drm_modeset_is_locked(&dev->mode_config.connection_mutex));
4190         return to_dp_mst_topology_state(drm_atomic_get_private_obj_state(state, &mgr->base));
4191 }
4192 EXPORT_SYMBOL(drm_atomic_get_mst_topology_state);
4193
4194 /**
4195  * drm_dp_mst_topology_mgr_init - initialise a topology manager
4196  * @mgr: manager struct to initialise
4197  * @dev: device providing this structure - for i2c addition.
4198  * @aux: DP helper aux channel to talk to this device
4199  * @max_dpcd_transaction_bytes: hw specific DPCD transaction limit
4200  * @max_payloads: maximum number of payloads this GPU can source
4201  * @conn_base_id: the connector object ID the MST device is connected to.
4202  *
4203  * Return 0 for success, or negative error code on failure
4204  */
4205 int drm_dp_mst_topology_mgr_init(struct drm_dp_mst_topology_mgr *mgr,
4206                                  struct drm_device *dev, struct drm_dp_aux *aux,
4207                                  int max_dpcd_transaction_bytes,
4208                                  int max_payloads, int conn_base_id)
4209 {
4210         struct drm_dp_mst_topology_state *mst_state;
4211
4212         mutex_init(&mgr->lock);
4213         mutex_init(&mgr->qlock);
4214         mutex_init(&mgr->payload_lock);
4215         mutex_init(&mgr->destroy_connector_lock);
4216         INIT_LIST_HEAD(&mgr->tx_msg_downq);
4217         INIT_LIST_HEAD(&mgr->destroy_connector_list);
4218         INIT_WORK(&mgr->work, drm_dp_mst_link_probe_work);
4219         INIT_WORK(&mgr->tx_work, drm_dp_tx_work);
4220         INIT_WORK(&mgr->destroy_connector_work, drm_dp_destroy_connector_work);
4221         init_waitqueue_head(&mgr->tx_waitq);
4222         mgr->dev = dev;
4223         mgr->aux = aux;
4224         mgr->max_dpcd_transaction_bytes = max_dpcd_transaction_bytes;
4225         mgr->max_payloads = max_payloads;
4226         mgr->conn_base_id = conn_base_id;
4227         if (max_payloads + 1 > sizeof(mgr->payload_mask) * 8 ||
4228             max_payloads + 1 > sizeof(mgr->vcpi_mask) * 8)
4229                 return -EINVAL;
4230         mgr->payloads = kcalloc(max_payloads, sizeof(struct drm_dp_payload), GFP_KERNEL);
4231         if (!mgr->payloads)
4232                 return -ENOMEM;
4233         mgr->proposed_vcpis = kcalloc(max_payloads, sizeof(struct drm_dp_vcpi *), GFP_KERNEL);
4234         if (!mgr->proposed_vcpis)
4235                 return -ENOMEM;
4236         set_bit(0, &mgr->payload_mask);
4237
4238         mst_state = kzalloc(sizeof(*mst_state), GFP_KERNEL);
4239         if (mst_state == NULL)
4240                 return -ENOMEM;
4241
4242         mst_state->mgr = mgr;
4243         INIT_LIST_HEAD(&mst_state->vcpis);
4244
4245         drm_atomic_private_obj_init(dev, &mgr->base,
4246                                     &mst_state->base,
4247                                     &drm_dp_mst_topology_state_funcs);
4248
4249         return 0;
4250 }
4251 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_init);
4252
4253 /**
4254  * drm_dp_mst_topology_mgr_destroy() - destroy topology manager.
4255  * @mgr: manager to destroy
4256  */
4257 void drm_dp_mst_topology_mgr_destroy(struct drm_dp_mst_topology_mgr *mgr)
4258 {
4259         drm_dp_mst_topology_mgr_set_mst(mgr, false);
4260         flush_work(&mgr->work);
4261         flush_work(&mgr->destroy_connector_work);
4262         mutex_lock(&mgr->payload_lock);
4263         kfree(mgr->payloads);
4264         mgr->payloads = NULL;
4265         kfree(mgr->proposed_vcpis);
4266         mgr->proposed_vcpis = NULL;
4267         mutex_unlock(&mgr->payload_lock);
4268         mgr->dev = NULL;
4269         mgr->aux = NULL;
4270         drm_atomic_private_obj_fini(&mgr->base);
4271         mgr->funcs = NULL;
4272
4273         mutex_destroy(&mgr->destroy_connector_lock);
4274         mutex_destroy(&mgr->payload_lock);
4275         mutex_destroy(&mgr->qlock);
4276         mutex_destroy(&mgr->lock);
4277 }
4278 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_destroy);
4279
4280 static bool remote_i2c_read_ok(const struct i2c_msg msgs[], int num)
4281 {
4282         int i;
4283
4284         if (num - 1 > DP_REMOTE_I2C_READ_MAX_TRANSACTIONS)
4285                 return false;
4286
4287         for (i = 0; i < num - 1; i++) {
4288                 if (msgs[i].flags & I2C_M_RD ||
4289                     msgs[i].len > 0xff)
4290                         return false;
4291         }
4292
4293         return msgs[num - 1].flags & I2C_M_RD &&
4294                 msgs[num - 1].len <= 0xff;
4295 }
4296
4297 /* I2C device */
4298 static int drm_dp_mst_i2c_xfer(struct i2c_adapter *adapter, struct i2c_msg *msgs,
4299                                int num)
4300 {
4301         struct drm_dp_aux *aux = adapter->algo_data;
4302         struct drm_dp_mst_port *port = container_of(aux, struct drm_dp_mst_port, aux);
4303         struct drm_dp_mst_branch *mstb;
4304         struct drm_dp_mst_topology_mgr *mgr = port->mgr;
4305         unsigned int i;
4306         struct drm_dp_sideband_msg_req_body msg;
4307         struct drm_dp_sideband_msg_tx *txmsg = NULL;
4308         int ret;
4309
4310         mstb = drm_dp_mst_topology_get_mstb_validated(mgr, port->parent);
4311         if (!mstb)
4312                 return -EREMOTEIO;
4313
4314         if (!remote_i2c_read_ok(msgs, num)) {
4315                 DRM_DEBUG_KMS("Unsupported I2C transaction for MST device\n");
4316                 ret = -EIO;
4317                 goto out;
4318         }
4319
4320         memset(&msg, 0, sizeof(msg));
4321         msg.req_type = DP_REMOTE_I2C_READ;
4322         msg.u.i2c_read.num_transactions = num - 1;
4323         msg.u.i2c_read.port_number = port->port_num;
4324         for (i = 0; i < num - 1; i++) {
4325                 msg.u.i2c_read.transactions[i].i2c_dev_id = msgs[i].addr;
4326                 msg.u.i2c_read.transactions[i].num_bytes = msgs[i].len;
4327                 msg.u.i2c_read.transactions[i].bytes = msgs[i].buf;
4328                 msg.u.i2c_read.transactions[i].no_stop_bit = !(msgs[i].flags & I2C_M_STOP);
4329         }
4330         msg.u.i2c_read.read_i2c_device_id = msgs[num - 1].addr;
4331         msg.u.i2c_read.num_bytes_read = msgs[num - 1].len;
4332
4333         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
4334         if (!txmsg) {
4335                 ret = -ENOMEM;
4336                 goto out;
4337         }
4338
4339         txmsg->dst = mstb;
4340         drm_dp_encode_sideband_req(&msg, txmsg);
4341
4342         drm_dp_queue_down_tx(mgr, txmsg);
4343
4344         ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
4345         if (ret > 0) {
4346
4347                 if (txmsg->reply.reply_type == DP_SIDEBAND_REPLY_NAK) {
4348                         ret = -EREMOTEIO;
4349                         goto out;
4350                 }
4351                 if (txmsg->reply.u.remote_i2c_read_ack.num_bytes != msgs[num - 1].len) {
4352                         ret = -EIO;
4353                         goto out;
4354                 }
4355                 memcpy(msgs[num - 1].buf, txmsg->reply.u.remote_i2c_read_ack.bytes, msgs[num - 1].len);
4356                 ret = num;
4357         }
4358 out:
4359         kfree(txmsg);
4360         drm_dp_mst_topology_put_mstb(mstb);
4361         return ret;
4362 }
4363
4364 static u32 drm_dp_mst_i2c_functionality(struct i2c_adapter *adapter)
4365 {
4366         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
4367                I2C_FUNC_SMBUS_READ_BLOCK_DATA |
4368                I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
4369                I2C_FUNC_10BIT_ADDR;
4370 }
4371
4372 static const struct i2c_algorithm drm_dp_mst_i2c_algo = {
4373         .functionality = drm_dp_mst_i2c_functionality,
4374         .master_xfer = drm_dp_mst_i2c_xfer,
4375 };
4376
4377 /**
4378  * drm_dp_mst_register_i2c_bus() - register an I2C adapter for I2C-over-AUX
4379  * @aux: DisplayPort AUX channel
4380  *
4381  * Returns 0 on success or a negative error code on failure.
4382  */
4383 static int drm_dp_mst_register_i2c_bus(struct drm_dp_aux *aux)
4384 {
4385         aux->ddc.algo = &drm_dp_mst_i2c_algo;
4386         aux->ddc.algo_data = aux;
4387         aux->ddc.retries = 3;
4388
4389         aux->ddc.class = I2C_CLASS_DDC;
4390         aux->ddc.owner = THIS_MODULE;
4391         aux->ddc.dev.parent = aux->dev;
4392         aux->ddc.dev.of_node = aux->dev->of_node;
4393
4394         strlcpy(aux->ddc.name, aux->name ? aux->name : dev_name(aux->dev),
4395                 sizeof(aux->ddc.name));
4396
4397         return i2c_add_adapter(&aux->ddc);
4398 }
4399
4400 /**
4401  * drm_dp_mst_unregister_i2c_bus() - unregister an I2C-over-AUX adapter
4402  * @aux: DisplayPort AUX channel
4403  */
4404 static void drm_dp_mst_unregister_i2c_bus(struct drm_dp_aux *aux)
4405 {
4406         i2c_del_adapter(&aux->ddc);
4407 }
This page took 0.29062 seconds and 4 git commands to generate.