drm/i915: Update to Linux 4.7.10
[dragonfly.git] / sys / dev / drm / drm_dp_helper.c
1 /*
2  * Copyright © 2009 Keith Packard
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/module.h>
25 #include <linux/delay.h>
26 #include <linux/errno.h>
27 #include <linux/sched.h>
28 #include <linux/i2c.h>
29 #include <drm/drm_dp_helper.h>
30 #include <drm/drm_dp_aux_dev.h>
31 #include <drm/drmP.h>
32
33 /**
34  * DOC: dp helpers
35  *
36  * These functions contain some common logic and helpers at various abstraction
37  * levels to deal with Display Port sink devices and related things like DP aux
38  * channel transfers, EDID reading over DP aux channels, decoding certain DPCD
39  * blocks, ...
40  */
41
42 /* Helpers for DP link training */
43 static u8 dp_link_status(const u8 link_status[DP_LINK_STATUS_SIZE], int r)
44 {
45         return link_status[r - DP_LANE0_1_STATUS];
46 }
47
48 static u8 dp_get_lane_status(const u8 link_status[DP_LINK_STATUS_SIZE],
49                              int lane)
50 {
51         int i = DP_LANE0_1_STATUS + (lane >> 1);
52         int s = (lane & 1) * 4;
53         u8 l = dp_link_status(link_status, i);
54         return (l >> s) & 0xf;
55 }
56
57 bool drm_dp_channel_eq_ok(const u8 link_status[DP_LINK_STATUS_SIZE],
58                           int lane_count)
59 {
60         u8 lane_align;
61         u8 lane_status;
62         int lane;
63
64         lane_align = dp_link_status(link_status,
65                                     DP_LANE_ALIGN_STATUS_UPDATED);
66         if ((lane_align & DP_INTERLANE_ALIGN_DONE) == 0)
67                 return false;
68         for (lane = 0; lane < lane_count; lane++) {
69                 lane_status = dp_get_lane_status(link_status, lane);
70                 if ((lane_status & DP_CHANNEL_EQ_BITS) != DP_CHANNEL_EQ_BITS)
71                         return false;
72         }
73         return true;
74 }
75 EXPORT_SYMBOL(drm_dp_channel_eq_ok);
76
77 bool drm_dp_clock_recovery_ok(const u8 link_status[DP_LINK_STATUS_SIZE],
78                               int lane_count)
79 {
80         int lane;
81         u8 lane_status;
82
83         for (lane = 0; lane < lane_count; lane++) {
84                 lane_status = dp_get_lane_status(link_status, lane);
85                 if ((lane_status & DP_LANE_CR_DONE) == 0)
86                         return false;
87         }
88         return true;
89 }
90 EXPORT_SYMBOL(drm_dp_clock_recovery_ok);
91
92 u8 drm_dp_get_adjust_request_voltage(const u8 link_status[DP_LINK_STATUS_SIZE],
93                                      int lane)
94 {
95         int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
96         int s = ((lane & 1) ?
97                  DP_ADJUST_VOLTAGE_SWING_LANE1_SHIFT :
98                  DP_ADJUST_VOLTAGE_SWING_LANE0_SHIFT);
99         u8 l = dp_link_status(link_status, i);
100
101         return ((l >> s) & 0x3) << DP_TRAIN_VOLTAGE_SWING_SHIFT;
102 }
103 EXPORT_SYMBOL(drm_dp_get_adjust_request_voltage);
104
105 u8 drm_dp_get_adjust_request_pre_emphasis(const u8 link_status[DP_LINK_STATUS_SIZE],
106                                           int lane)
107 {
108         int i = DP_ADJUST_REQUEST_LANE0_1 + (lane >> 1);
109         int s = ((lane & 1) ?
110                  DP_ADJUST_PRE_EMPHASIS_LANE1_SHIFT :
111                  DP_ADJUST_PRE_EMPHASIS_LANE0_SHIFT);
112         u8 l = dp_link_status(link_status, i);
113
114         return ((l >> s) & 0x3) << DP_TRAIN_PRE_EMPHASIS_SHIFT;
115 }
116 EXPORT_SYMBOL(drm_dp_get_adjust_request_pre_emphasis);
117
118 void drm_dp_link_train_clock_recovery_delay(const u8 dpcd[DP_RECEIVER_CAP_SIZE]) {
119         if (dpcd[DP_TRAINING_AUX_RD_INTERVAL] == 0)
120                 udelay(100);
121         else
122                 mdelay(dpcd[DP_TRAINING_AUX_RD_INTERVAL] * 4);
123 }
124 EXPORT_SYMBOL(drm_dp_link_train_clock_recovery_delay);
125
126 void drm_dp_link_train_channel_eq_delay(const u8 dpcd[DP_RECEIVER_CAP_SIZE]) {
127         if (dpcd[DP_TRAINING_AUX_RD_INTERVAL] == 0)
128                 udelay(400);
129         else
130                 mdelay(dpcd[DP_TRAINING_AUX_RD_INTERVAL] * 4);
131 }
132 EXPORT_SYMBOL(drm_dp_link_train_channel_eq_delay);
133
134 u8 drm_dp_link_rate_to_bw_code(int link_rate)
135 {
136         switch (link_rate) {
137         case 162000:
138         default:
139                 return DP_LINK_BW_1_62;
140         case 270000:
141                 return DP_LINK_BW_2_7;
142         case 540000:
143                 return DP_LINK_BW_5_4;
144         }
145 }
146 EXPORT_SYMBOL(drm_dp_link_rate_to_bw_code);
147
148 int drm_dp_bw_code_to_link_rate(u8 link_bw)
149 {
150         switch (link_bw) {
151         case DP_LINK_BW_1_62:
152         default:
153                 return 162000;
154         case DP_LINK_BW_2_7:
155                 return 270000;
156         case DP_LINK_BW_5_4:
157                 return 540000;
158         }
159 }
160 EXPORT_SYMBOL(drm_dp_bw_code_to_link_rate);
161
162 #define AUX_RETRY_INTERVAL 500 /* us */
163
164 /**
165  * DOC: dp helpers
166  *
167  * The DisplayPort AUX channel is an abstraction to allow generic, driver-
168  * independent access to AUX functionality. Drivers can take advantage of
169  * this by filling in the fields of the drm_dp_aux structure.
170  *
171  * Transactions are described using a hardware-independent drm_dp_aux_msg
172  * structure, which is passed into a driver's .transfer() implementation.
173  * Both native and I2C-over-AUX transactions are supported.
174  */
175
176 static int drm_dp_dpcd_access(struct drm_dp_aux *aux, u8 request,
177                               unsigned int offset, void *buffer, size_t size)
178 {
179         struct drm_dp_aux_msg msg;
180         unsigned int retry, native_reply;
181         int err = 0, ret = 0;
182
183         memset(&msg, 0, sizeof(msg));
184         msg.address = offset;
185         msg.request = request;
186         msg.buffer = buffer;
187         msg.size = size;
188
189         mutex_lock(&aux->hw_mutex);
190
191         /*
192          * The specification doesn't give any recommendation on how often to
193          * retry native transactions. We used to retry 7 times like for
194          * aux i2c transactions but real world devices this wasn't
195          * sufficient, bump to 32 which makes Dell 4k monitors happier.
196          */
197         for (retry = 0; retry < 32; retry++) {
198                 if (ret != 0 && ret != -ETIMEDOUT) {
199                         usleep_range(AUX_RETRY_INTERVAL,
200                                      AUX_RETRY_INTERVAL + 100);
201                 }
202
203                 ret = aux->transfer(aux, &msg);
204
205                 if (ret > 0) {
206                         native_reply = msg.reply & DP_AUX_NATIVE_REPLY_MASK;
207                         if (native_reply == DP_AUX_NATIVE_REPLY_ACK) {
208                                 if (ret == size)
209                                         goto unlock;
210
211                                 ret = -EPROTO;
212                         } else
213                                 ret = -EIO;
214                 }
215
216                 /*
217                  * We want the error we return to be the error we received on
218                  * the first transaction, since we may get a different error the
219                  * next time we retry
220                  */
221                 if (!err)
222                         err = ret;
223         }
224
225         DRM_DEBUG_KMS("too many retries, giving up\n");
226         ret = err;
227
228 unlock:
229         mutex_unlock(&aux->hw_mutex);
230         return ret;
231 }
232
233 /**
234  * drm_dp_dpcd_read() - read a series of bytes from the DPCD
235  * @aux: DisplayPort AUX channel
236  * @offset: address of the (first) register to read
237  * @buffer: buffer to store the register values
238  * @size: number of bytes in @buffer
239  *
240  * Returns the number of bytes transferred on success, or a negative error
241  * code on failure. -EIO is returned if the request was NAKed by the sink or
242  * if the retry count was exceeded. If not all bytes were transferred, this
243  * function returns -EPROTO. Errors from the underlying AUX channel transfer
244  * function, with the exception of -EBUSY (which causes the transaction to
245  * be retried), are propagated to the caller.
246  */
247 ssize_t drm_dp_dpcd_read(struct drm_dp_aux *aux, unsigned int offset,
248                          void *buffer, size_t size)
249 {
250         int ret;
251
252         /*
253          * HP ZR24w corrupts the first DPCD access after entering power save
254          * mode. Eg. on a read, the entire buffer will be filled with the same
255          * byte. Do a throw away read to avoid corrupting anything we care
256          * about. Afterwards things will work correctly until the monitor
257          * gets woken up and subsequently re-enters power save mode.
258          *
259          * The user pressing any button on the monitor is enough to wake it
260          * up, so there is no particularly good place to do the workaround.
261          * We just have to do it before any DPCD access and hope that the
262          * monitor doesn't power down exactly after the throw away read.
263          */
264         ret = drm_dp_dpcd_access(aux, DP_AUX_NATIVE_READ, DP_DPCD_REV, buffer,
265                                  1);
266         if (ret != 1)
267                 return ret;
268
269         return drm_dp_dpcd_access(aux, DP_AUX_NATIVE_READ, offset, buffer,
270                                   size);
271 }
272 EXPORT_SYMBOL(drm_dp_dpcd_read);
273
274 /**
275  * drm_dp_dpcd_write() - write a series of bytes to the DPCD
276  * @aux: DisplayPort AUX channel
277  * @offset: address of the (first) register to write
278  * @buffer: buffer containing the values to write
279  * @size: number of bytes in @buffer
280  *
281  * Returns the number of bytes transferred on success, or a negative error
282  * code on failure. -EIO is returned if the request was NAKed by the sink or
283  * if the retry count was exceeded. If not all bytes were transferred, this
284  * function returns -EPROTO. Errors from the underlying AUX channel transfer
285  * function, with the exception of -EBUSY (which causes the transaction to
286  * be retried), are propagated to the caller.
287  */
288 ssize_t drm_dp_dpcd_write(struct drm_dp_aux *aux, unsigned int offset,
289                           void *buffer, size_t size)
290 {
291         return drm_dp_dpcd_access(aux, DP_AUX_NATIVE_WRITE, offset, buffer,
292                                   size);
293 }
294 EXPORT_SYMBOL(drm_dp_dpcd_write);
295
296 /**
297  * drm_dp_dpcd_read_link_status() - read DPCD link status (bytes 0x202-0x207)
298  * @aux: DisplayPort AUX channel
299  * @status: buffer to store the link status in (must be at least 6 bytes)
300  *
301  * Returns the number of bytes transferred on success or a negative error
302  * code on failure.
303  */
304 int drm_dp_dpcd_read_link_status(struct drm_dp_aux *aux,
305                                  u8 status[DP_LINK_STATUS_SIZE])
306 {
307         return drm_dp_dpcd_read(aux, DP_LANE0_1_STATUS, status,
308                                 DP_LINK_STATUS_SIZE);
309 }
310 EXPORT_SYMBOL(drm_dp_dpcd_read_link_status);
311
312 /**
313  * drm_dp_link_probe() - probe a DisplayPort link for capabilities
314  * @aux: DisplayPort AUX channel
315  * @link: pointer to structure in which to return link capabilities
316  *
317  * The structure filled in by this function can usually be passed directly
318  * into drm_dp_link_power_up() and drm_dp_link_configure() to power up and
319  * configure the link based on the link's capabilities.
320  *
321  * Returns 0 on success or a negative error code on failure.
322  */
323 int drm_dp_link_probe(struct drm_dp_aux *aux, struct drm_dp_link *link)
324 {
325         u8 values[3];
326         int err;
327
328         memset(link, 0, sizeof(*link));
329
330         err = drm_dp_dpcd_read(aux, DP_DPCD_REV, values, sizeof(values));
331         if (err < 0)
332                 return err;
333
334         link->revision = values[0];
335         link->rate = drm_dp_bw_code_to_link_rate(values[1]);
336         link->num_lanes = values[2] & DP_MAX_LANE_COUNT_MASK;
337
338         if (values[2] & DP_ENHANCED_FRAME_CAP)
339                 link->capabilities |= DP_LINK_CAP_ENHANCED_FRAMING;
340
341         return 0;
342 }
343 EXPORT_SYMBOL(drm_dp_link_probe);
344
345 /**
346  * drm_dp_link_power_up() - power up a DisplayPort link
347  * @aux: DisplayPort AUX channel
348  * @link: pointer to a structure containing the link configuration
349  *
350  * Returns 0 on success or a negative error code on failure.
351  */
352 int drm_dp_link_power_up(struct drm_dp_aux *aux, struct drm_dp_link *link)
353 {
354         u8 value;
355         int err;
356
357         /* DP_SET_POWER register is only available on DPCD v1.1 and later */
358         if (link->revision < 0x11)
359                 return 0;
360
361         err = drm_dp_dpcd_readb(aux, DP_SET_POWER, &value);
362         if (err < 0)
363                 return err;
364
365         value &= ~DP_SET_POWER_MASK;
366         value |= DP_SET_POWER_D0;
367
368         err = drm_dp_dpcd_writeb(aux, DP_SET_POWER, value);
369         if (err < 0)
370                 return err;
371
372         /*
373          * According to the DP 1.1 specification, a "Sink Device must exit the
374          * power saving state within 1 ms" (Section 2.5.3.1, Table 5-52, "Sink
375          * Control Field" (register 0x600).
376          */
377         usleep_range(1000, 2000);
378
379         return 0;
380 }
381 EXPORT_SYMBOL(drm_dp_link_power_up);
382
383 /**
384  * drm_dp_link_power_down() - power down a DisplayPort link
385  * @aux: DisplayPort AUX channel
386  * @link: pointer to a structure containing the link configuration
387  *
388  * Returns 0 on success or a negative error code on failure.
389  */
390 int drm_dp_link_power_down(struct drm_dp_aux *aux, struct drm_dp_link *link)
391 {
392         u8 value;
393         int err;
394
395         /* DP_SET_POWER register is only available on DPCD v1.1 and later */
396         if (link->revision < 0x11)
397                 return 0;
398
399         err = drm_dp_dpcd_readb(aux, DP_SET_POWER, &value);
400         if (err < 0)
401                 return err;
402
403         value &= ~DP_SET_POWER_MASK;
404         value |= DP_SET_POWER_D3;
405
406         err = drm_dp_dpcd_writeb(aux, DP_SET_POWER, value);
407         if (err < 0)
408                 return err;
409
410         return 0;
411 }
412 EXPORT_SYMBOL(drm_dp_link_power_down);
413
414 /**
415  * drm_dp_link_configure() - configure a DisplayPort link
416  * @aux: DisplayPort AUX channel
417  * @link: pointer to a structure containing the link configuration
418  *
419  * Returns 0 on success or a negative error code on failure.
420  */
421 int drm_dp_link_configure(struct drm_dp_aux *aux, struct drm_dp_link *link)
422 {
423         u8 values[2];
424         int err;
425
426         values[0] = drm_dp_link_rate_to_bw_code(link->rate);
427         values[1] = link->num_lanes;
428
429         if (link->capabilities & DP_LINK_CAP_ENHANCED_FRAMING)
430                 values[1] |= DP_LANE_COUNT_ENHANCED_FRAME_EN;
431
432         err = drm_dp_dpcd_write(aux, DP_LINK_BW_SET, values, sizeof(values));
433         if (err < 0)
434                 return err;
435
436         return 0;
437 }
438 EXPORT_SYMBOL(drm_dp_link_configure);
439
440 /*
441  * I2C-over-AUX implementation
442  */
443
444 static u32 drm_dp_i2c_functionality(struct i2c_adapter *adapter)
445 {
446         return I2C_FUNC_I2C | I2C_FUNC_SMBUS_EMUL |
447                I2C_FUNC_SMBUS_READ_BLOCK_DATA |
448                I2C_FUNC_SMBUS_BLOCK_PROC_CALL |
449                I2C_FUNC_10BIT_ADDR;
450 }
451
452 static void drm_dp_i2c_msg_write_status_update(struct drm_dp_aux_msg *msg)
453 {
454         /*
455          * In case of i2c defer or short i2c ack reply to a write,
456          * we need to switch to WRITE_STATUS_UPDATE to drain the
457          * rest of the message
458          */
459         if ((msg->request & ~DP_AUX_I2C_MOT) == DP_AUX_I2C_WRITE) {
460                 msg->request &= DP_AUX_I2C_MOT;
461                 msg->request |= DP_AUX_I2C_WRITE_STATUS_UPDATE;
462         }
463 }
464
465 #define AUX_PRECHARGE_LEN 10 /* 10 to 16 */
466 #define AUX_SYNC_LEN (16 + 4) /* preamble + AUX_SYNC_END */
467 #define AUX_STOP_LEN 4
468 #define AUX_CMD_LEN 4
469 #define AUX_ADDRESS_LEN 20
470 #define AUX_REPLY_PAD_LEN 4
471 #define AUX_LENGTH_LEN 8
472
473 /*
474  * Calculate the duration of the AUX request/reply in usec. Gives the
475  * "best" case estimate, ie. successful while as short as possible.
476  */
477 static int drm_dp_aux_req_duration(const struct drm_dp_aux_msg *msg)
478 {
479         int len = AUX_PRECHARGE_LEN + AUX_SYNC_LEN + AUX_STOP_LEN +
480                 AUX_CMD_LEN + AUX_ADDRESS_LEN + AUX_LENGTH_LEN;
481
482         if ((msg->request & DP_AUX_I2C_READ) == 0)
483                 len += msg->size * 8;
484
485         return len;
486 }
487
488 static int drm_dp_aux_reply_duration(const struct drm_dp_aux_msg *msg)
489 {
490         int len = AUX_PRECHARGE_LEN + AUX_SYNC_LEN + AUX_STOP_LEN +
491                 AUX_CMD_LEN + AUX_REPLY_PAD_LEN;
492
493         /*
494          * For read we expect what was asked. For writes there will
495          * be 0 or 1 data bytes. Assume 0 for the "best" case.
496          */
497         if (msg->request & DP_AUX_I2C_READ)
498                 len += msg->size * 8;
499
500         return len;
501 }
502
503 #define I2C_START_LEN 1
504 #define I2C_STOP_LEN 1
505 #define I2C_ADDR_LEN 9 /* ADDRESS + R/W + ACK/NACK */
506 #define I2C_DATA_LEN 9 /* DATA + ACK/NACK */
507
508 /*
509  * Calculate the length of the i2c transfer in usec, assuming
510  * the i2c bus speed is as specified. Gives the the "worst"
511  * case estimate, ie. successful while as long as possible.
512  * Doesn't account the the "MOT" bit, and instead assumes each
513  * message includes a START, ADDRESS and STOP. Neither does it
514  * account for additional random variables such as clock stretching.
515  */
516 static int drm_dp_i2c_msg_duration(const struct drm_dp_aux_msg *msg,
517                                    int i2c_speed_khz)
518 {
519         /* AUX bitrate is 1MHz, i2c bitrate as specified */
520         return DIV_ROUND_UP((I2C_START_LEN + I2C_ADDR_LEN +
521                              msg->size * I2C_DATA_LEN +
522                              I2C_STOP_LEN) * 1000, i2c_speed_khz);
523 }
524
525 /*
526  * Deterine how many retries should be attempted to successfully transfer
527  * the specified message, based on the estimated durations of the
528  * i2c and AUX transfers.
529  */
530 static int drm_dp_i2c_retry_count(const struct drm_dp_aux_msg *msg,
531                               int i2c_speed_khz)
532 {
533         int aux_time_us = drm_dp_aux_req_duration(msg) +
534                 drm_dp_aux_reply_duration(msg);
535         int i2c_time_us = drm_dp_i2c_msg_duration(msg, i2c_speed_khz);
536
537         return DIV_ROUND_UP(i2c_time_us, aux_time_us + AUX_RETRY_INTERVAL);
538 }
539
540 /*
541  * FIXME currently assumes 10 kHz as some real world devices seem
542  * to require it. We should query/set the speed via DPCD if supported.
543  */
544 static int dp_aux_i2c_speed_khz __read_mostly = 10;
545 MODULE_PARM_DESC(dp_aux_i2c_speed_khz,
546                  "Assumed speed of the i2c bus in kHz, (1-400, default 10)");
547
548 /*
549  * Transfer a single I2C-over-AUX message and handle various error conditions,
550  * retrying the transaction as appropriate.  It is assumed that the
551  * aux->transfer function does not modify anything in the msg other than the
552  * reply field.
553  *
554  * Returns bytes transferred on success, or a negative error code on failure.
555  */
556 static int drm_dp_i2c_do_msg(struct drm_dp_aux *aux, struct drm_dp_aux_msg *msg)
557 {
558         unsigned int retry, defer_i2c;
559         int ret;
560         /*
561          * DP1.2 sections 2.7.7.1.5.6.1 and 2.7.7.1.6.6.1: A DP Source device
562          * is required to retry at least seven times upon receiving AUX_DEFER
563          * before giving up the AUX transaction.
564          *
565          * We also try to account for the i2c bus speed.
566          */
567         int max_retries = max(7, drm_dp_i2c_retry_count(msg, dp_aux_i2c_speed_khz));
568
569         for (retry = 0, defer_i2c = 0; retry < (max_retries + defer_i2c); retry++) {
570                 ret = aux->transfer(aux, msg);
571                 if (ret < 0) {
572                         if (ret == -EBUSY)
573                                 continue;
574
575                         DRM_DEBUG_KMS("transaction failed: %d\n", ret);
576                         return ret;
577                 }
578
579
580                 switch (msg->reply & DP_AUX_NATIVE_REPLY_MASK) {
581                 case DP_AUX_NATIVE_REPLY_ACK:
582                         /*
583                          * For I2C-over-AUX transactions this isn't enough, we
584                          * need to check for the I2C ACK reply.
585                          */
586                         break;
587
588                 case DP_AUX_NATIVE_REPLY_NACK:
589                         DRM_DEBUG_KMS("native nack (result=%d, size=%zu)\n", ret, msg->size);
590                         return -EREMOTEIO;
591
592                 case DP_AUX_NATIVE_REPLY_DEFER:
593                         DRM_DEBUG_KMS("native defer\n");
594                         /*
595                          * We could check for I2C bit rate capabilities and if
596                          * available adjust this interval. We could also be
597                          * more careful with DP-to-legacy adapters where a
598                          * long legacy cable may force very low I2C bit rates.
599                          *
600                          * For now just defer for long enough to hopefully be
601                          * safe for all use-cases.
602                          */
603                         usleep_range(AUX_RETRY_INTERVAL, AUX_RETRY_INTERVAL + 100);
604                         continue;
605
606                 default:
607                         DRM_ERROR("invalid native reply %#04x\n", msg->reply);
608                         return -EREMOTEIO;
609                 }
610
611                 switch (msg->reply & DP_AUX_I2C_REPLY_MASK) {
612                 case DP_AUX_I2C_REPLY_ACK:
613                         /*
614                          * Both native ACK and I2C ACK replies received. We
615                          * can assume the transfer was successful.
616                          */
617                         if (ret != msg->size)
618                                 drm_dp_i2c_msg_write_status_update(msg);
619                         return ret;
620
621                 case DP_AUX_I2C_REPLY_NACK:
622                         DRM_DEBUG_KMS("I2C nack (result=%d, size=%zu\n", ret, msg->size);
623                         aux->i2c_nack_count++;
624                         return -EREMOTEIO;
625
626                 case DP_AUX_I2C_REPLY_DEFER:
627                         DRM_DEBUG_KMS("I2C defer\n");
628                         /* DP Compliance Test 4.2.2.5 Requirement:
629                          * Must have at least 7 retries for I2C defers on the
630                          * transaction to pass this test
631                          */
632                         aux->i2c_defer_count++;
633                         if (defer_i2c < 7)
634                                 defer_i2c++;
635                         usleep_range(AUX_RETRY_INTERVAL, AUX_RETRY_INTERVAL + 100);
636                         drm_dp_i2c_msg_write_status_update(msg);
637
638                         continue;
639
640                 default:
641                         DRM_ERROR("invalid I2C reply %#04x\n", msg->reply);
642                         return -EREMOTEIO;
643                 }
644         }
645
646         DRM_DEBUG_KMS("too many retries, giving up\n");
647         return -EREMOTEIO;
648 }
649
650 static void drm_dp_i2c_msg_set_request(struct drm_dp_aux_msg *msg,
651                                        const struct i2c_msg *i2c_msg)
652 {
653         msg->request = (i2c_msg->flags & I2C_M_RD) ?
654                 DP_AUX_I2C_READ : DP_AUX_I2C_WRITE;
655         msg->request |= DP_AUX_I2C_MOT;
656 }
657
658 /*
659  * Keep retrying drm_dp_i2c_do_msg until all data has been transferred.
660  *
661  * Returns an error code on failure, or a recommended transfer size on success.
662  */
663 static int drm_dp_i2c_drain_msg(struct drm_dp_aux *aux, struct drm_dp_aux_msg *orig_msg)
664 {
665         int err, ret = orig_msg->size;
666         struct drm_dp_aux_msg msg = *orig_msg;
667
668         while (msg.size > 0) {
669                 err = drm_dp_i2c_do_msg(aux, &msg);
670                 if (err <= 0)
671                         return err == 0 ? -EPROTO : err;
672
673                 if (err < msg.size && err < ret) {
674                         DRM_DEBUG_KMS("Partial I2C reply: requested %zu bytes got %d bytes\n",
675                                       msg.size, err);
676                         ret = err;
677                 }
678
679                 msg.size -= err;
680                 msg.buffer += err;
681         }
682
683         return ret;
684 }
685
686 /*
687  * Bizlink designed DP->DVI-D Dual Link adapters require the I2C over AUX
688  * packets to be as large as possible. If not, the I2C transactions never
689  * succeed. Hence the default is maximum.
690  */
691 static int dp_aux_i2c_transfer_size __read_mostly = DP_AUX_MAX_PAYLOAD_BYTES;
692 MODULE_PARM_DESC(dp_aux_i2c_transfer_size,
693                  "Number of bytes to transfer in a single I2C over DP AUX CH message, (1-16, default 16)");
694
695 static int drm_dp_i2c_xfer(struct i2c_adapter *adapter, struct i2c_msg *msgs,
696                            int num)
697 {
698         struct drm_dp_aux *aux = adapter->algo_data;
699         unsigned int i, j;
700         unsigned transfer_size;
701         struct drm_dp_aux_msg msg;
702         int err = 0;
703
704         dp_aux_i2c_transfer_size = clamp(dp_aux_i2c_transfer_size, 1, DP_AUX_MAX_PAYLOAD_BYTES);
705
706         memset(&msg, 0, sizeof(msg));
707
708         mutex_lock(&aux->hw_mutex);
709
710         for (i = 0; i < num; i++) {
711                 msg.address = msgs[i].addr;
712                 drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
713                 /* Send a bare address packet to start the transaction.
714                  * Zero sized messages specify an address only (bare
715                  * address) transaction.
716                  */
717                 msg.buffer = NULL;
718                 msg.size = 0;
719                 err = drm_dp_i2c_do_msg(aux, &msg);
720
721                 /*
722                  * Reset msg.request in case in case it got
723                  * changed into a WRITE_STATUS_UPDATE.
724                  */
725                 drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
726
727                 if (err < 0)
728                         break;
729                 /* We want each transaction to be as large as possible, but
730                  * we'll go to smaller sizes if the hardware gives us a
731                  * short reply.
732                  */
733                 transfer_size = dp_aux_i2c_transfer_size;
734                 for (j = 0; j < msgs[i].len; j += msg.size) {
735                         msg.buffer = msgs[i].buf + j;
736                         msg.size = min(transfer_size, msgs[i].len - j);
737
738                         err = drm_dp_i2c_drain_msg(aux, &msg);
739
740                         /*
741                          * Reset msg.request in case in case it got
742                          * changed into a WRITE_STATUS_UPDATE.
743                          */
744                         drm_dp_i2c_msg_set_request(&msg, &msgs[i]);
745
746                         if (err < 0)
747                                 break;
748                         transfer_size = err;
749                 }
750                 if (err < 0)
751                         break;
752         }
753         if (err >= 0)
754                 err = num;
755         /* Send a bare address packet to close out the transaction.
756          * Zero sized messages specify an address only (bare
757          * address) transaction.
758          */
759         msg.request &= ~DP_AUX_I2C_MOT;
760         msg.buffer = NULL;
761         msg.size = 0;
762         (void)drm_dp_i2c_do_msg(aux, &msg);
763
764         mutex_unlock(&aux->hw_mutex);
765
766         return err;
767 }
768
769 static const struct i2c_algorithm drm_dp_i2c_algo = {
770         .functionality = drm_dp_i2c_functionality,
771         .master_xfer = drm_dp_i2c_xfer,
772 };
773
774 /**
775  * drm_dp_aux_register() - initialise and register aux channel
776  * @aux: DisplayPort AUX channel
777  *
778  * Returns 0 on success or a negative error code on failure.
779  */
780 int drm_dp_aux_register(struct drm_dp_aux *aux)
781 {
782         int ret;
783
784         lockinit(&aux->hw_mutex, "ahwm", 0, LK_CANRECURSE);
785
786         aux->ddc.algo = &drm_dp_i2c_algo;
787         aux->ddc.algo_data = aux;
788         aux->ddc.retries = 3;
789
790 #if 0
791         aux->ddc.class = I2C_CLASS_DDC;
792         aux->ddc.owner = THIS_MODULE;
793 #endif
794         aux->ddc.dev.parent = aux->dev;
795 #if 0
796         aux->ddc.dev.of_node = aux->dev->of_node;
797 #endif
798
799         strlcpy(aux->ddc.name, aux->name ? aux->name : dev_name(aux->dev),
800                 sizeof(aux->ddc.name));
801
802         ret = drm_dp_aux_register_devnode(aux);
803         if (ret)
804                 return ret;
805
806         ret = i2c_add_adapter(&aux->ddc);
807         if (ret) {
808                 drm_dp_aux_unregister_devnode(aux);
809                 return ret;
810         }
811
812         return 0;
813 }
814 EXPORT_SYMBOL(drm_dp_aux_register);
815
816 /**
817  * drm_dp_aux_unregister() - unregister an AUX adapter
818  * @aux: DisplayPort AUX channel
819  */
820 void drm_dp_aux_unregister(struct drm_dp_aux *aux)
821 {
822         drm_dp_aux_unregister_devnode(aux);
823         i2c_del_adapter(&aux->ddc);
824 }
825 EXPORT_SYMBOL(drm_dp_aux_unregister);