drm/mst: fix build with debugfs off.
[cascardo/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/kernel.h>
24 #include <linux/delay.h>
25 #include <linux/init.h>
26 #include <linux/errno.h>
27 #include <linux/sched.h>
28 #include <linux/seq_file.h>
29 #include <linux/i2c.h>
30 #include <drm/drm_dp_mst_helper.h>
31 #include <drm/drmP.h>
32
33 #include <drm/drm_fixed.h>
34
35 /**
36  * DOC: dp mst helper
37  *
38  * These functions contain parts of the DisplayPort 1.2a MultiStream Transport
39  * protocol. The helpers contain a topology manager and bandwidth manager.
40  * The helpers encapsulate the sending and received of sideband msgs.
41  */
42 static bool dump_dp_payload_table(struct drm_dp_mst_topology_mgr *mgr,
43                                   char *buf);
44 static int test_calc_pbn_mode(void);
45
46 static void drm_dp_put_port(struct drm_dp_mst_port *port);
47
48 static int drm_dp_dpcd_write_payload(struct drm_dp_mst_topology_mgr *mgr,
49                                      int id,
50                                      struct drm_dp_payload *payload);
51
52 static int drm_dp_send_dpcd_write(struct drm_dp_mst_topology_mgr *mgr,
53                                   struct drm_dp_mst_port *port,
54                                   int offset, int size, u8 *bytes);
55
56 static int drm_dp_send_link_address(struct drm_dp_mst_topology_mgr *mgr,
57                                     struct drm_dp_mst_branch *mstb);
58 static int drm_dp_send_enum_path_resources(struct drm_dp_mst_topology_mgr *mgr,
59                                            struct drm_dp_mst_branch *mstb,
60                                            struct drm_dp_mst_port *port);
61 static bool drm_dp_validate_guid(struct drm_dp_mst_topology_mgr *mgr,
62                                  u8 *guid);
63
64 static int drm_dp_mst_register_i2c_bus(struct drm_dp_aux *aux);
65 static void drm_dp_mst_unregister_i2c_bus(struct drm_dp_aux *aux);
66 static void drm_dp_mst_kick_tx(struct drm_dp_mst_topology_mgr *mgr);
67 /* sideband msg handling */
68 static u8 drm_dp_msg_header_crc4(const uint8_t *data, size_t num_nibbles)
69 {
70         u8 bitmask = 0x80;
71         u8 bitshift = 7;
72         u8 array_index = 0;
73         int number_of_bits = num_nibbles * 4;
74         u8 remainder = 0;
75
76         while (number_of_bits != 0) {
77                 number_of_bits--;
78                 remainder <<= 1;
79                 remainder |= (data[array_index] & bitmask) >> bitshift;
80                 bitmask >>= 1;
81                 bitshift--;
82                 if (bitmask == 0) {
83                         bitmask = 0x80;
84                         bitshift = 7;
85                         array_index++;
86                 }
87                 if ((remainder & 0x10) == 0x10)
88                         remainder ^= 0x13;
89         }
90
91         number_of_bits = 4;
92         while (number_of_bits != 0) {
93                 number_of_bits--;
94                 remainder <<= 1;
95                 if ((remainder & 0x10) != 0)
96                         remainder ^= 0x13;
97         }
98
99         return remainder;
100 }
101
102 static u8 drm_dp_msg_data_crc4(const uint8_t *data, u8 number_of_bytes)
103 {
104         u8 bitmask = 0x80;
105         u8 bitshift = 7;
106         u8 array_index = 0;
107         int number_of_bits = number_of_bytes * 8;
108         u16 remainder = 0;
109
110         while (number_of_bits != 0) {
111                 number_of_bits--;
112                 remainder <<= 1;
113                 remainder |= (data[array_index] & bitmask) >> bitshift;
114                 bitmask >>= 1;
115                 bitshift--;
116                 if (bitmask == 0) {
117                         bitmask = 0x80;
118                         bitshift = 7;
119                         array_index++;
120                 }
121                 if ((remainder & 0x100) == 0x100)
122                         remainder ^= 0xd5;
123         }
124
125         number_of_bits = 8;
126         while (number_of_bits != 0) {
127                 number_of_bits--;
128                 remainder <<= 1;
129                 if ((remainder & 0x100) != 0)
130                         remainder ^= 0xd5;
131         }
132
133         return remainder & 0xff;
134 }
135 static inline u8 drm_dp_calc_sb_hdr_size(struct drm_dp_sideband_msg_hdr *hdr)
136 {
137         u8 size = 3;
138         size += (hdr->lct / 2);
139         return size;
140 }
141
142 static void drm_dp_encode_sideband_msg_hdr(struct drm_dp_sideband_msg_hdr *hdr,
143                                            u8 *buf, int *len)
144 {
145         int idx = 0;
146         int i;
147         u8 crc4;
148         buf[idx++] = ((hdr->lct & 0xf) << 4) | (hdr->lcr & 0xf);
149         for (i = 0; i < (hdr->lct / 2); i++)
150                 buf[idx++] = hdr->rad[i];
151         buf[idx++] = (hdr->broadcast << 7) | (hdr->path_msg << 6) |
152                 (hdr->msg_len & 0x3f);
153         buf[idx++] = (hdr->somt << 7) | (hdr->eomt << 6) | (hdr->seqno << 4);
154
155         crc4 = drm_dp_msg_header_crc4(buf, (idx * 2) - 1);
156         buf[idx - 1] |= (crc4 & 0xf);
157
158         *len = idx;
159 }
160
161 static bool drm_dp_decode_sideband_msg_hdr(struct drm_dp_sideband_msg_hdr *hdr,
162                                            u8 *buf, int buflen, u8 *hdrlen)
163 {
164         u8 crc4;
165         u8 len;
166         int i;
167         u8 idx;
168         if (buf[0] == 0)
169                 return false;
170         len = 3;
171         len += ((buf[0] & 0xf0) >> 4) / 2;
172         if (len > buflen)
173                 return false;
174         crc4 = drm_dp_msg_header_crc4(buf, (len * 2) - 1);
175
176         if ((crc4 & 0xf) != (buf[len - 1] & 0xf)) {
177                 DRM_DEBUG_KMS("crc4 mismatch 0x%x 0x%x\n", crc4, buf[len - 1]);
178                 return false;
179         }
180
181         hdr->lct = (buf[0] & 0xf0) >> 4;
182         hdr->lcr = (buf[0] & 0xf);
183         idx = 1;
184         for (i = 0; i < (hdr->lct / 2); i++)
185                 hdr->rad[i] = buf[idx++];
186         hdr->broadcast = (buf[idx] >> 7) & 0x1;
187         hdr->path_msg = (buf[idx] >> 6) & 0x1;
188         hdr->msg_len = buf[idx] & 0x3f;
189         idx++;
190         hdr->somt = (buf[idx] >> 7) & 0x1;
191         hdr->eomt = (buf[idx] >> 6) & 0x1;
192         hdr->seqno = (buf[idx] >> 4) & 0x1;
193         idx++;
194         *hdrlen = idx;
195         return true;
196 }
197
198 static void drm_dp_encode_sideband_req(struct drm_dp_sideband_msg_req_body *req,
199                                        struct drm_dp_sideband_msg_tx *raw)
200 {
201         int idx = 0;
202         int i;
203         u8 *buf = raw->msg;
204         buf[idx++] = req->req_type & 0x7f;
205
206         switch (req->req_type) {
207         case DP_ENUM_PATH_RESOURCES:
208                 buf[idx] = (req->u.port_num.port_number & 0xf) << 4;
209                 idx++;
210                 break;
211         case DP_ALLOCATE_PAYLOAD:
212                 buf[idx] = (req->u.allocate_payload.port_number & 0xf) << 4 |
213                         (req->u.allocate_payload.number_sdp_streams & 0xf);
214                 idx++;
215                 buf[idx] = (req->u.allocate_payload.vcpi & 0x7f);
216                 idx++;
217                 buf[idx] = (req->u.allocate_payload.pbn >> 8);
218                 idx++;
219                 buf[idx] = (req->u.allocate_payload.pbn & 0xff);
220                 idx++;
221                 for (i = 0; i < req->u.allocate_payload.number_sdp_streams / 2; i++) {
222                         buf[idx] = ((req->u.allocate_payload.sdp_stream_sink[i * 2] & 0xf) << 4) |
223                                 (req->u.allocate_payload.sdp_stream_sink[i * 2 + 1] & 0xf);
224                         idx++;
225                 }
226                 if (req->u.allocate_payload.number_sdp_streams & 1) {
227                         i = req->u.allocate_payload.number_sdp_streams - 1;
228                         buf[idx] = (req->u.allocate_payload.sdp_stream_sink[i] & 0xf) << 4;
229                         idx++;
230                 }
231                 break;
232         case DP_QUERY_PAYLOAD:
233                 buf[idx] = (req->u.query_payload.port_number & 0xf) << 4;
234                 idx++;
235                 buf[idx] = (req->u.query_payload.vcpi & 0x7f);
236                 idx++;
237                 break;
238         case DP_REMOTE_DPCD_READ:
239                 buf[idx] = (req->u.dpcd_read.port_number & 0xf) << 4;
240                 buf[idx] |= ((req->u.dpcd_read.dpcd_address & 0xf0000) >> 16) & 0xf;
241                 idx++;
242                 buf[idx] = (req->u.dpcd_read.dpcd_address & 0xff00) >> 8;
243                 idx++;
244                 buf[idx] = (req->u.dpcd_read.dpcd_address & 0xff);
245                 idx++;
246                 buf[idx] = (req->u.dpcd_read.num_bytes);
247                 idx++;
248                 break;
249
250         case DP_REMOTE_DPCD_WRITE:
251                 buf[idx] = (req->u.dpcd_write.port_number & 0xf) << 4;
252                 buf[idx] |= ((req->u.dpcd_write.dpcd_address & 0xf0000) >> 16) & 0xf;
253                 idx++;
254                 buf[idx] = (req->u.dpcd_write.dpcd_address & 0xff00) >> 8;
255                 idx++;
256                 buf[idx] = (req->u.dpcd_write.dpcd_address & 0xff);
257                 idx++;
258                 buf[idx] = (req->u.dpcd_write.num_bytes);
259                 idx++;
260                 memcpy(&buf[idx], req->u.dpcd_write.bytes, req->u.dpcd_write.num_bytes);
261                 idx += req->u.dpcd_write.num_bytes;
262                 break;
263         case DP_REMOTE_I2C_READ:
264                 buf[idx] = (req->u.i2c_read.port_number & 0xf) << 4;
265                 buf[idx] |= (req->u.i2c_read.num_transactions & 0x3);
266                 idx++;
267                 for (i = 0; i < (req->u.i2c_read.num_transactions & 0x3); i++) {
268                         buf[idx] = req->u.i2c_read.transactions[i].i2c_dev_id & 0x7f;
269                         idx++;
270                         buf[idx] = req->u.i2c_read.transactions[i].num_bytes;
271                         idx++;
272                         memcpy(&buf[idx], req->u.i2c_read.transactions[i].bytes, req->u.i2c_read.transactions[i].num_bytes);
273                         idx += req->u.i2c_read.transactions[i].num_bytes;
274
275                         buf[idx] = (req->u.i2c_read.transactions[i].no_stop_bit & 0x1) << 5;
276                         buf[idx] |= (req->u.i2c_read.transactions[i].i2c_transaction_delay & 0xf);
277                         idx++;
278                 }
279                 buf[idx] = (req->u.i2c_read.read_i2c_device_id) & 0x7f;
280                 idx++;
281                 buf[idx] = (req->u.i2c_read.num_bytes_read);
282                 idx++;
283                 break;
284
285         case DP_REMOTE_I2C_WRITE:
286                 buf[idx] = (req->u.i2c_write.port_number & 0xf) << 4;
287                 idx++;
288                 buf[idx] = (req->u.i2c_write.write_i2c_device_id) & 0x7f;
289                 idx++;
290                 buf[idx] = (req->u.i2c_write.num_bytes);
291                 idx++;
292                 memcpy(&buf[idx], req->u.i2c_write.bytes, req->u.i2c_write.num_bytes);
293                 idx += req->u.i2c_write.num_bytes;
294                 break;
295         }
296         raw->cur_len = idx;
297 }
298
299 static void drm_dp_crc_sideband_chunk_req(u8 *msg, u8 len)
300 {
301         u8 crc4;
302         crc4 = drm_dp_msg_data_crc4(msg, len);
303         msg[len] = crc4;
304 }
305
306 static void drm_dp_encode_sideband_reply(struct drm_dp_sideband_msg_reply_body *rep,
307                                          struct drm_dp_sideband_msg_tx *raw)
308 {
309         int idx = 0;
310         u8 *buf = raw->msg;
311
312         buf[idx++] = (rep->reply_type & 0x1) << 7 | (rep->req_type & 0x7f);
313
314         raw->cur_len = idx;
315 }
316
317 /* this adds a chunk of msg to the builder to get the final msg */
318 static bool drm_dp_sideband_msg_build(struct drm_dp_sideband_msg_rx *msg,
319                                       u8 *replybuf, u8 replybuflen, bool hdr)
320 {
321         int ret;
322         u8 crc4;
323
324         if (hdr) {
325                 u8 hdrlen;
326                 struct drm_dp_sideband_msg_hdr recv_hdr;
327                 ret = drm_dp_decode_sideband_msg_hdr(&recv_hdr, replybuf, replybuflen, &hdrlen);
328                 if (ret == false) {
329                         print_hex_dump(KERN_DEBUG, "failed hdr", DUMP_PREFIX_NONE, 16, 1, replybuf, replybuflen, false);
330                         return false;
331                 }
332
333                 /* get length contained in this portion */
334                 msg->curchunk_len = recv_hdr.msg_len;
335                 msg->curchunk_hdrlen = hdrlen;
336
337                 /* we have already gotten an somt - don't bother parsing */
338                 if (recv_hdr.somt && msg->have_somt)
339                         return false;
340
341                 if (recv_hdr.somt) {
342                         memcpy(&msg->initial_hdr, &recv_hdr, sizeof(struct drm_dp_sideband_msg_hdr));
343                         msg->have_somt = true;
344                 }
345                 if (recv_hdr.eomt)
346                         msg->have_eomt = true;
347
348                 /* copy the bytes for the remainder of this header chunk */
349                 msg->curchunk_idx = min(msg->curchunk_len, (u8)(replybuflen - hdrlen));
350                 memcpy(&msg->chunk[0], replybuf + hdrlen, msg->curchunk_idx);
351         } else {
352                 memcpy(&msg->chunk[msg->curchunk_idx], replybuf, replybuflen);
353                 msg->curchunk_idx += replybuflen;
354         }
355
356         if (msg->curchunk_idx >= msg->curchunk_len) {
357                 /* do CRC */
358                 crc4 = drm_dp_msg_data_crc4(msg->chunk, msg->curchunk_len - 1);
359                 /* copy chunk into bigger msg */
360                 memcpy(&msg->msg[msg->curlen], msg->chunk, msg->curchunk_len - 1);
361                 msg->curlen += msg->curchunk_len - 1;
362         }
363         return true;
364 }
365
366 static bool drm_dp_sideband_parse_link_address(struct drm_dp_sideband_msg_rx *raw,
367                                                struct drm_dp_sideband_msg_reply_body *repmsg)
368 {
369         int idx = 1;
370         int i;
371         memcpy(repmsg->u.link_addr.guid, &raw->msg[idx], 16);
372         idx += 16;
373         repmsg->u.link_addr.nports = raw->msg[idx] & 0xf;
374         idx++;
375         if (idx > raw->curlen)
376                 goto fail_len;
377         for (i = 0; i < repmsg->u.link_addr.nports; i++) {
378                 if (raw->msg[idx] & 0x80)
379                         repmsg->u.link_addr.ports[i].input_port = 1;
380
381                 repmsg->u.link_addr.ports[i].peer_device_type = (raw->msg[idx] >> 4) & 0x7;
382                 repmsg->u.link_addr.ports[i].port_number = (raw->msg[idx] & 0xf);
383
384                 idx++;
385                 if (idx > raw->curlen)
386                         goto fail_len;
387                 repmsg->u.link_addr.ports[i].mcs = (raw->msg[idx] >> 7) & 0x1;
388                 repmsg->u.link_addr.ports[i].ddps = (raw->msg[idx] >> 6) & 0x1;
389                 if (repmsg->u.link_addr.ports[i].input_port == 0)
390                         repmsg->u.link_addr.ports[i].legacy_device_plug_status = (raw->msg[idx] >> 5) & 0x1;
391                 idx++;
392                 if (idx > raw->curlen)
393                         goto fail_len;
394                 if (repmsg->u.link_addr.ports[i].input_port == 0) {
395                         repmsg->u.link_addr.ports[i].dpcd_revision = (raw->msg[idx]);
396                         idx++;
397                         if (idx > raw->curlen)
398                                 goto fail_len;
399                         memcpy(repmsg->u.link_addr.ports[i].peer_guid, &raw->msg[idx], 16);
400                         idx += 16;
401                         if (idx > raw->curlen)
402                                 goto fail_len;
403                         repmsg->u.link_addr.ports[i].num_sdp_streams = (raw->msg[idx] >> 4) & 0xf;
404                         repmsg->u.link_addr.ports[i].num_sdp_stream_sinks = (raw->msg[idx] & 0xf);
405                         idx++;
406
407                 }
408                 if (idx > raw->curlen)
409                         goto fail_len;
410         }
411
412         return true;
413 fail_len:
414         DRM_DEBUG_KMS("link address reply parse length fail %d %d\n", idx, raw->curlen);
415         return false;
416 }
417
418 static bool drm_dp_sideband_parse_remote_dpcd_read(struct drm_dp_sideband_msg_rx *raw,
419                                                    struct drm_dp_sideband_msg_reply_body *repmsg)
420 {
421         int idx = 1;
422         repmsg->u.remote_dpcd_read_ack.port_number = raw->msg[idx] & 0xf;
423         idx++;
424         if (idx > raw->curlen)
425                 goto fail_len;
426         repmsg->u.remote_dpcd_read_ack.num_bytes = raw->msg[idx];
427         if (idx > raw->curlen)
428                 goto fail_len;
429
430         memcpy(repmsg->u.remote_dpcd_read_ack.bytes, &raw->msg[idx], repmsg->u.remote_dpcd_read_ack.num_bytes);
431         return true;
432 fail_len:
433         DRM_DEBUG_KMS("link address reply parse length fail %d %d\n", idx, raw->curlen);
434         return false;
435 }
436
437 static bool drm_dp_sideband_parse_remote_dpcd_write(struct drm_dp_sideband_msg_rx *raw,
438                                                       struct drm_dp_sideband_msg_reply_body *repmsg)
439 {
440         int idx = 1;
441         repmsg->u.remote_dpcd_write_ack.port_number = raw->msg[idx] & 0xf;
442         idx++;
443         if (idx > raw->curlen)
444                 goto fail_len;
445         return true;
446 fail_len:
447         DRM_DEBUG_KMS("parse length fail %d %d\n", idx, raw->curlen);
448         return false;
449 }
450
451 static bool drm_dp_sideband_parse_remote_i2c_read_ack(struct drm_dp_sideband_msg_rx *raw,
452                                                       struct drm_dp_sideband_msg_reply_body *repmsg)
453 {
454         int idx = 1;
455
456         repmsg->u.remote_i2c_read_ack.port_number = (raw->msg[idx] & 0xf);
457         idx++;
458         if (idx > raw->curlen)
459                 goto fail_len;
460         repmsg->u.remote_i2c_read_ack.num_bytes = raw->msg[idx];
461         idx++;
462         /* TODO check */
463         memcpy(repmsg->u.remote_i2c_read_ack.bytes, &raw->msg[idx], repmsg->u.remote_i2c_read_ack.num_bytes);
464         return true;
465 fail_len:
466         DRM_DEBUG_KMS("remote i2c reply parse length fail %d %d\n", idx, raw->curlen);
467         return false;
468 }
469
470 static bool drm_dp_sideband_parse_enum_path_resources_ack(struct drm_dp_sideband_msg_rx *raw,
471                                                           struct drm_dp_sideband_msg_reply_body *repmsg)
472 {
473         int idx = 1;
474         repmsg->u.path_resources.port_number = (raw->msg[idx] >> 4) & 0xf;
475         idx++;
476         if (idx > raw->curlen)
477                 goto fail_len;
478         repmsg->u.path_resources.full_payload_bw_number = (raw->msg[idx] << 8) | (raw->msg[idx+1]);
479         idx += 2;
480         if (idx > raw->curlen)
481                 goto fail_len;
482         repmsg->u.path_resources.avail_payload_bw_number = (raw->msg[idx] << 8) | (raw->msg[idx+1]);
483         idx += 2;
484         if (idx > raw->curlen)
485                 goto fail_len;
486         return true;
487 fail_len:
488         DRM_DEBUG_KMS("enum resource parse length fail %d %d\n", idx, raw->curlen);
489         return false;
490 }
491
492 static bool drm_dp_sideband_parse_allocate_payload_ack(struct drm_dp_sideband_msg_rx *raw,
493                                                           struct drm_dp_sideband_msg_reply_body *repmsg)
494 {
495         int idx = 1;
496         repmsg->u.allocate_payload.port_number = (raw->msg[idx] >> 4) & 0xf;
497         idx++;
498         if (idx > raw->curlen)
499                 goto fail_len;
500         repmsg->u.allocate_payload.vcpi = raw->msg[idx];
501         idx++;
502         if (idx > raw->curlen)
503                 goto fail_len;
504         repmsg->u.allocate_payload.allocated_pbn = (raw->msg[idx] << 8) | (raw->msg[idx+1]);
505         idx += 2;
506         if (idx > raw->curlen)
507                 goto fail_len;
508         return true;
509 fail_len:
510         DRM_DEBUG_KMS("allocate payload parse length fail %d %d\n", idx, raw->curlen);
511         return false;
512 }
513
514 static bool drm_dp_sideband_parse_query_payload_ack(struct drm_dp_sideband_msg_rx *raw,
515                                                     struct drm_dp_sideband_msg_reply_body *repmsg)
516 {
517         int idx = 1;
518         repmsg->u.query_payload.port_number = (raw->msg[idx] >> 4) & 0xf;
519         idx++;
520         if (idx > raw->curlen)
521                 goto fail_len;
522         repmsg->u.query_payload.allocated_pbn = (raw->msg[idx] << 8) | (raw->msg[idx + 1]);
523         idx += 2;
524         if (idx > raw->curlen)
525                 goto fail_len;
526         return true;
527 fail_len:
528         DRM_DEBUG_KMS("query payload parse length fail %d %d\n", idx, raw->curlen);
529         return false;
530 }
531
532 static bool drm_dp_sideband_parse_reply(struct drm_dp_sideband_msg_rx *raw,
533                                         struct drm_dp_sideband_msg_reply_body *msg)
534 {
535         memset(msg, 0, sizeof(*msg));
536         msg->reply_type = (raw->msg[0] & 0x80) >> 7;
537         msg->req_type = (raw->msg[0] & 0x7f);
538
539         if (msg->reply_type) {
540                 memcpy(msg->u.nak.guid, &raw->msg[1], 16);
541                 msg->u.nak.reason = raw->msg[17];
542                 msg->u.nak.nak_data = raw->msg[18];
543                 return false;
544         }
545
546         switch (msg->req_type) {
547         case DP_LINK_ADDRESS:
548                 return drm_dp_sideband_parse_link_address(raw, msg);
549         case DP_QUERY_PAYLOAD:
550                 return drm_dp_sideband_parse_query_payload_ack(raw, msg);
551         case DP_REMOTE_DPCD_READ:
552                 return drm_dp_sideband_parse_remote_dpcd_read(raw, msg);
553         case DP_REMOTE_DPCD_WRITE:
554                 return drm_dp_sideband_parse_remote_dpcd_write(raw, msg);
555         case DP_REMOTE_I2C_READ:
556                 return drm_dp_sideband_parse_remote_i2c_read_ack(raw, msg);
557         case DP_ENUM_PATH_RESOURCES:
558                 return drm_dp_sideband_parse_enum_path_resources_ack(raw, msg);
559         case DP_ALLOCATE_PAYLOAD:
560                 return drm_dp_sideband_parse_allocate_payload_ack(raw, msg);
561         default:
562                 DRM_ERROR("Got unknown reply 0x%02x\n", msg->req_type);
563                 return false;
564         }
565 }
566
567 static bool drm_dp_sideband_parse_connection_status_notify(struct drm_dp_sideband_msg_rx *raw,
568                                                            struct drm_dp_sideband_msg_req_body *msg)
569 {
570         int idx = 1;
571
572         msg->u.conn_stat.port_number = (raw->msg[idx] & 0xf0) >> 4;
573         idx++;
574         if (idx > raw->curlen)
575                 goto fail_len;
576
577         memcpy(msg->u.conn_stat.guid, &raw->msg[idx], 16);
578         idx += 16;
579         if (idx > raw->curlen)
580                 goto fail_len;
581
582         msg->u.conn_stat.legacy_device_plug_status = (raw->msg[idx] >> 6) & 0x1;
583         msg->u.conn_stat.displayport_device_plug_status = (raw->msg[idx] >> 5) & 0x1;
584         msg->u.conn_stat.message_capability_status = (raw->msg[idx] >> 4) & 0x1;
585         msg->u.conn_stat.input_port = (raw->msg[idx] >> 3) & 0x1;
586         msg->u.conn_stat.peer_device_type = (raw->msg[idx] & 0x7);
587         idx++;
588         return true;
589 fail_len:
590         DRM_DEBUG_KMS("connection status reply parse length fail %d %d\n", idx, raw->curlen);
591         return false;
592 }
593
594 static bool drm_dp_sideband_parse_resource_status_notify(struct drm_dp_sideband_msg_rx *raw,
595                                                            struct drm_dp_sideband_msg_req_body *msg)
596 {
597         int idx = 1;
598
599         msg->u.resource_stat.port_number = (raw->msg[idx] & 0xf0) >> 4;
600         idx++;
601         if (idx > raw->curlen)
602                 goto fail_len;
603
604         memcpy(msg->u.resource_stat.guid, &raw->msg[idx], 16);
605         idx += 16;
606         if (idx > raw->curlen)
607                 goto fail_len;
608
609         msg->u.resource_stat.available_pbn = (raw->msg[idx] << 8) | (raw->msg[idx + 1]);
610         idx++;
611         return true;
612 fail_len:
613         DRM_DEBUG_KMS("resource status reply parse length fail %d %d\n", idx, raw->curlen);
614         return false;
615 }
616
617 static bool drm_dp_sideband_parse_req(struct drm_dp_sideband_msg_rx *raw,
618                                       struct drm_dp_sideband_msg_req_body *msg)
619 {
620         memset(msg, 0, sizeof(*msg));
621         msg->req_type = (raw->msg[0] & 0x7f);
622
623         switch (msg->req_type) {
624         case DP_CONNECTION_STATUS_NOTIFY:
625                 return drm_dp_sideband_parse_connection_status_notify(raw, msg);
626         case DP_RESOURCE_STATUS_NOTIFY:
627                 return drm_dp_sideband_parse_resource_status_notify(raw, msg);
628         default:
629                 DRM_ERROR("Got unknown request 0x%02x\n", msg->req_type);
630                 return false;
631         }
632 }
633
634 static int build_dpcd_write(struct drm_dp_sideband_msg_tx *msg, u8 port_num, u32 offset, u8 num_bytes, u8 *bytes)
635 {
636         struct drm_dp_sideband_msg_req_body req;
637
638         req.req_type = DP_REMOTE_DPCD_WRITE;
639         req.u.dpcd_write.port_number = port_num;
640         req.u.dpcd_write.dpcd_address = offset;
641         req.u.dpcd_write.num_bytes = num_bytes;
642         req.u.dpcd_write.bytes = bytes;
643         drm_dp_encode_sideband_req(&req, msg);
644
645         return 0;
646 }
647
648 static int build_link_address(struct drm_dp_sideband_msg_tx *msg)
649 {
650         struct drm_dp_sideband_msg_req_body req;
651
652         req.req_type = DP_LINK_ADDRESS;
653         drm_dp_encode_sideband_req(&req, msg);
654         return 0;
655 }
656
657 static int build_enum_path_resources(struct drm_dp_sideband_msg_tx *msg, int port_num)
658 {
659         struct drm_dp_sideband_msg_req_body req;
660
661         req.req_type = DP_ENUM_PATH_RESOURCES;
662         req.u.port_num.port_number = port_num;
663         drm_dp_encode_sideband_req(&req, msg);
664         msg->path_msg = true;
665         return 0;
666 }
667
668 static int build_allocate_payload(struct drm_dp_sideband_msg_tx *msg, int port_num,
669                                   u8 vcpi, uint16_t pbn)
670 {
671         struct drm_dp_sideband_msg_req_body req;
672         memset(&req, 0, sizeof(req));
673         req.req_type = DP_ALLOCATE_PAYLOAD;
674         req.u.allocate_payload.port_number = port_num;
675         req.u.allocate_payload.vcpi = vcpi;
676         req.u.allocate_payload.pbn = pbn;
677         drm_dp_encode_sideband_req(&req, msg);
678         msg->path_msg = true;
679         return 0;
680 }
681
682 static int drm_dp_mst_assign_payload_id(struct drm_dp_mst_topology_mgr *mgr,
683                                         struct drm_dp_vcpi *vcpi)
684 {
685         int ret;
686
687         mutex_lock(&mgr->payload_lock);
688         ret = find_first_zero_bit(&mgr->payload_mask, mgr->max_payloads + 1);
689         if (ret > mgr->max_payloads) {
690                 ret = -EINVAL;
691                 DRM_DEBUG_KMS("out of payload ids %d\n", ret);
692                 goto out_unlock;
693         }
694
695         set_bit(ret, &mgr->payload_mask);
696         vcpi->vcpi = ret;
697         mgr->proposed_vcpis[ret - 1] = vcpi;
698 out_unlock:
699         mutex_unlock(&mgr->payload_lock);
700         return ret;
701 }
702
703 static void drm_dp_mst_put_payload_id(struct drm_dp_mst_topology_mgr *mgr,
704                                       int id)
705 {
706         if (id == 0)
707                 return;
708
709         mutex_lock(&mgr->payload_lock);
710         DRM_DEBUG_KMS("putting payload %d\n", id);
711         clear_bit(id, &mgr->payload_mask);
712         mgr->proposed_vcpis[id - 1] = NULL;
713         mutex_unlock(&mgr->payload_lock);
714 }
715
716 static bool check_txmsg_state(struct drm_dp_mst_topology_mgr *mgr,
717                               struct drm_dp_sideband_msg_tx *txmsg)
718 {
719         bool ret;
720         mutex_lock(&mgr->qlock);
721         ret = (txmsg->state == DRM_DP_SIDEBAND_TX_RX ||
722                txmsg->state == DRM_DP_SIDEBAND_TX_TIMEOUT);
723         mutex_unlock(&mgr->qlock);
724         return ret;
725 }
726
727 static int drm_dp_mst_wait_tx_reply(struct drm_dp_mst_branch *mstb,
728                                     struct drm_dp_sideband_msg_tx *txmsg)
729 {
730         struct drm_dp_mst_topology_mgr *mgr = mstb->mgr;
731         int ret;
732
733         ret = wait_event_timeout(mgr->tx_waitq,
734                                  check_txmsg_state(mgr, txmsg),
735                                  (4 * HZ));
736         mutex_lock(&mstb->mgr->qlock);
737         if (ret > 0) {
738                 if (txmsg->state == DRM_DP_SIDEBAND_TX_TIMEOUT) {
739                         ret = -EIO;
740                         goto out;
741                 }
742         } else {
743                 DRM_DEBUG_KMS("timedout msg send %p %d %d\n", txmsg, txmsg->state, txmsg->seqno);
744
745                 /* dump some state */
746                 ret = -EIO;
747
748                 /* remove from q */
749                 if (txmsg->state == DRM_DP_SIDEBAND_TX_QUEUED ||
750                     txmsg->state == DRM_DP_SIDEBAND_TX_START_SEND) {
751                         list_del(&txmsg->next);
752                 }
753
754                 if (txmsg->state == DRM_DP_SIDEBAND_TX_START_SEND ||
755                     txmsg->state == DRM_DP_SIDEBAND_TX_SENT) {
756                         mstb->tx_slots[txmsg->seqno] = NULL;
757                 }
758         }
759 out:
760         mutex_unlock(&mgr->qlock);
761
762         return ret;
763 }
764
765 static struct drm_dp_mst_branch *drm_dp_add_mst_branch_device(u8 lct, u8 *rad)
766 {
767         struct drm_dp_mst_branch *mstb;
768
769         mstb = kzalloc(sizeof(*mstb), GFP_KERNEL);
770         if (!mstb)
771                 return NULL;
772
773         mstb->lct = lct;
774         if (lct > 1)
775                 memcpy(mstb->rad, rad, lct / 2);
776         INIT_LIST_HEAD(&mstb->ports);
777         kref_init(&mstb->kref);
778         return mstb;
779 }
780
781 static void drm_dp_destroy_mst_branch_device(struct kref *kref)
782 {
783         struct drm_dp_mst_branch *mstb = container_of(kref, struct drm_dp_mst_branch, kref);
784         struct drm_dp_mst_port *port, *tmp;
785         bool wake_tx = false;
786
787         cancel_work_sync(&mstb->mgr->work);
788
789         /*
790          * destroy all ports - don't need lock
791          * as there are no more references to the mst branch
792          * device at this point.
793          */
794         list_for_each_entry_safe(port, tmp, &mstb->ports, next) {
795                 list_del(&port->next);
796                 drm_dp_put_port(port);
797         }
798
799         /* drop any tx slots msg */
800         mutex_lock(&mstb->mgr->qlock);
801         if (mstb->tx_slots[0]) {
802                 mstb->tx_slots[0]->state = DRM_DP_SIDEBAND_TX_TIMEOUT;
803                 mstb->tx_slots[0] = NULL;
804                 wake_tx = true;
805         }
806         if (mstb->tx_slots[1]) {
807                 mstb->tx_slots[1]->state = DRM_DP_SIDEBAND_TX_TIMEOUT;
808                 mstb->tx_slots[1] = NULL;
809                 wake_tx = true;
810         }
811         mutex_unlock(&mstb->mgr->qlock);
812
813         if (wake_tx)
814                 wake_up(&mstb->mgr->tx_waitq);
815         kfree(mstb);
816 }
817
818 static void drm_dp_put_mst_branch_device(struct drm_dp_mst_branch *mstb)
819 {
820         kref_put(&mstb->kref, drm_dp_destroy_mst_branch_device);
821 }
822
823
824 static void drm_dp_port_teardown_pdt(struct drm_dp_mst_port *port, int old_pdt)
825 {
826         switch (old_pdt) {
827         case DP_PEER_DEVICE_DP_LEGACY_CONV:
828         case DP_PEER_DEVICE_SST_SINK:
829                 /* remove i2c over sideband */
830                 drm_dp_mst_unregister_i2c_bus(&port->aux);
831                 break;
832         case DP_PEER_DEVICE_MST_BRANCHING:
833                 drm_dp_put_mst_branch_device(port->mstb);
834                 port->mstb = NULL;
835                 break;
836         }
837 }
838
839 static void drm_dp_destroy_port(struct kref *kref)
840 {
841         struct drm_dp_mst_port *port = container_of(kref, struct drm_dp_mst_port, kref);
842         struct drm_dp_mst_topology_mgr *mgr = port->mgr;
843         if (!port->input) {
844                 port->vcpi.num_slots = 0;
845                 if (port->connector)
846                         (*port->mgr->cbs->destroy_connector)(mgr, port->connector);
847                 drm_dp_port_teardown_pdt(port, port->pdt);
848
849                 if (!port->input && port->vcpi.vcpi > 0)
850                         drm_dp_mst_put_payload_id(mgr, port->vcpi.vcpi);
851         }
852         kfree(port);
853
854         (*mgr->cbs->hotplug)(mgr);
855 }
856
857 static void drm_dp_put_port(struct drm_dp_mst_port *port)
858 {
859         kref_put(&port->kref, drm_dp_destroy_port);
860 }
861
862 static struct drm_dp_mst_branch *drm_dp_mst_get_validated_mstb_ref_locked(struct drm_dp_mst_branch *mstb, struct drm_dp_mst_branch *to_find)
863 {
864         struct drm_dp_mst_port *port;
865         struct drm_dp_mst_branch *rmstb;
866         if (to_find == mstb) {
867                 kref_get(&mstb->kref);
868                 return mstb;
869         }
870         list_for_each_entry(port, &mstb->ports, next) {
871                 if (port->mstb) {
872                         rmstb = drm_dp_mst_get_validated_mstb_ref_locked(port->mstb, to_find);
873                         if (rmstb)
874                                 return rmstb;
875                 }
876         }
877         return NULL;
878 }
879
880 static struct drm_dp_mst_branch *drm_dp_get_validated_mstb_ref(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_branch *mstb)
881 {
882         struct drm_dp_mst_branch *rmstb = NULL;
883         mutex_lock(&mgr->lock);
884         if (mgr->mst_primary)
885                 rmstb = drm_dp_mst_get_validated_mstb_ref_locked(mgr->mst_primary, mstb);
886         mutex_unlock(&mgr->lock);
887         return rmstb;
888 }
889
890 static struct drm_dp_mst_port *drm_dp_mst_get_port_ref_locked(struct drm_dp_mst_branch *mstb, struct drm_dp_mst_port *to_find)
891 {
892         struct drm_dp_mst_port *port, *mport;
893
894         list_for_each_entry(port, &mstb->ports, next) {
895                 if (port == to_find) {
896                         kref_get(&port->kref);
897                         return port;
898                 }
899                 if (port->mstb) {
900                         mport = drm_dp_mst_get_port_ref_locked(port->mstb, to_find);
901                         if (mport)
902                                 return mport;
903                 }
904         }
905         return NULL;
906 }
907
908 static struct drm_dp_mst_port *drm_dp_get_validated_port_ref(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
909 {
910         struct drm_dp_mst_port *rport = NULL;
911         mutex_lock(&mgr->lock);
912         if (mgr->mst_primary)
913                 rport = drm_dp_mst_get_port_ref_locked(mgr->mst_primary, port);
914         mutex_unlock(&mgr->lock);
915         return rport;
916 }
917
918 static struct drm_dp_mst_port *drm_dp_get_port(struct drm_dp_mst_branch *mstb, u8 port_num)
919 {
920         struct drm_dp_mst_port *port;
921
922         list_for_each_entry(port, &mstb->ports, next) {
923                 if (port->port_num == port_num) {
924                         kref_get(&port->kref);
925                         return port;
926                 }
927         }
928
929         return NULL;
930 }
931
932 /*
933  * calculate a new RAD for this MST branch device
934  * if parent has an LCT of 2 then it has 1 nibble of RAD,
935  * if parent has an LCT of 3 then it has 2 nibbles of RAD,
936  */
937 static u8 drm_dp_calculate_rad(struct drm_dp_mst_port *port,
938                                  u8 *rad)
939 {
940         int lct = port->parent->lct;
941         int shift = 4;
942         int idx = lct / 2;
943         if (lct > 1) {
944                 memcpy(rad, port->parent->rad, idx);
945                 shift = (lct % 2) ? 4 : 0;
946         } else
947                 rad[0] = 0;
948
949         rad[idx] |= port->port_num << shift;
950         return lct + 1;
951 }
952
953 /*
954  * return sends link address for new mstb
955  */
956 static bool drm_dp_port_setup_pdt(struct drm_dp_mst_port *port)
957 {
958         int ret;
959         u8 rad[6], lct;
960         bool send_link = false;
961         switch (port->pdt) {
962         case DP_PEER_DEVICE_DP_LEGACY_CONV:
963         case DP_PEER_DEVICE_SST_SINK:
964                 /* add i2c over sideband */
965                 ret = drm_dp_mst_register_i2c_bus(&port->aux);
966                 break;
967         case DP_PEER_DEVICE_MST_BRANCHING:
968                 lct = drm_dp_calculate_rad(port, rad);
969
970                 port->mstb = drm_dp_add_mst_branch_device(lct, rad);
971                 port->mstb->mgr = port->mgr;
972                 port->mstb->port_parent = port;
973
974                 send_link = true;
975                 break;
976         }
977         return send_link;
978 }
979
980 static void drm_dp_check_port_guid(struct drm_dp_mst_branch *mstb,
981                                    struct drm_dp_mst_port *port)
982 {
983         int ret;
984         if (port->dpcd_rev >= 0x12) {
985                 port->guid_valid = drm_dp_validate_guid(mstb->mgr, port->guid);
986                 if (!port->guid_valid) {
987                         ret = drm_dp_send_dpcd_write(mstb->mgr,
988                                                      port,
989                                                      DP_GUID,
990                                                      16, port->guid);
991                         port->guid_valid = true;
992                 }
993         }
994 }
995
996 static void build_mst_prop_path(struct drm_dp_mst_port *port,
997                                 struct drm_dp_mst_branch *mstb,
998                                 char *proppath)
999 {
1000         int i;
1001         char temp[8];
1002         snprintf(proppath, 255, "mst:%d", mstb->mgr->conn_base_id);
1003         for (i = 0; i < (mstb->lct - 1); i++) {
1004                 int shift = (i % 2) ? 0 : 4;
1005                 int port_num = mstb->rad[i / 2] >> shift;
1006                 snprintf(temp, 8, "-%d", port_num);
1007                 strncat(proppath, temp, 255);
1008         }
1009         snprintf(temp, 8, "-%d", port->port_num);
1010         strncat(proppath, temp, 255);
1011 }
1012
1013 static void drm_dp_add_port(struct drm_dp_mst_branch *mstb,
1014                             struct device *dev,
1015                             struct drm_dp_link_addr_reply_port *port_msg)
1016 {
1017         struct drm_dp_mst_port *port;
1018         bool ret;
1019         bool created = false;
1020         int old_pdt = 0;
1021         int old_ddps = 0;
1022         port = drm_dp_get_port(mstb, port_msg->port_number);
1023         if (!port) {
1024                 port = kzalloc(sizeof(*port), GFP_KERNEL);
1025                 if (!port)
1026                         return;
1027                 kref_init(&port->kref);
1028                 port->parent = mstb;
1029                 port->port_num = port_msg->port_number;
1030                 port->mgr = mstb->mgr;
1031                 port->aux.name = "DPMST";
1032                 port->aux.dev = dev;
1033                 created = true;
1034         } else {
1035                 old_pdt = port->pdt;
1036                 old_ddps = port->ddps;
1037         }
1038
1039         port->pdt = port_msg->peer_device_type;
1040         port->input = port_msg->input_port;
1041         port->mcs = port_msg->mcs;
1042         port->ddps = port_msg->ddps;
1043         port->ldps = port_msg->legacy_device_plug_status;
1044         port->dpcd_rev = port_msg->dpcd_revision;
1045         port->num_sdp_streams = port_msg->num_sdp_streams;
1046         port->num_sdp_stream_sinks = port_msg->num_sdp_stream_sinks;
1047         memcpy(port->guid, port_msg->peer_guid, 16);
1048
1049         /* manage mstb port lists with mgr lock - take a reference
1050            for this list */
1051         if (created) {
1052                 mutex_lock(&mstb->mgr->lock);
1053                 kref_get(&port->kref);
1054                 list_add(&port->next, &mstb->ports);
1055                 mutex_unlock(&mstb->mgr->lock);
1056         }
1057
1058         if (old_ddps != port->ddps) {
1059                 if (port->ddps) {
1060                         drm_dp_check_port_guid(mstb, port);
1061                         if (!port->input)
1062                                 drm_dp_send_enum_path_resources(mstb->mgr, mstb, port);
1063                 } else {
1064                         port->guid_valid = false;
1065                         port->available_pbn = 0;
1066                         }
1067         }
1068
1069         if (old_pdt != port->pdt && !port->input) {
1070                 drm_dp_port_teardown_pdt(port, old_pdt);
1071
1072                 ret = drm_dp_port_setup_pdt(port);
1073                 if (ret == true) {
1074                         drm_dp_send_link_address(mstb->mgr, port->mstb);
1075                         port->mstb->link_address_sent = true;
1076                 }
1077         }
1078
1079         if (created && !port->input) {
1080                 char proppath[255];
1081                 build_mst_prop_path(port, mstb, proppath);
1082                 port->connector = (*mstb->mgr->cbs->add_connector)(mstb->mgr, port, proppath);
1083         }
1084
1085         /* put reference to this port */
1086         drm_dp_put_port(port);
1087 }
1088
1089 static void drm_dp_update_port(struct drm_dp_mst_branch *mstb,
1090                                struct drm_dp_connection_status_notify *conn_stat)
1091 {
1092         struct drm_dp_mst_port *port;
1093         int old_pdt;
1094         int old_ddps;
1095         bool dowork = false;
1096         port = drm_dp_get_port(mstb, conn_stat->port_number);
1097         if (!port)
1098                 return;
1099
1100         old_ddps = port->ddps;
1101         old_pdt = port->pdt;
1102         port->pdt = conn_stat->peer_device_type;
1103         port->mcs = conn_stat->message_capability_status;
1104         port->ldps = conn_stat->legacy_device_plug_status;
1105         port->ddps = conn_stat->displayport_device_plug_status;
1106
1107         if (old_ddps != port->ddps) {
1108                 if (port->ddps) {
1109                         drm_dp_check_port_guid(mstb, port);
1110                         dowork = true;
1111                 } else {
1112                         port->guid_valid = false;
1113                         port->available_pbn = 0;
1114                 }
1115         }
1116         if (old_pdt != port->pdt && !port->input) {
1117                 drm_dp_port_teardown_pdt(port, old_pdt);
1118
1119                 if (drm_dp_port_setup_pdt(port))
1120                         dowork = true;
1121         }
1122
1123         drm_dp_put_port(port);
1124         if (dowork)
1125                 queue_work(system_long_wq, &mstb->mgr->work);
1126
1127 }
1128
1129 static struct drm_dp_mst_branch *drm_dp_get_mst_branch_device(struct drm_dp_mst_topology_mgr *mgr,
1130                                                                u8 lct, u8 *rad)
1131 {
1132         struct drm_dp_mst_branch *mstb;
1133         struct drm_dp_mst_port *port;
1134         int i;
1135         /* find the port by iterating down */
1136         mstb = mgr->mst_primary;
1137
1138         for (i = 0; i < lct - 1; i++) {
1139                 int shift = (i % 2) ? 0 : 4;
1140                 int port_num = rad[i / 2] >> shift;
1141
1142                 list_for_each_entry(port, &mstb->ports, next) {
1143                         if (port->port_num == port_num) {
1144                                 if (!port->mstb) {
1145                                         DRM_ERROR("failed to lookup MSTB with lct %d, rad %02x\n", lct, rad[0]);
1146                                         return NULL;
1147                                 }
1148
1149                                 mstb = port->mstb;
1150                                 break;
1151                         }
1152                 }
1153         }
1154         kref_get(&mstb->kref);
1155         return mstb;
1156 }
1157
1158 static void drm_dp_check_and_send_link_address(struct drm_dp_mst_topology_mgr *mgr,
1159                                                struct drm_dp_mst_branch *mstb)
1160 {
1161         struct drm_dp_mst_port *port;
1162
1163         if (!mstb->link_address_sent) {
1164                 drm_dp_send_link_address(mgr, mstb);
1165                 mstb->link_address_sent = true;
1166         }
1167         list_for_each_entry(port, &mstb->ports, next) {
1168                 if (port->input)
1169                         continue;
1170
1171                 if (!port->ddps)
1172                         continue;
1173
1174                 if (!port->available_pbn)
1175                         drm_dp_send_enum_path_resources(mgr, mstb, port);
1176
1177                 if (port->mstb)
1178                         drm_dp_check_and_send_link_address(mgr, port->mstb);
1179         }
1180 }
1181
1182 static void drm_dp_mst_link_probe_work(struct work_struct *work)
1183 {
1184         struct drm_dp_mst_topology_mgr *mgr = container_of(work, struct drm_dp_mst_topology_mgr, work);
1185
1186         drm_dp_check_and_send_link_address(mgr, mgr->mst_primary);
1187
1188 }
1189
1190 static bool drm_dp_validate_guid(struct drm_dp_mst_topology_mgr *mgr,
1191                                  u8 *guid)
1192 {
1193         static u8 zero_guid[16];
1194
1195         if (!memcmp(guid, zero_guid, 16)) {
1196                 u64 salt = get_jiffies_64();
1197                 memcpy(&guid[0], &salt, sizeof(u64));
1198                 memcpy(&guid[8], &salt, sizeof(u64));
1199                 return false;
1200         }
1201         return true;
1202 }
1203
1204 #if 0
1205 static int build_dpcd_read(struct drm_dp_sideband_msg_tx *msg, u8 port_num, u32 offset, u8 num_bytes)
1206 {
1207         struct drm_dp_sideband_msg_req_body req;
1208
1209         req.req_type = DP_REMOTE_DPCD_READ;
1210         req.u.dpcd_read.port_number = port_num;
1211         req.u.dpcd_read.dpcd_address = offset;
1212         req.u.dpcd_read.num_bytes = num_bytes;
1213         drm_dp_encode_sideband_req(&req, msg);
1214
1215         return 0;
1216 }
1217 #endif
1218
1219 static int drm_dp_send_sideband_msg(struct drm_dp_mst_topology_mgr *mgr,
1220                                     bool up, u8 *msg, int len)
1221 {
1222         int ret;
1223         int regbase = up ? DP_SIDEBAND_MSG_UP_REP_BASE : DP_SIDEBAND_MSG_DOWN_REQ_BASE;
1224         int tosend, total, offset;
1225         int retries = 0;
1226
1227 retry:
1228         total = len;
1229         offset = 0;
1230         do {
1231                 tosend = min3(mgr->max_dpcd_transaction_bytes, 16, total);
1232
1233                 ret = drm_dp_dpcd_write(mgr->aux, regbase + offset,
1234                                         &msg[offset],
1235                                         tosend);
1236                 if (ret != tosend) {
1237                         if (ret == -EIO && retries < 5) {
1238                                 retries++;
1239                                 goto retry;
1240                         }
1241                         DRM_DEBUG_KMS("failed to dpcd write %d %d\n", tosend, ret);
1242                         WARN(1, "fail\n");
1243
1244                         return -EIO;
1245                 }
1246                 offset += tosend;
1247                 total -= tosend;
1248         } while (total > 0);
1249         return 0;
1250 }
1251
1252 static int set_hdr_from_dst_qlock(struct drm_dp_sideband_msg_hdr *hdr,
1253                                   struct drm_dp_sideband_msg_tx *txmsg)
1254 {
1255         struct drm_dp_mst_branch *mstb = txmsg->dst;
1256
1257         /* both msg slots are full */
1258         if (txmsg->seqno == -1) {
1259                 if (mstb->tx_slots[0] && mstb->tx_slots[1]) {
1260                         DRM_DEBUG_KMS("%s: failed to find slot\n", __func__);
1261                         return -EAGAIN;
1262                 }
1263                 if (mstb->tx_slots[0] == NULL && mstb->tx_slots[1] == NULL) {
1264                         txmsg->seqno = mstb->last_seqno;
1265                         mstb->last_seqno ^= 1;
1266                 } else if (mstb->tx_slots[0] == NULL)
1267                         txmsg->seqno = 0;
1268                 else
1269                         txmsg->seqno = 1;
1270                 mstb->tx_slots[txmsg->seqno] = txmsg;
1271         }
1272         hdr->broadcast = 0;
1273         hdr->path_msg = txmsg->path_msg;
1274         hdr->lct = mstb->lct;
1275         hdr->lcr = mstb->lct - 1;
1276         if (mstb->lct > 1)
1277                 memcpy(hdr->rad, mstb->rad, mstb->lct / 2);
1278         hdr->seqno = txmsg->seqno;
1279         return 0;
1280 }
1281 /*
1282  * process a single block of the next message in the sideband queue
1283  */
1284 static int process_single_tx_qlock(struct drm_dp_mst_topology_mgr *mgr,
1285                                    struct drm_dp_sideband_msg_tx *txmsg,
1286                                    bool up)
1287 {
1288         u8 chunk[48];
1289         struct drm_dp_sideband_msg_hdr hdr;
1290         int len, space, idx, tosend;
1291         int ret;
1292
1293         if (txmsg->state == DRM_DP_SIDEBAND_TX_QUEUED) {
1294                 txmsg->seqno = -1;
1295                 txmsg->state = DRM_DP_SIDEBAND_TX_START_SEND;
1296         }
1297
1298         /* make hdr from dst mst - for replies use seqno
1299            otherwise assign one */
1300         ret = set_hdr_from_dst_qlock(&hdr, txmsg);
1301         if (ret < 0)
1302                 return ret;
1303
1304         /* amount left to send in this message */
1305         len = txmsg->cur_len - txmsg->cur_offset;
1306
1307         /* 48 - sideband msg size - 1 byte for data CRC, x header bytes */
1308         space = 48 - 1 - drm_dp_calc_sb_hdr_size(&hdr);
1309
1310         tosend = min(len, space);
1311         if (len == txmsg->cur_len)
1312                 hdr.somt = 1;
1313         if (space >= len)
1314                 hdr.eomt = 1;
1315
1316
1317         hdr.msg_len = tosend + 1;
1318         drm_dp_encode_sideband_msg_hdr(&hdr, chunk, &idx);
1319         memcpy(&chunk[idx], &txmsg->msg[txmsg->cur_offset], tosend);
1320         /* add crc at end */
1321         drm_dp_crc_sideband_chunk_req(&chunk[idx], tosend);
1322         idx += tosend + 1;
1323
1324         ret = drm_dp_send_sideband_msg(mgr, up, chunk, idx);
1325         if (ret) {
1326                 DRM_DEBUG_KMS("sideband msg failed to send\n");
1327                 return ret;
1328         }
1329
1330         txmsg->cur_offset += tosend;
1331         if (txmsg->cur_offset == txmsg->cur_len) {
1332                 txmsg->state = DRM_DP_SIDEBAND_TX_SENT;
1333                 return 1;
1334         }
1335         return 0;
1336 }
1337
1338 /* must be called holding qlock */
1339 static void process_single_down_tx_qlock(struct drm_dp_mst_topology_mgr *mgr)
1340 {
1341         struct drm_dp_sideband_msg_tx *txmsg;
1342         int ret;
1343
1344         /* construct a chunk from the first msg in the tx_msg queue */
1345         if (list_empty(&mgr->tx_msg_downq)) {
1346                 mgr->tx_down_in_progress = false;
1347                 return;
1348         }
1349         mgr->tx_down_in_progress = true;
1350
1351         txmsg = list_first_entry(&mgr->tx_msg_downq, struct drm_dp_sideband_msg_tx, next);
1352         ret = process_single_tx_qlock(mgr, txmsg, false);
1353         if (ret == 1) {
1354                 /* txmsg is sent it should be in the slots now */
1355                 list_del(&txmsg->next);
1356         } else if (ret) {
1357                 DRM_DEBUG_KMS("failed to send msg in q %d\n", ret);
1358                 list_del(&txmsg->next);
1359                 if (txmsg->seqno != -1)
1360                         txmsg->dst->tx_slots[txmsg->seqno] = NULL;
1361                 txmsg->state = DRM_DP_SIDEBAND_TX_TIMEOUT;
1362                 wake_up(&mgr->tx_waitq);
1363         }
1364         if (list_empty(&mgr->tx_msg_downq)) {
1365                 mgr->tx_down_in_progress = false;
1366                 return;
1367         }
1368 }
1369
1370 /* called holding qlock */
1371 static void process_single_up_tx_qlock(struct drm_dp_mst_topology_mgr *mgr)
1372 {
1373         struct drm_dp_sideband_msg_tx *txmsg;
1374         int ret;
1375
1376         /* construct a chunk from the first msg in the tx_msg queue */
1377         if (list_empty(&mgr->tx_msg_upq)) {
1378                 mgr->tx_up_in_progress = false;
1379                 return;
1380         }
1381
1382         txmsg = list_first_entry(&mgr->tx_msg_upq, struct drm_dp_sideband_msg_tx, next);
1383         ret = process_single_tx_qlock(mgr, txmsg, true);
1384         if (ret == 1) {
1385                 /* up txmsgs aren't put in slots - so free after we send it */
1386                 list_del(&txmsg->next);
1387                 kfree(txmsg);
1388         } else if (ret)
1389                 DRM_DEBUG_KMS("failed to send msg in q %d\n", ret);
1390         mgr->tx_up_in_progress = true;
1391 }
1392
1393 static void drm_dp_queue_down_tx(struct drm_dp_mst_topology_mgr *mgr,
1394                                  struct drm_dp_sideband_msg_tx *txmsg)
1395 {
1396         mutex_lock(&mgr->qlock);
1397         list_add_tail(&txmsg->next, &mgr->tx_msg_downq);
1398         if (!mgr->tx_down_in_progress)
1399                 process_single_down_tx_qlock(mgr);
1400         mutex_unlock(&mgr->qlock);
1401 }
1402
1403 static int drm_dp_send_link_address(struct drm_dp_mst_topology_mgr *mgr,
1404                                     struct drm_dp_mst_branch *mstb)
1405 {
1406         int len;
1407         struct drm_dp_sideband_msg_tx *txmsg;
1408         int ret;
1409
1410         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
1411         if (!txmsg)
1412                 return -ENOMEM;
1413
1414         txmsg->dst = mstb;
1415         len = build_link_address(txmsg);
1416
1417         drm_dp_queue_down_tx(mgr, txmsg);
1418
1419         ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
1420         if (ret > 0) {
1421                 int i;
1422
1423                 if (txmsg->reply.reply_type == 1)
1424                         DRM_DEBUG_KMS("link address nak received\n");
1425                 else {
1426                         DRM_DEBUG_KMS("link address reply: %d\n", txmsg->reply.u.link_addr.nports);
1427                         for (i = 0; i < txmsg->reply.u.link_addr.nports; i++) {
1428                                 DRM_DEBUG_KMS("port %d: input %d, pdt: %d, pn: %d, dpcd_rev: %02x, mcs: %d, ddps: %d, ldps %d, sdp %d/%d\n", i,
1429                                        txmsg->reply.u.link_addr.ports[i].input_port,
1430                                        txmsg->reply.u.link_addr.ports[i].peer_device_type,
1431                                        txmsg->reply.u.link_addr.ports[i].port_number,
1432                                        txmsg->reply.u.link_addr.ports[i].dpcd_revision,
1433                                        txmsg->reply.u.link_addr.ports[i].mcs,
1434                                        txmsg->reply.u.link_addr.ports[i].ddps,
1435                                        txmsg->reply.u.link_addr.ports[i].legacy_device_plug_status,
1436                                        txmsg->reply.u.link_addr.ports[i].num_sdp_streams,
1437                                        txmsg->reply.u.link_addr.ports[i].num_sdp_stream_sinks);
1438                         }
1439                         for (i = 0; i < txmsg->reply.u.link_addr.nports; i++) {
1440                                 drm_dp_add_port(mstb, mgr->dev, &txmsg->reply.u.link_addr.ports[i]);
1441                         }
1442                         (*mgr->cbs->hotplug)(mgr);
1443                 }
1444         } else
1445                 DRM_DEBUG_KMS("link address failed %d\n", ret);
1446
1447         kfree(txmsg);
1448         return 0;
1449 }
1450
1451 static int drm_dp_send_enum_path_resources(struct drm_dp_mst_topology_mgr *mgr,
1452                                            struct drm_dp_mst_branch *mstb,
1453                                            struct drm_dp_mst_port *port)
1454 {
1455         int len;
1456         struct drm_dp_sideband_msg_tx *txmsg;
1457         int ret;
1458
1459         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
1460         if (!txmsg)
1461                 return -ENOMEM;
1462
1463         txmsg->dst = mstb;
1464         len = build_enum_path_resources(txmsg, port->port_num);
1465
1466         drm_dp_queue_down_tx(mgr, txmsg);
1467
1468         ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
1469         if (ret > 0) {
1470                 if (txmsg->reply.reply_type == 1)
1471                         DRM_DEBUG_KMS("enum path resources nak received\n");
1472                 else {
1473                         if (port->port_num != txmsg->reply.u.path_resources.port_number)
1474                                 DRM_ERROR("got incorrect port in response\n");
1475                         DRM_DEBUG_KMS("enum path resources %d: %d %d\n", txmsg->reply.u.path_resources.port_number, txmsg->reply.u.path_resources.full_payload_bw_number,
1476                                txmsg->reply.u.path_resources.avail_payload_bw_number);
1477                         port->available_pbn = txmsg->reply.u.path_resources.avail_payload_bw_number;
1478                 }
1479         }
1480
1481         kfree(txmsg);
1482         return 0;
1483 }
1484
1485 int drm_dp_payload_send_msg(struct drm_dp_mst_topology_mgr *mgr,
1486                             struct drm_dp_mst_port *port,
1487                             int id,
1488                             int pbn)
1489 {
1490         struct drm_dp_sideband_msg_tx *txmsg;
1491         struct drm_dp_mst_branch *mstb;
1492         int len, ret;
1493
1494         mstb = drm_dp_get_validated_mstb_ref(mgr, port->parent);
1495         if (!mstb)
1496                 return -EINVAL;
1497
1498         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
1499         if (!txmsg) {
1500                 ret = -ENOMEM;
1501                 goto fail_put;
1502         }
1503
1504         txmsg->dst = mstb;
1505         len = build_allocate_payload(txmsg, port->port_num,
1506                                      id,
1507                                      pbn);
1508
1509         drm_dp_queue_down_tx(mgr, txmsg);
1510
1511         ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
1512         if (ret > 0) {
1513                 if (txmsg->reply.reply_type == 1) {
1514                         ret = -EINVAL;
1515                 } else
1516                         ret = 0;
1517         }
1518         kfree(txmsg);
1519 fail_put:
1520         drm_dp_put_mst_branch_device(mstb);
1521         return ret;
1522 }
1523
1524 static int drm_dp_create_payload_step1(struct drm_dp_mst_topology_mgr *mgr,
1525                                        int id,
1526                                        struct drm_dp_payload *payload)
1527 {
1528         int ret;
1529
1530         ret = drm_dp_dpcd_write_payload(mgr, id, payload);
1531         if (ret < 0) {
1532                 payload->payload_state = 0;
1533                 return ret;
1534         }
1535         payload->payload_state = DP_PAYLOAD_LOCAL;
1536         return 0;
1537 }
1538
1539 int drm_dp_create_payload_step2(struct drm_dp_mst_topology_mgr *mgr,
1540                                 struct drm_dp_mst_port *port,
1541                                 int id,
1542                                 struct drm_dp_payload *payload)
1543 {
1544         int ret;
1545         ret = drm_dp_payload_send_msg(mgr, port, id, port->vcpi.pbn);
1546         if (ret < 0)
1547                 return ret;
1548         payload->payload_state = DP_PAYLOAD_REMOTE;
1549         return ret;
1550 }
1551
1552 int drm_dp_destroy_payload_step1(struct drm_dp_mst_topology_mgr *mgr,
1553                                  struct drm_dp_mst_port *port,
1554                                  int id,
1555                                  struct drm_dp_payload *payload)
1556 {
1557         DRM_DEBUG_KMS("\n");
1558         /* its okay for these to fail */
1559         if (port) {
1560                 drm_dp_payload_send_msg(mgr, port, id, 0);
1561         }
1562
1563         drm_dp_dpcd_write_payload(mgr, id, payload);
1564         payload->payload_state = 0;
1565         return 0;
1566 }
1567
1568 int drm_dp_destroy_payload_step2(struct drm_dp_mst_topology_mgr *mgr,
1569                                  int id,
1570                                  struct drm_dp_payload *payload)
1571 {
1572         payload->payload_state = 0;
1573         return 0;
1574 }
1575
1576 /**
1577  * drm_dp_update_payload_part1() - Execute payload update part 1
1578  * @mgr: manager to use.
1579  *
1580  * This iterates over all proposed virtual channels, and tries to
1581  * allocate space in the link for them. For 0->slots transitions,
1582  * this step just writes the VCPI to the MST device. For slots->0
1583  * transitions, this writes the updated VCPIs and removes the
1584  * remote VC payloads.
1585  *
1586  * after calling this the driver should generate ACT and payload
1587  * packets.
1588  */
1589 int drm_dp_update_payload_part1(struct drm_dp_mst_topology_mgr *mgr)
1590 {
1591         int i;
1592         int cur_slots = 1;
1593         struct drm_dp_payload req_payload;
1594         struct drm_dp_mst_port *port;
1595
1596         mutex_lock(&mgr->payload_lock);
1597         for (i = 0; i < mgr->max_payloads; i++) {
1598                 /* solve the current payloads - compare to the hw ones
1599                    - update the hw view */
1600                 req_payload.start_slot = cur_slots;
1601                 if (mgr->proposed_vcpis[i]) {
1602                         port = container_of(mgr->proposed_vcpis[i], struct drm_dp_mst_port, vcpi);
1603                         req_payload.num_slots = mgr->proposed_vcpis[i]->num_slots;
1604                 } else {
1605                         port = NULL;
1606                         req_payload.num_slots = 0;
1607                 }
1608                 /* work out what is required to happen with this payload */
1609                 if (mgr->payloads[i].start_slot != req_payload.start_slot ||
1610                     mgr->payloads[i].num_slots != req_payload.num_slots) {
1611
1612                         /* need to push an update for this payload */
1613                         if (req_payload.num_slots) {
1614                                 drm_dp_create_payload_step1(mgr, i + 1, &req_payload);
1615                                 mgr->payloads[i].num_slots = req_payload.num_slots;
1616                         } else if (mgr->payloads[i].num_slots) {
1617                                 mgr->payloads[i].num_slots = 0;
1618                                 drm_dp_destroy_payload_step1(mgr, port, i + 1, &mgr->payloads[i]);
1619                                 req_payload.payload_state = mgr->payloads[i].payload_state;
1620                         } else
1621                                 req_payload.payload_state = 0;
1622
1623                         mgr->payloads[i].start_slot = req_payload.start_slot;
1624                         mgr->payloads[i].payload_state = req_payload.payload_state;
1625                 }
1626                 cur_slots += req_payload.num_slots;
1627         }
1628         mutex_unlock(&mgr->payload_lock);
1629
1630         return 0;
1631 }
1632 EXPORT_SYMBOL(drm_dp_update_payload_part1);
1633
1634 /**
1635  * drm_dp_update_payload_part2() - Execute payload update part 2
1636  * @mgr: manager to use.
1637  *
1638  * This iterates over all proposed virtual channels, and tries to
1639  * allocate space in the link for them. For 0->slots transitions,
1640  * this step writes the remote VC payload commands. For slots->0
1641  * this just resets some internal state.
1642  */
1643 int drm_dp_update_payload_part2(struct drm_dp_mst_topology_mgr *mgr)
1644 {
1645         struct drm_dp_mst_port *port;
1646         int i;
1647         int ret;
1648         mutex_lock(&mgr->payload_lock);
1649         for (i = 0; i < mgr->max_payloads; i++) {
1650
1651                 if (!mgr->proposed_vcpis[i])
1652                         continue;
1653
1654                 port = container_of(mgr->proposed_vcpis[i], struct drm_dp_mst_port, vcpi);
1655
1656                 DRM_DEBUG_KMS("payload %d %d\n", i, mgr->payloads[i].payload_state);
1657                 if (mgr->payloads[i].payload_state == DP_PAYLOAD_LOCAL) {
1658                         ret = drm_dp_create_payload_step2(mgr, port, i + 1, &mgr->payloads[i]);
1659                 } else if (mgr->payloads[i].payload_state == DP_PAYLOAD_DELETE_LOCAL) {
1660                         ret = drm_dp_destroy_payload_step2(mgr, i + 1, &mgr->payloads[i]);
1661                 }
1662                 if (ret) {
1663                         mutex_unlock(&mgr->payload_lock);
1664                         return ret;
1665                 }
1666         }
1667         mutex_unlock(&mgr->payload_lock);
1668         return 0;
1669 }
1670 EXPORT_SYMBOL(drm_dp_update_payload_part2);
1671
1672 #if 0 /* unused as of yet */
1673 static int drm_dp_send_dpcd_read(struct drm_dp_mst_topology_mgr *mgr,
1674                                  struct drm_dp_mst_port *port,
1675                                  int offset, int size)
1676 {
1677         int len;
1678         struct drm_dp_sideband_msg_tx *txmsg;
1679
1680         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
1681         if (!txmsg)
1682                 return -ENOMEM;
1683
1684         len = build_dpcd_read(txmsg, port->port_num, 0, 8);
1685         txmsg->dst = port->parent;
1686
1687         drm_dp_queue_down_tx(mgr, txmsg);
1688
1689         return 0;
1690 }
1691 #endif
1692
1693 static int drm_dp_send_dpcd_write(struct drm_dp_mst_topology_mgr *mgr,
1694                                   struct drm_dp_mst_port *port,
1695                                   int offset, int size, u8 *bytes)
1696 {
1697         int len;
1698         int ret;
1699         struct drm_dp_sideband_msg_tx *txmsg;
1700         struct drm_dp_mst_branch *mstb;
1701
1702         mstb = drm_dp_get_validated_mstb_ref(mgr, port->parent);
1703         if (!mstb)
1704                 return -EINVAL;
1705
1706         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
1707         if (!txmsg) {
1708                 ret = -ENOMEM;
1709                 goto fail_put;
1710         }
1711
1712         len = build_dpcd_write(txmsg, port->port_num, offset, size, bytes);
1713         txmsg->dst = mstb;
1714
1715         drm_dp_queue_down_tx(mgr, txmsg);
1716
1717         ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
1718         if (ret > 0) {
1719                 if (txmsg->reply.reply_type == 1) {
1720                         ret = -EINVAL;
1721                 } else
1722                         ret = 0;
1723         }
1724         kfree(txmsg);
1725 fail_put:
1726         drm_dp_put_mst_branch_device(mstb);
1727         return ret;
1728 }
1729
1730 static int drm_dp_encode_up_ack_reply(struct drm_dp_sideband_msg_tx *msg, u8 req_type)
1731 {
1732         struct drm_dp_sideband_msg_reply_body reply;
1733
1734         reply.reply_type = 1;
1735         reply.req_type = req_type;
1736         drm_dp_encode_sideband_reply(&reply, msg);
1737         return 0;
1738 }
1739
1740 static int drm_dp_send_up_ack_reply(struct drm_dp_mst_topology_mgr *mgr,
1741                                     struct drm_dp_mst_branch *mstb,
1742                                     int req_type, int seqno, bool broadcast)
1743 {
1744         struct drm_dp_sideband_msg_tx *txmsg;
1745
1746         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
1747         if (!txmsg)
1748                 return -ENOMEM;
1749
1750         txmsg->dst = mstb;
1751         txmsg->seqno = seqno;
1752         drm_dp_encode_up_ack_reply(txmsg, req_type);
1753
1754         mutex_lock(&mgr->qlock);
1755         list_add_tail(&txmsg->next, &mgr->tx_msg_upq);
1756         if (!mgr->tx_up_in_progress) {
1757                 process_single_up_tx_qlock(mgr);
1758         }
1759         mutex_unlock(&mgr->qlock);
1760         return 0;
1761 }
1762
1763 static int drm_dp_get_vc_payload_bw(int dp_link_bw, int dp_link_count)
1764 {
1765         switch (dp_link_bw) {
1766         case DP_LINK_BW_1_62:
1767                 return 3 * dp_link_count;
1768         case DP_LINK_BW_2_7:
1769                 return 5 * dp_link_count;
1770         case DP_LINK_BW_5_4:
1771                 return 10 * dp_link_count;
1772         }
1773         return 0;
1774 }
1775
1776 /**
1777  * drm_dp_mst_topology_mgr_set_mst() - Set the MST state for a topology manager
1778  * @mgr: manager to set state for
1779  * @mst_state: true to enable MST on this connector - false to disable.
1780  *
1781  * This is called by the driver when it detects an MST capable device plugged
1782  * into a DP MST capable port, or when a DP MST capable device is unplugged.
1783  */
1784 int drm_dp_mst_topology_mgr_set_mst(struct drm_dp_mst_topology_mgr *mgr, bool mst_state)
1785 {
1786         int ret = 0;
1787         struct drm_dp_mst_branch *mstb = NULL;
1788
1789         mutex_lock(&mgr->lock);
1790         if (mst_state == mgr->mst_state)
1791                 goto out_unlock;
1792
1793         mgr->mst_state = mst_state;
1794         /* set the device into MST mode */
1795         if (mst_state) {
1796                 WARN_ON(mgr->mst_primary);
1797
1798                 /* get dpcd info */
1799                 ret = drm_dp_dpcd_read(mgr->aux, DP_DPCD_REV, mgr->dpcd, DP_RECEIVER_CAP_SIZE);
1800                 if (ret != DP_RECEIVER_CAP_SIZE) {
1801                         DRM_DEBUG_KMS("failed to read DPCD\n");
1802                         goto out_unlock;
1803                 }
1804
1805                 mgr->pbn_div = drm_dp_get_vc_payload_bw(mgr->dpcd[1], mgr->dpcd[2] & DP_MAX_LANE_COUNT_MASK);
1806                 mgr->total_pbn = 2560;
1807                 mgr->total_slots = DIV_ROUND_UP(mgr->total_pbn, mgr->pbn_div);
1808                 mgr->avail_slots = mgr->total_slots;
1809
1810                 /* add initial branch device at LCT 1 */
1811                 mstb = drm_dp_add_mst_branch_device(1, NULL);
1812                 if (mstb == NULL) {
1813                         ret = -ENOMEM;
1814                         goto out_unlock;
1815                 }
1816                 mstb->mgr = mgr;
1817
1818                 /* give this the main reference */
1819                 mgr->mst_primary = mstb;
1820                 kref_get(&mgr->mst_primary->kref);
1821
1822                 {
1823                         struct drm_dp_payload reset_pay;
1824                         reset_pay.start_slot = 0;
1825                         reset_pay.num_slots = 0x3f;
1826                         drm_dp_dpcd_write_payload(mgr, 0, &reset_pay);
1827                 }
1828
1829                 ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
1830                                          DP_MST_EN | DP_UP_REQ_EN | DP_UPSTREAM_IS_SRC);
1831                 if (ret < 0) {
1832                         goto out_unlock;
1833                 }
1834
1835
1836                 /* sort out guid */
1837                 ret = drm_dp_dpcd_read(mgr->aux, DP_GUID, mgr->guid, 16);
1838                 if (ret != 16) {
1839                         DRM_DEBUG_KMS("failed to read DP GUID %d\n", ret);
1840                         goto out_unlock;
1841                 }
1842
1843                 mgr->guid_valid = drm_dp_validate_guid(mgr, mgr->guid);
1844                 if (!mgr->guid_valid) {
1845                         ret = drm_dp_dpcd_write(mgr->aux, DP_GUID, mgr->guid, 16);
1846                         mgr->guid_valid = true;
1847                 }
1848
1849                 queue_work(system_long_wq, &mgr->work);
1850
1851                 ret = 0;
1852         } else {
1853                 /* disable MST on the device */
1854                 mstb = mgr->mst_primary;
1855                 mgr->mst_primary = NULL;
1856                 /* this can fail if the device is gone */
1857                 drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL, 0);
1858                 ret = 0;
1859                 memset(mgr->payloads, 0, mgr->max_payloads * sizeof(struct drm_dp_payload));
1860                 mgr->payload_mask = 0;
1861                 set_bit(0, &mgr->payload_mask);
1862         }
1863
1864 out_unlock:
1865         mutex_unlock(&mgr->lock);
1866         if (mstb)
1867                 drm_dp_put_mst_branch_device(mstb);
1868         return ret;
1869
1870 }
1871 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_set_mst);
1872
1873 /**
1874  * drm_dp_mst_topology_mgr_suspend() - suspend the MST manager
1875  * @mgr: manager to suspend
1876  *
1877  * This function tells the MST device that we can't handle UP messages
1878  * anymore. This should stop it from sending any since we are suspended.
1879  */
1880 void drm_dp_mst_topology_mgr_suspend(struct drm_dp_mst_topology_mgr *mgr)
1881 {
1882         mutex_lock(&mgr->lock);
1883         drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
1884                            DP_MST_EN | DP_UPSTREAM_IS_SRC);
1885         mutex_unlock(&mgr->lock);
1886 }
1887 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_suspend);
1888
1889 /**
1890  * drm_dp_mst_topology_mgr_resume() - resume the MST manager
1891  * @mgr: manager to resume
1892  *
1893  * This will fetch DPCD and see if the device is still there,
1894  * if it is, it will rewrite the MSTM control bits, and return.
1895  *
1896  * if the device fails this returns -1, and the driver should do
1897  * a full MST reprobe, in case we were undocked.
1898  */
1899 int drm_dp_mst_topology_mgr_resume(struct drm_dp_mst_topology_mgr *mgr)
1900 {
1901         int ret = 0;
1902
1903         mutex_lock(&mgr->lock);
1904
1905         if (mgr->mst_primary) {
1906                 int sret;
1907                 sret = drm_dp_dpcd_read(mgr->aux, DP_DPCD_REV, mgr->dpcd, DP_RECEIVER_CAP_SIZE);
1908                 if (sret != DP_RECEIVER_CAP_SIZE) {
1909                         DRM_DEBUG_KMS("dpcd read failed - undocked during suspend?\n");
1910                         ret = -1;
1911                         goto out_unlock;
1912                 }
1913
1914                 ret = drm_dp_dpcd_writeb(mgr->aux, DP_MSTM_CTRL,
1915                                          DP_MST_EN | DP_UP_REQ_EN | DP_UPSTREAM_IS_SRC);
1916                 if (ret < 0) {
1917                         DRM_DEBUG_KMS("mst write failed - undocked during suspend?\n");
1918                         ret = -1;
1919                         goto out_unlock;
1920                 }
1921                 ret = 0;
1922         } else
1923                 ret = -1;
1924
1925 out_unlock:
1926         mutex_unlock(&mgr->lock);
1927         return ret;
1928 }
1929 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_resume);
1930
1931 static void drm_dp_get_one_sb_msg(struct drm_dp_mst_topology_mgr *mgr, bool up)
1932 {
1933         int len;
1934         u8 replyblock[32];
1935         int replylen, origlen, curreply;
1936         int ret;
1937         struct drm_dp_sideband_msg_rx *msg;
1938         int basereg = up ? DP_SIDEBAND_MSG_UP_REQ_BASE : DP_SIDEBAND_MSG_DOWN_REP_BASE;
1939         msg = up ? &mgr->up_req_recv : &mgr->down_rep_recv;
1940
1941         len = min(mgr->max_dpcd_transaction_bytes, 16);
1942         ret = drm_dp_dpcd_read(mgr->aux, basereg,
1943                                replyblock, len);
1944         if (ret != len) {
1945                 DRM_DEBUG_KMS("failed to read DPCD down rep %d %d\n", len, ret);
1946                 return;
1947         }
1948         ret = drm_dp_sideband_msg_build(msg, replyblock, len, true);
1949         if (!ret) {
1950                 DRM_DEBUG_KMS("sideband msg build failed %d\n", replyblock[0]);
1951                 return;
1952         }
1953         replylen = msg->curchunk_len + msg->curchunk_hdrlen;
1954
1955         origlen = replylen;
1956         replylen -= len;
1957         curreply = len;
1958         while (replylen > 0) {
1959                 len = min3(replylen, mgr->max_dpcd_transaction_bytes, 16);
1960                 ret = drm_dp_dpcd_read(mgr->aux, basereg + curreply,
1961                                     replyblock, len);
1962                 if (ret != len) {
1963                         DRM_DEBUG_KMS("failed to read a chunk\n");
1964                 }
1965                 ret = drm_dp_sideband_msg_build(msg, replyblock, len, false);
1966                 if (ret == false)
1967                         DRM_DEBUG_KMS("failed to build sideband msg\n");
1968                 curreply += len;
1969                 replylen -= len;
1970         }
1971 }
1972
1973 static int drm_dp_mst_handle_down_rep(struct drm_dp_mst_topology_mgr *mgr)
1974 {
1975         int ret = 0;
1976
1977         drm_dp_get_one_sb_msg(mgr, false);
1978
1979         if (mgr->down_rep_recv.have_eomt) {
1980                 struct drm_dp_sideband_msg_tx *txmsg;
1981                 struct drm_dp_mst_branch *mstb;
1982                 int slot = -1;
1983                 mstb = drm_dp_get_mst_branch_device(mgr,
1984                                                     mgr->down_rep_recv.initial_hdr.lct,
1985                                                     mgr->down_rep_recv.initial_hdr.rad);
1986
1987                 if (!mstb) {
1988                         DRM_DEBUG_KMS("Got MST reply from unknown device %d\n", mgr->down_rep_recv.initial_hdr.lct);
1989                         memset(&mgr->down_rep_recv, 0, sizeof(struct drm_dp_sideband_msg_rx));
1990                         return 0;
1991                 }
1992
1993                 /* find the message */
1994                 slot = mgr->down_rep_recv.initial_hdr.seqno;
1995                 mutex_lock(&mgr->qlock);
1996                 txmsg = mstb->tx_slots[slot];
1997                 /* remove from slots */
1998                 mutex_unlock(&mgr->qlock);
1999
2000                 if (!txmsg) {
2001                         DRM_DEBUG_KMS("Got MST reply with no msg %p %d %d %02x %02x\n",
2002                                mstb,
2003                                mgr->down_rep_recv.initial_hdr.seqno,
2004                                mgr->down_rep_recv.initial_hdr.lct,
2005                                       mgr->down_rep_recv.initial_hdr.rad[0],
2006                                       mgr->down_rep_recv.msg[0]);
2007                         drm_dp_put_mst_branch_device(mstb);
2008                         memset(&mgr->down_rep_recv, 0, sizeof(struct drm_dp_sideband_msg_rx));
2009                         return 0;
2010                 }
2011
2012                 drm_dp_sideband_parse_reply(&mgr->down_rep_recv, &txmsg->reply);
2013                 if (txmsg->reply.reply_type == 1) {
2014                         DRM_DEBUG_KMS("Got NAK reply: req 0x%02x, reason 0x%02x, nak data 0x%02x\n", txmsg->reply.req_type, txmsg->reply.u.nak.reason, txmsg->reply.u.nak.nak_data);
2015                 }
2016
2017                 memset(&mgr->down_rep_recv, 0, sizeof(struct drm_dp_sideband_msg_rx));
2018                 drm_dp_put_mst_branch_device(mstb);
2019
2020                 mutex_lock(&mgr->qlock);
2021                 txmsg->state = DRM_DP_SIDEBAND_TX_RX;
2022                 mstb->tx_slots[slot] = NULL;
2023                 mutex_unlock(&mgr->qlock);
2024
2025                 wake_up(&mgr->tx_waitq);
2026         }
2027         return ret;
2028 }
2029
2030 static int drm_dp_mst_handle_up_req(struct drm_dp_mst_topology_mgr *mgr)
2031 {
2032         int ret = 0;
2033         drm_dp_get_one_sb_msg(mgr, true);
2034
2035         if (mgr->up_req_recv.have_eomt) {
2036                 struct drm_dp_sideband_msg_req_body msg;
2037                 struct drm_dp_mst_branch *mstb;
2038                 bool seqno;
2039                 mstb = drm_dp_get_mst_branch_device(mgr,
2040                                                     mgr->up_req_recv.initial_hdr.lct,
2041                                                     mgr->up_req_recv.initial_hdr.rad);
2042                 if (!mstb) {
2043                         DRM_DEBUG_KMS("Got MST reply from unknown device %d\n", mgr->up_req_recv.initial_hdr.lct);
2044                         memset(&mgr->up_req_recv, 0, sizeof(struct drm_dp_sideband_msg_rx));
2045                         return 0;
2046                 }
2047
2048                 seqno = mgr->up_req_recv.initial_hdr.seqno;
2049                 drm_dp_sideband_parse_req(&mgr->up_req_recv, &msg);
2050
2051                 if (msg.req_type == DP_CONNECTION_STATUS_NOTIFY) {
2052                         drm_dp_send_up_ack_reply(mgr, mstb, msg.req_type, seqno, false);
2053                         drm_dp_update_port(mstb, &msg.u.conn_stat);
2054                         DRM_DEBUG_KMS("Got CSN: pn: %d ldps:%d ddps: %d mcs: %d ip: %d pdt: %d\n", msg.u.conn_stat.port_number, msg.u.conn_stat.legacy_device_plug_status, msg.u.conn_stat.displayport_device_plug_status, msg.u.conn_stat.message_capability_status, msg.u.conn_stat.input_port, msg.u.conn_stat.peer_device_type);
2055                         (*mgr->cbs->hotplug)(mgr);
2056
2057                 } else if (msg.req_type == DP_RESOURCE_STATUS_NOTIFY) {
2058                         drm_dp_send_up_ack_reply(mgr, mstb, msg.req_type, seqno, false);
2059                         DRM_DEBUG_KMS("Got RSN: pn: %d avail_pbn %d\n", msg.u.resource_stat.port_number, msg.u.resource_stat.available_pbn);
2060                 }
2061
2062                 drm_dp_put_mst_branch_device(mstb);
2063                 memset(&mgr->up_req_recv, 0, sizeof(struct drm_dp_sideband_msg_rx));
2064         }
2065         return ret;
2066 }
2067
2068 /**
2069  * drm_dp_mst_hpd_irq() - MST hotplug IRQ notify
2070  * @mgr: manager to notify irq for.
2071  * @esi: 4 bytes from SINK_COUNT_ESI
2072  *
2073  * This should be called from the driver when it detects a short IRQ,
2074  * along with the value of the DEVICE_SERVICE_IRQ_VECTOR_ESI0. The
2075  * topology manager will process the sideband messages received as a result
2076  * of this.
2077  */
2078 int drm_dp_mst_hpd_irq(struct drm_dp_mst_topology_mgr *mgr, u8 *esi, bool *handled)
2079 {
2080         int ret = 0;
2081         int sc;
2082         *handled = false;
2083         sc = esi[0] & 0x3f;
2084
2085         if (sc != mgr->sink_count) {
2086                 mgr->sink_count = sc;
2087                 *handled = true;
2088         }
2089
2090         if (esi[1] & DP_DOWN_REP_MSG_RDY) {
2091                 ret = drm_dp_mst_handle_down_rep(mgr);
2092                 *handled = true;
2093         }
2094
2095         if (esi[1] & DP_UP_REQ_MSG_RDY) {
2096                 ret |= drm_dp_mst_handle_up_req(mgr);
2097                 *handled = true;
2098         }
2099
2100         drm_dp_mst_kick_tx(mgr);
2101         return ret;
2102 }
2103 EXPORT_SYMBOL(drm_dp_mst_hpd_irq);
2104
2105 /**
2106  * drm_dp_mst_detect_port() - get connection status for an MST port
2107  * @mgr: manager for this port
2108  * @port: unverified pointer to a port
2109  *
2110  * This returns the current connection state for a port. It validates the
2111  * port pointer still exists so the caller doesn't require a reference
2112  */
2113 enum drm_connector_status drm_dp_mst_detect_port(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
2114 {
2115         enum drm_connector_status status = connector_status_disconnected;
2116
2117         /* we need to search for the port in the mgr in case its gone */
2118         port = drm_dp_get_validated_port_ref(mgr, port);
2119         if (!port)
2120                 return connector_status_disconnected;
2121
2122         if (!port->ddps)
2123                 goto out;
2124
2125         switch (port->pdt) {
2126         case DP_PEER_DEVICE_NONE:
2127         case DP_PEER_DEVICE_MST_BRANCHING:
2128                 break;
2129
2130         case DP_PEER_DEVICE_SST_SINK:
2131                 status = connector_status_connected;
2132                 break;
2133         case DP_PEER_DEVICE_DP_LEGACY_CONV:
2134                 if (port->ldps)
2135                         status = connector_status_connected;
2136                 break;
2137         }
2138 out:
2139         drm_dp_put_port(port);
2140         return status;
2141 }
2142 EXPORT_SYMBOL(drm_dp_mst_detect_port);
2143
2144 /**
2145  * drm_dp_mst_get_edid() - get EDID for an MST port
2146  * @connector: toplevel connector to get EDID for
2147  * @mgr: manager for this port
2148  * @port: unverified pointer to a port.
2149  *
2150  * This returns an EDID for the port connected to a connector,
2151  * It validates the pointer still exists so the caller doesn't require a
2152  * reference.
2153  */
2154 struct edid *drm_dp_mst_get_edid(struct drm_connector *connector, struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
2155 {
2156         struct edid *edid = NULL;
2157
2158         /* we need to search for the port in the mgr in case its gone */
2159         port = drm_dp_get_validated_port_ref(mgr, port);
2160         if (!port)
2161                 return NULL;
2162
2163         edid = drm_get_edid(connector, &port->aux.ddc);
2164         drm_dp_put_port(port);
2165         return edid;
2166 }
2167 EXPORT_SYMBOL(drm_dp_mst_get_edid);
2168
2169 /**
2170  * drm_dp_find_vcpi_slots() - find slots for this PBN value
2171  * @mgr: manager to use
2172  * @pbn: payload bandwidth to convert into slots.
2173  */
2174 int drm_dp_find_vcpi_slots(struct drm_dp_mst_topology_mgr *mgr,
2175                            int pbn)
2176 {
2177         int num_slots;
2178
2179         num_slots = DIV_ROUND_UP(pbn, mgr->pbn_div);
2180
2181         if (num_slots > mgr->avail_slots)
2182                 return -ENOSPC;
2183         return num_slots;
2184 }
2185 EXPORT_SYMBOL(drm_dp_find_vcpi_slots);
2186
2187 static int drm_dp_init_vcpi(struct drm_dp_mst_topology_mgr *mgr,
2188                             struct drm_dp_vcpi *vcpi, int pbn)
2189 {
2190         int num_slots;
2191         int ret;
2192
2193         num_slots = DIV_ROUND_UP(pbn, mgr->pbn_div);
2194
2195         if (num_slots > mgr->avail_slots)
2196                 return -ENOSPC;
2197
2198         vcpi->pbn = pbn;
2199         vcpi->aligned_pbn = num_slots * mgr->pbn_div;
2200         vcpi->num_slots = num_slots;
2201
2202         ret = drm_dp_mst_assign_payload_id(mgr, vcpi);
2203         if (ret < 0)
2204                 return ret;
2205         return 0;
2206 }
2207
2208 /**
2209  * drm_dp_mst_allocate_vcpi() - Allocate a virtual channel
2210  * @mgr: manager for this port
2211  * @port: port to allocate a virtual channel for.
2212  * @pbn: payload bandwidth number to request
2213  * @slots: returned number of slots for this PBN.
2214  */
2215 bool drm_dp_mst_allocate_vcpi(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port, int pbn, int *slots)
2216 {
2217         int ret;
2218
2219         port = drm_dp_get_validated_port_ref(mgr, port);
2220         if (!port)
2221                 return false;
2222
2223         if (port->vcpi.vcpi > 0) {
2224                 DRM_DEBUG_KMS("payload: vcpi %d already allocated for pbn %d - requested pbn %d\n", port->vcpi.vcpi, port->vcpi.pbn, pbn);
2225                 if (pbn == port->vcpi.pbn) {
2226                         *slots = port->vcpi.num_slots;
2227                         return true;
2228                 }
2229         }
2230
2231         ret = drm_dp_init_vcpi(mgr, &port->vcpi, pbn);
2232         if (ret) {
2233                 DRM_DEBUG_KMS("failed to init vcpi %d %d %d\n", DIV_ROUND_UP(pbn, mgr->pbn_div), mgr->avail_slots, ret);
2234                 goto out;
2235         }
2236         DRM_DEBUG_KMS("initing vcpi for %d %d\n", pbn, port->vcpi.num_slots);
2237         *slots = port->vcpi.num_slots;
2238
2239         drm_dp_put_port(port);
2240         return true;
2241 out:
2242         return false;
2243 }
2244 EXPORT_SYMBOL(drm_dp_mst_allocate_vcpi);
2245
2246 /**
2247  * drm_dp_mst_reset_vcpi_slots() - Reset number of slots to 0 for VCPI
2248  * @mgr: manager for this port
2249  * @port: unverified pointer to a port.
2250  *
2251  * This just resets the number of slots for the ports VCPI for later programming.
2252  */
2253 void drm_dp_mst_reset_vcpi_slots(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
2254 {
2255         port = drm_dp_get_validated_port_ref(mgr, port);
2256         if (!port)
2257                 return;
2258         port->vcpi.num_slots = 0;
2259         drm_dp_put_port(port);
2260 }
2261 EXPORT_SYMBOL(drm_dp_mst_reset_vcpi_slots);
2262
2263 /**
2264  * drm_dp_mst_deallocate_vcpi() - deallocate a VCPI
2265  * @mgr: manager for this port
2266  * @port: unverified port to deallocate vcpi for
2267  */
2268 void drm_dp_mst_deallocate_vcpi(struct drm_dp_mst_topology_mgr *mgr, struct drm_dp_mst_port *port)
2269 {
2270         port = drm_dp_get_validated_port_ref(mgr, port);
2271         if (!port)
2272                 return;
2273
2274         drm_dp_mst_put_payload_id(mgr, port->vcpi.vcpi);
2275         port->vcpi.num_slots = 0;
2276         port->vcpi.pbn = 0;
2277         port->vcpi.aligned_pbn = 0;
2278         port->vcpi.vcpi = 0;
2279         drm_dp_put_port(port);
2280 }
2281 EXPORT_SYMBOL(drm_dp_mst_deallocate_vcpi);
2282
2283 static int drm_dp_dpcd_write_payload(struct drm_dp_mst_topology_mgr *mgr,
2284                                      int id, struct drm_dp_payload *payload)
2285 {
2286         u8 payload_alloc[3], status;
2287         int ret;
2288         int retries = 0;
2289
2290         drm_dp_dpcd_writeb(mgr->aux, DP_PAYLOAD_TABLE_UPDATE_STATUS,
2291                            DP_PAYLOAD_TABLE_UPDATED);
2292
2293         payload_alloc[0] = id;
2294         payload_alloc[1] = payload->start_slot;
2295         payload_alloc[2] = payload->num_slots;
2296
2297         ret = drm_dp_dpcd_write(mgr->aux, DP_PAYLOAD_ALLOCATE_SET, payload_alloc, 3);
2298         if (ret != 3) {
2299                 DRM_DEBUG_KMS("failed to write payload allocation %d\n", ret);
2300                 goto fail;
2301         }
2302
2303 retry:
2304         ret = drm_dp_dpcd_readb(mgr->aux, DP_PAYLOAD_TABLE_UPDATE_STATUS, &status);
2305         if (ret < 0) {
2306                 DRM_DEBUG_KMS("failed to read payload table status %d\n", ret);
2307                 goto fail;
2308         }
2309
2310         if (!(status & DP_PAYLOAD_TABLE_UPDATED)) {
2311                 retries++;
2312                 if (retries < 20) {
2313                         usleep_range(10000, 20000);
2314                         goto retry;
2315                 }
2316                 DRM_DEBUG_KMS("status not set after read payload table status %d\n", status);
2317                 ret = -EINVAL;
2318                 goto fail;
2319         }
2320         ret = 0;
2321 fail:
2322         return ret;
2323 }
2324
2325
2326 /**
2327  * drm_dp_check_act_status() - Check ACT handled status.
2328  * @mgr: manager to use
2329  *
2330  * Check the payload status bits in the DPCD for ACT handled completion.
2331  */
2332 int drm_dp_check_act_status(struct drm_dp_mst_topology_mgr *mgr)
2333 {
2334         u8 status;
2335         int ret;
2336         int count = 0;
2337
2338         do {
2339                 ret = drm_dp_dpcd_readb(mgr->aux, DP_PAYLOAD_TABLE_UPDATE_STATUS, &status);
2340
2341                 if (ret < 0) {
2342                         DRM_DEBUG_KMS("failed to read payload table status %d\n", ret);
2343                         goto fail;
2344                 }
2345
2346                 if (status & DP_PAYLOAD_ACT_HANDLED)
2347                         break;
2348                 count++;
2349                 udelay(100);
2350
2351         } while (count < 30);
2352
2353         if (!(status & DP_PAYLOAD_ACT_HANDLED)) {
2354                 DRM_DEBUG_KMS("failed to get ACT bit %d after %d retries\n", status, count);
2355                 ret = -EINVAL;
2356                 goto fail;
2357         }
2358         return 0;
2359 fail:
2360         return ret;
2361 }
2362 EXPORT_SYMBOL(drm_dp_check_act_status);
2363
2364 /**
2365  * drm_dp_calc_pbn_mode() - Calculate the PBN for a mode.
2366  * @clock: dot clock for the mode
2367  * @bpp: bpp for the mode.
2368  *
2369  * This uses the formula in the spec to calculate the PBN value for a mode.
2370  */
2371 int drm_dp_calc_pbn_mode(int clock, int bpp)
2372 {
2373         fixed20_12 pix_bw;
2374         fixed20_12 fbpp;
2375         fixed20_12 result;
2376         fixed20_12 margin, tmp;
2377         u32 res;
2378
2379         pix_bw.full = dfixed_const(clock);
2380         fbpp.full = dfixed_const(bpp);
2381         tmp.full = dfixed_const(8);
2382         fbpp.full = dfixed_div(fbpp, tmp);
2383
2384         result.full = dfixed_mul(pix_bw, fbpp);
2385         margin.full = dfixed_const(54);
2386         tmp.full = dfixed_const(64);
2387         margin.full = dfixed_div(margin, tmp);
2388         result.full = dfixed_div(result, margin);
2389
2390         margin.full = dfixed_const(1006);
2391         tmp.full = dfixed_const(1000);
2392         margin.full = dfixed_div(margin, tmp);
2393         result.full = dfixed_mul(result, margin);
2394
2395         result.full = dfixed_div(result, tmp);
2396         result.full = dfixed_ceil(result);
2397         res = dfixed_trunc(result);
2398         return res;
2399 }
2400 EXPORT_SYMBOL(drm_dp_calc_pbn_mode);
2401
2402 static int test_calc_pbn_mode(void)
2403 {
2404         int ret;
2405         ret = drm_dp_calc_pbn_mode(154000, 30);
2406         if (ret != 689)
2407                 return -EINVAL;
2408         ret = drm_dp_calc_pbn_mode(234000, 30);
2409         if (ret != 1047)
2410                 return -EINVAL;
2411         return 0;
2412 }
2413
2414 /* we want to kick the TX after we've ack the up/down IRQs. */
2415 static void drm_dp_mst_kick_tx(struct drm_dp_mst_topology_mgr *mgr)
2416 {
2417         queue_work(system_long_wq, &mgr->tx_work);
2418 }
2419
2420 static void drm_dp_mst_dump_mstb(struct seq_file *m,
2421                                  struct drm_dp_mst_branch *mstb)
2422 {
2423         struct drm_dp_mst_port *port;
2424         int tabs = mstb->lct;
2425         char prefix[10];
2426         int i;
2427
2428         for (i = 0; i < tabs; i++)
2429                 prefix[i] = '\t';
2430         prefix[i] = '\0';
2431
2432         seq_printf(m, "%smst: %p, %d\n", prefix, mstb, mstb->num_ports);
2433         list_for_each_entry(port, &mstb->ports, next) {
2434                 seq_printf(m, "%sport: %d: ddps: %d ldps: %d, %p, conn: %p\n", prefix, port->port_num, port->ddps, port->ldps, port, port->connector);
2435                 if (port->mstb)
2436                         drm_dp_mst_dump_mstb(m, port->mstb);
2437         }
2438 }
2439
2440 static bool dump_dp_payload_table(struct drm_dp_mst_topology_mgr *mgr,
2441                                   char *buf)
2442 {
2443         int ret;
2444         int i;
2445         for (i = 0; i < 4; i++) {
2446                 ret = drm_dp_dpcd_read(mgr->aux, DP_PAYLOAD_TABLE_UPDATE_STATUS + (i * 16), &buf[i * 16], 16);
2447                 if (ret != 16)
2448                         break;
2449         }
2450         if (i == 4)
2451                 return true;
2452         return false;
2453 }
2454
2455 /**
2456  * drm_dp_mst_dump_topology(): dump topology to seq file.
2457  * @m: seq_file to dump output to
2458  * @mgr: manager to dump current topology for.
2459  *
2460  * helper to dump MST topology to a seq file for debugfs.
2461  */
2462 void drm_dp_mst_dump_topology(struct seq_file *m,
2463                               struct drm_dp_mst_topology_mgr *mgr)
2464 {
2465         int i;
2466         struct drm_dp_mst_port *port;
2467         mutex_lock(&mgr->lock);
2468         if (mgr->mst_primary)
2469                 drm_dp_mst_dump_mstb(m, mgr->mst_primary);
2470
2471         /* dump VCPIs */
2472         mutex_unlock(&mgr->lock);
2473
2474         mutex_lock(&mgr->payload_lock);
2475         seq_printf(m, "vcpi: %lx\n", mgr->payload_mask);
2476
2477         for (i = 0; i < mgr->max_payloads; i++) {
2478                 if (mgr->proposed_vcpis[i]) {
2479                         port = container_of(mgr->proposed_vcpis[i], struct drm_dp_mst_port, vcpi);
2480                         seq_printf(m, "vcpi %d: %d %d %d\n", i, port->port_num, port->vcpi.vcpi, port->vcpi.num_slots);
2481                 } else
2482                         seq_printf(m, "vcpi %d:unsed\n", i);
2483         }
2484         for (i = 0; i < mgr->max_payloads; i++) {
2485                 seq_printf(m, "payload %d: %d, %d, %d\n",
2486                            i,
2487                            mgr->payloads[i].payload_state,
2488                            mgr->payloads[i].start_slot,
2489                            mgr->payloads[i].num_slots);
2490
2491
2492         }
2493         mutex_unlock(&mgr->payload_lock);
2494
2495         mutex_lock(&mgr->lock);
2496         if (mgr->mst_primary) {
2497                 u8 buf[64];
2498                 bool bret;
2499                 int ret;
2500                 ret = drm_dp_dpcd_read(mgr->aux, DP_DPCD_REV, buf, DP_RECEIVER_CAP_SIZE);
2501                 seq_printf(m, "dpcd: ");
2502                 for (i = 0; i < DP_RECEIVER_CAP_SIZE; i++)
2503                         seq_printf(m, "%02x ", buf[i]);
2504                 seq_printf(m, "\n");
2505                 ret = drm_dp_dpcd_read(mgr->aux, DP_FAUX_CAP, buf, 2);
2506                 seq_printf(m, "faux/mst: ");
2507                 for (i = 0; i < 2; i++)
2508                         seq_printf(m, "%02x ", buf[i]);
2509                 seq_printf(m, "\n");
2510                 ret = drm_dp_dpcd_read(mgr->aux, DP_MSTM_CTRL, buf, 1);
2511                 seq_printf(m, "mst ctrl: ");
2512                 for (i = 0; i < 1; i++)
2513                         seq_printf(m, "%02x ", buf[i]);
2514                 seq_printf(m, "\n");
2515
2516                 bret = dump_dp_payload_table(mgr, buf);
2517                 if (bret == true) {
2518                         seq_printf(m, "payload table: ");
2519                         for (i = 0; i < 63; i++)
2520                                 seq_printf(m, "%02x ", buf[i]);
2521                         seq_printf(m, "\n");
2522                 }
2523
2524         }
2525
2526         mutex_unlock(&mgr->lock);
2527
2528 }
2529 EXPORT_SYMBOL(drm_dp_mst_dump_topology);
2530
2531 static void drm_dp_tx_work(struct work_struct *work)
2532 {
2533         struct drm_dp_mst_topology_mgr *mgr = container_of(work, struct drm_dp_mst_topology_mgr, tx_work);
2534
2535         mutex_lock(&mgr->qlock);
2536         if (mgr->tx_down_in_progress)
2537                 process_single_down_tx_qlock(mgr);
2538         mutex_unlock(&mgr->qlock);
2539 }
2540
2541 /**
2542  * drm_dp_mst_topology_mgr_init - initialise a topology manager
2543  * @mgr: manager struct to initialise
2544  * @dev: device providing this structure - for i2c addition.
2545  * @aux: DP helper aux channel to talk to this device
2546  * @max_dpcd_transaction_bytes: hw specific DPCD transaction limit
2547  * @max_payloads: maximum number of payloads this GPU can source
2548  * @conn_base_id: the connector object ID the MST device is connected to.
2549  *
2550  * Return 0 for success, or negative error code on failure
2551  */
2552 int drm_dp_mst_topology_mgr_init(struct drm_dp_mst_topology_mgr *mgr,
2553                                  struct device *dev, struct drm_dp_aux *aux,
2554                                  int max_dpcd_transaction_bytes,
2555                                  int max_payloads, int conn_base_id)
2556 {
2557         mutex_init(&mgr->lock);
2558         mutex_init(&mgr->qlock);
2559         mutex_init(&mgr->payload_lock);
2560         INIT_LIST_HEAD(&mgr->tx_msg_upq);
2561         INIT_LIST_HEAD(&mgr->tx_msg_downq);
2562         INIT_WORK(&mgr->work, drm_dp_mst_link_probe_work);
2563         INIT_WORK(&mgr->tx_work, drm_dp_tx_work);
2564         init_waitqueue_head(&mgr->tx_waitq);
2565         mgr->dev = dev;
2566         mgr->aux = aux;
2567         mgr->max_dpcd_transaction_bytes = max_dpcd_transaction_bytes;
2568         mgr->max_payloads = max_payloads;
2569         mgr->conn_base_id = conn_base_id;
2570         mgr->payloads = kcalloc(max_payloads, sizeof(struct drm_dp_payload), GFP_KERNEL);
2571         if (!mgr->payloads)
2572                 return -ENOMEM;
2573         mgr->proposed_vcpis = kcalloc(max_payloads, sizeof(struct drm_dp_vcpi *), GFP_KERNEL);
2574         if (!mgr->proposed_vcpis)
2575                 return -ENOMEM;
2576         set_bit(0, &mgr->payload_mask);
2577         test_calc_pbn_mode();
2578         return 0;
2579 }
2580 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_init);
2581
2582 /**
2583  * drm_dp_mst_topology_mgr_destroy() - destroy topology manager.
2584  * @mgr: manager to destroy
2585  */
2586 void drm_dp_mst_topology_mgr_destroy(struct drm_dp_mst_topology_mgr *mgr)
2587 {
2588         mutex_lock(&mgr->payload_lock);
2589         kfree(mgr->payloads);
2590         mgr->payloads = NULL;
2591         kfree(mgr->proposed_vcpis);
2592         mgr->proposed_vcpis = NULL;
2593         mutex_unlock(&mgr->payload_lock);
2594         mgr->dev = NULL;
2595         mgr->aux = NULL;
2596 }
2597 EXPORT_SYMBOL(drm_dp_mst_topology_mgr_destroy);
2598
2599 /* I2C device */
2600 static int drm_dp_mst_i2c_xfer(struct i2c_adapter *adapter, struct i2c_msg *msgs,
2601                                int num)
2602 {
2603         struct drm_dp_aux *aux = adapter->algo_data;
2604         struct drm_dp_mst_port *port = container_of(aux, struct drm_dp_mst_port, aux);
2605         struct drm_dp_mst_branch *mstb;
2606         struct drm_dp_mst_topology_mgr *mgr = port->mgr;
2607         unsigned int i;
2608         bool reading = false;
2609         struct drm_dp_sideband_msg_req_body msg;
2610         struct drm_dp_sideband_msg_tx *txmsg = NULL;
2611         int ret;
2612
2613         mstb = drm_dp_get_validated_mstb_ref(mgr, port->parent);
2614         if (!mstb)
2615                 return -EREMOTEIO;
2616
2617         /* construct i2c msg */
2618         /* see if last msg is a read */
2619         if (msgs[num - 1].flags & I2C_M_RD)
2620                 reading = true;
2621
2622         if (!reading) {
2623                 DRM_DEBUG_KMS("Unsupported I2C transaction for MST device\n");
2624                 ret = -EIO;
2625                 goto out;
2626         }
2627
2628         msg.req_type = DP_REMOTE_I2C_READ;
2629         msg.u.i2c_read.num_transactions = num - 1;
2630         msg.u.i2c_read.port_number = port->port_num;
2631         for (i = 0; i < num - 1; i++) {
2632                 msg.u.i2c_read.transactions[i].i2c_dev_id = msgs[i].addr;
2633                 msg.u.i2c_read.transactions[i].num_bytes = msgs[i].len;
2634                 msg.u.i2c_read.transactions[i].bytes = msgs[i].buf;
2635         }
2636         msg.u.i2c_read.read_i2c_device_id = msgs[num - 1].addr;
2637         msg.u.i2c_read.num_bytes_read = msgs[num - 1].len;
2638
2639         txmsg = kzalloc(sizeof(*txmsg), GFP_KERNEL);
2640         if (!txmsg) {
2641                 ret = -ENOMEM;
2642                 goto out;
2643         }
2644
2645         txmsg->dst = mstb;
2646         drm_dp_encode_sideband_req(&msg, txmsg);
2647
2648         drm_dp_queue_down_tx(mgr, txmsg);
2649
2650         ret = drm_dp_mst_wait_tx_reply(mstb, txmsg);
2651         if (ret > 0) {
2652
2653                 if (txmsg->reply.reply_type == 1) { /* got a NAK back */
2654                         ret = -EREMOTEIO;
2655                         goto out;
2656                 }
2657                 if (txmsg->reply.u.remote_i2c_read_ack.num_bytes != msgs[num - 1].len) {
2658                         ret = -EIO;
2659                         goto out;
2660                 }
2661                 memcpy(msgs[num - 1].buf, txmsg->reply.u.remote_i2c_read_ack.bytes, msgs[num - 1].len);
2662                 ret = num;
2663         }
2664 out:
2665         kfree(txmsg);
2666         drm_dp_put_mst_branch_device(mstb);
2667         return ret;
2668 }
2669
2670 static u32 drm_dp_mst_i2c_functionality(struct i2c_adapter *adapter)
2671 {
2672         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
2673                I2C_FUNC_SMBUS_READ_BLOCK_DATA |
2674                I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
2675                I2C_FUNC_10BIT_ADDR;
2676 }
2677
2678 static const struct i2c_algorithm drm_dp_mst_i2c_algo = {
2679         .functionality = drm_dp_mst_i2c_functionality,
2680         .master_xfer = drm_dp_mst_i2c_xfer,
2681 };
2682
2683 /**
2684  * drm_dp_mst_register_i2c_bus() - register an I2C adapter for I2C-over-AUX
2685  * @aux: DisplayPort AUX channel
2686  *
2687  * Returns 0 on success or a negative error code on failure.
2688  */
2689 static int drm_dp_mst_register_i2c_bus(struct drm_dp_aux *aux)
2690 {
2691         aux->ddc.algo = &drm_dp_mst_i2c_algo;
2692         aux->ddc.algo_data = aux;
2693         aux->ddc.retries = 3;
2694
2695         aux->ddc.class = I2C_CLASS_DDC;
2696         aux->ddc.owner = THIS_MODULE;
2697         aux->ddc.dev.parent = aux->dev;
2698         aux->ddc.dev.of_node = aux->dev->of_node;
2699
2700         strlcpy(aux->ddc.name, aux->name ? aux->name : dev_name(aux->dev),
2701                 sizeof(aux->ddc.name));
2702
2703         return i2c_add_adapter(&aux->ddc);
2704 }
2705
2706 /**
2707  * drm_dp_mst_unregister_i2c_bus() - unregister an I2C-over-AUX adapter
2708  * @aux: DisplayPort AUX channel
2709  */
2710 static void drm_dp_mst_unregister_i2c_bus(struct drm_dp_aux *aux)
2711 {
2712         i2c_del_adapter(&aux->ddc);
2713 }