xref: /linux/drivers/i2c/busses/i2c-designware-master.c (revision 7f4f3b14e8079ecde096bd734af10e30d40c27b7)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Synopsys DesignWare I2C adapter driver (master only).
4  *
5  * Based on the TI DAVINCI I2C adapter driver.
6  *
7  * Copyright (C) 2006 Texas Instruments.
8  * Copyright (C) 2007 MontaVista Software Inc.
9  * Copyright (C) 2009 Provigent Ltd.
10  */
11 #include <linux/delay.h>
12 #include <linux/err.h>
13 #include <linux/errno.h>
14 #include <linux/export.h>
15 #include <linux/gpio/consumer.h>
16 #include <linux/i2c.h>
17 #include <linux/interrupt.h>
18 #include <linux/io.h>
19 #include <linux/module.h>
20 #include <linux/pinctrl/consumer.h>
21 #include <linux/pm_runtime.h>
22 #include <linux/regmap.h>
23 #include <linux/reset.h>
24 
25 #define DEFAULT_SYMBOL_NAMESPACE	I2C_DW
26 
27 #include "i2c-designware-core.h"
28 
29 #define AMD_TIMEOUT_MIN_US	25
30 #define AMD_TIMEOUT_MAX_US	250
31 #define AMD_MASTERCFG_MASK	GENMASK(15, 0)
32 
33 static void i2c_dw_configure_fifo_master(struct dw_i2c_dev *dev)
34 {
35 	/* Configure Tx/Rx FIFO threshold levels */
36 	regmap_write(dev->map, DW_IC_TX_TL, dev->tx_fifo_depth / 2);
37 	regmap_write(dev->map, DW_IC_RX_TL, 0);
38 
39 	/* Configure the I2C master */
40 	regmap_write(dev->map, DW_IC_CON, dev->master_cfg);
41 }
42 
43 static int i2c_dw_set_timings_master(struct dw_i2c_dev *dev)
44 {
45 	unsigned int comp_param1;
46 	u32 sda_falling_time, scl_falling_time;
47 	struct i2c_timings *t = &dev->timings;
48 	const char *fp_str = "";
49 	u32 ic_clk;
50 	int ret;
51 
52 	ret = i2c_dw_acquire_lock(dev);
53 	if (ret)
54 		return ret;
55 
56 	ret = regmap_read(dev->map, DW_IC_COMP_PARAM_1, &comp_param1);
57 	i2c_dw_release_lock(dev);
58 	if (ret)
59 		return ret;
60 
61 	/* Set standard and fast speed dividers for high/low periods */
62 	sda_falling_time = t->sda_fall_ns ?: 300; /* ns */
63 	scl_falling_time = t->scl_fall_ns ?: 300; /* ns */
64 
65 	/* Calculate SCL timing parameters for standard mode if not set */
66 	if (!dev->ss_hcnt || !dev->ss_lcnt) {
67 		ic_clk = i2c_dw_clk_rate(dev);
68 		dev->ss_hcnt =
69 			i2c_dw_scl_hcnt(dev,
70 					DW_IC_SS_SCL_HCNT,
71 					ic_clk,
72 					4000,	/* tHD;STA = tHIGH = 4.0 us */
73 					sda_falling_time,
74 					0);	/* No offset */
75 		dev->ss_lcnt =
76 			i2c_dw_scl_lcnt(dev,
77 					DW_IC_SS_SCL_LCNT,
78 					ic_clk,
79 					4700,	/* tLOW = 4.7 us */
80 					scl_falling_time,
81 					0);	/* No offset */
82 	}
83 	dev_dbg(dev->dev, "Standard Mode HCNT:LCNT = %d:%d\n",
84 		dev->ss_hcnt, dev->ss_lcnt);
85 
86 	/*
87 	 * Set SCL timing parameters for fast mode or fast mode plus. Only
88 	 * difference is the timing parameter values since the registers are
89 	 * the same.
90 	 */
91 	if (t->bus_freq_hz == I2C_MAX_FAST_MODE_PLUS_FREQ) {
92 		/*
93 		 * Check are Fast Mode Plus parameters available. Calculate
94 		 * SCL timing parameters for Fast Mode Plus if not set.
95 		 */
96 		if (dev->fp_hcnt && dev->fp_lcnt) {
97 			dev->fs_hcnt = dev->fp_hcnt;
98 			dev->fs_lcnt = dev->fp_lcnt;
99 		} else {
100 			ic_clk = i2c_dw_clk_rate(dev);
101 			dev->fs_hcnt =
102 				i2c_dw_scl_hcnt(dev,
103 						DW_IC_FS_SCL_HCNT,
104 						ic_clk,
105 						260,	/* tHIGH = 260 ns */
106 						sda_falling_time,
107 						0);	/* No offset */
108 			dev->fs_lcnt =
109 				i2c_dw_scl_lcnt(dev,
110 						DW_IC_FS_SCL_LCNT,
111 						ic_clk,
112 						500,	/* tLOW = 500 ns */
113 						scl_falling_time,
114 						0);	/* No offset */
115 		}
116 		fp_str = " Plus";
117 	}
118 	/*
119 	 * Calculate SCL timing parameters for fast mode if not set. They are
120 	 * needed also in high speed mode.
121 	 */
122 	if (!dev->fs_hcnt || !dev->fs_lcnt) {
123 		ic_clk = i2c_dw_clk_rate(dev);
124 		dev->fs_hcnt =
125 			i2c_dw_scl_hcnt(dev,
126 					DW_IC_FS_SCL_HCNT,
127 					ic_clk,
128 					600,	/* tHD;STA = tHIGH = 0.6 us */
129 					sda_falling_time,
130 					0);	/* No offset */
131 		dev->fs_lcnt =
132 			i2c_dw_scl_lcnt(dev,
133 					DW_IC_FS_SCL_LCNT,
134 					ic_clk,
135 					1300,	/* tLOW = 1.3 us */
136 					scl_falling_time,
137 					0);	/* No offset */
138 	}
139 	dev_dbg(dev->dev, "Fast Mode%s HCNT:LCNT = %d:%d\n",
140 		fp_str, dev->fs_hcnt, dev->fs_lcnt);
141 
142 	/* Check is high speed possible and fall back to fast mode if not */
143 	if ((dev->master_cfg & DW_IC_CON_SPEED_MASK) ==
144 		DW_IC_CON_SPEED_HIGH) {
145 		if ((comp_param1 & DW_IC_COMP_PARAM_1_SPEED_MODE_MASK)
146 			!= DW_IC_COMP_PARAM_1_SPEED_MODE_HIGH) {
147 			dev_err(dev->dev, "High Speed not supported!\n");
148 			t->bus_freq_hz = I2C_MAX_FAST_MODE_FREQ;
149 			dev->master_cfg &= ~DW_IC_CON_SPEED_MASK;
150 			dev->master_cfg |= DW_IC_CON_SPEED_FAST;
151 			dev->hs_hcnt = 0;
152 			dev->hs_lcnt = 0;
153 		} else if (!dev->hs_hcnt || !dev->hs_lcnt) {
154 			ic_clk = i2c_dw_clk_rate(dev);
155 			dev->hs_hcnt =
156 				i2c_dw_scl_hcnt(dev,
157 						DW_IC_HS_SCL_HCNT,
158 						ic_clk,
159 						160,	/* tHIGH = 160 ns */
160 						sda_falling_time,
161 						0);	/* No offset */
162 			dev->hs_lcnt =
163 				i2c_dw_scl_lcnt(dev,
164 						DW_IC_HS_SCL_LCNT,
165 						ic_clk,
166 						320,	/* tLOW = 320 ns */
167 						scl_falling_time,
168 						0);	/* No offset */
169 		}
170 		dev_dbg(dev->dev, "High Speed Mode HCNT:LCNT = %d:%d\n",
171 			dev->hs_hcnt, dev->hs_lcnt);
172 	}
173 
174 	ret = i2c_dw_set_sda_hold(dev);
175 	if (ret)
176 		return ret;
177 
178 	dev_dbg(dev->dev, "Bus speed: %s\n", i2c_freq_mode_string(t->bus_freq_hz));
179 	return 0;
180 }
181 
182 /**
183  * i2c_dw_init_master() - Initialize the DesignWare I2C master hardware
184  * @dev: device private data
185  *
186  * This functions configures and enables the I2C master.
187  * This function is called during I2C init function, and in case of timeout at
188  * run time.
189  *
190  * Return: 0 on success, or negative errno otherwise.
191  */
192 static int i2c_dw_init_master(struct dw_i2c_dev *dev)
193 {
194 	int ret;
195 
196 	ret = i2c_dw_acquire_lock(dev);
197 	if (ret)
198 		return ret;
199 
200 	/* Disable the adapter */
201 	__i2c_dw_disable(dev);
202 
203 	/* Write standard speed timing parameters */
204 	regmap_write(dev->map, DW_IC_SS_SCL_HCNT, dev->ss_hcnt);
205 	regmap_write(dev->map, DW_IC_SS_SCL_LCNT, dev->ss_lcnt);
206 
207 	/* Write fast mode/fast mode plus timing parameters */
208 	regmap_write(dev->map, DW_IC_FS_SCL_HCNT, dev->fs_hcnt);
209 	regmap_write(dev->map, DW_IC_FS_SCL_LCNT, dev->fs_lcnt);
210 
211 	/* Write high speed timing parameters if supported */
212 	if (dev->hs_hcnt && dev->hs_lcnt) {
213 		regmap_write(dev->map, DW_IC_HS_SCL_HCNT, dev->hs_hcnt);
214 		regmap_write(dev->map, DW_IC_HS_SCL_LCNT, dev->hs_lcnt);
215 	}
216 
217 	/* Write SDA hold time if supported */
218 	if (dev->sda_hold_time)
219 		regmap_write(dev->map, DW_IC_SDA_HOLD, dev->sda_hold_time);
220 
221 	i2c_dw_configure_fifo_master(dev);
222 	i2c_dw_release_lock(dev);
223 
224 	return 0;
225 }
226 
227 static void i2c_dw_xfer_init(struct dw_i2c_dev *dev)
228 {
229 	struct i2c_msg *msgs = dev->msgs;
230 	u32 ic_con = 0, ic_tar = 0;
231 	unsigned int dummy;
232 
233 	/* Disable the adapter */
234 	__i2c_dw_disable(dev);
235 
236 	/* If the slave address is ten bit address, enable 10BITADDR */
237 	if (msgs[dev->msg_write_idx].flags & I2C_M_TEN) {
238 		ic_con = DW_IC_CON_10BITADDR_MASTER;
239 		/*
240 		 * If I2C_DYNAMIC_TAR_UPDATE is set, the 10-bit addressing
241 		 * mode has to be enabled via bit 12 of IC_TAR register.
242 		 * We set it always as I2C_DYNAMIC_TAR_UPDATE can't be
243 		 * detected from registers.
244 		 */
245 		ic_tar = DW_IC_TAR_10BITADDR_MASTER;
246 	}
247 
248 	regmap_update_bits(dev->map, DW_IC_CON, DW_IC_CON_10BITADDR_MASTER,
249 			   ic_con);
250 
251 	/*
252 	 * Set the slave (target) address and enable 10-bit addressing mode
253 	 * if applicable.
254 	 */
255 	regmap_write(dev->map, DW_IC_TAR,
256 		     msgs[dev->msg_write_idx].addr | ic_tar);
257 
258 	/* Enforce disabled interrupts (due to HW issues) */
259 	__i2c_dw_write_intr_mask(dev, 0);
260 
261 	/* Enable the adapter */
262 	__i2c_dw_enable(dev);
263 
264 	/* Dummy read to avoid the register getting stuck on Bay Trail */
265 	regmap_read(dev->map, DW_IC_ENABLE_STATUS, &dummy);
266 
267 	/* Clear and enable interrupts */
268 	regmap_read(dev->map, DW_IC_CLR_INTR, &dummy);
269 	__i2c_dw_write_intr_mask(dev, DW_IC_INTR_MASTER_MASK);
270 }
271 
272 /*
273  * This function waits for the controller to be idle before disabling I2C
274  * When the controller is not in the IDLE state, the MST_ACTIVITY bit
275  * (IC_STATUS[5]) is set.
276  *
277  * Values:
278  * 0x1 (ACTIVE): Controller not idle
279  * 0x0 (IDLE): Controller is idle
280  *
281  * The function is called after completing the current transfer.
282  *
283  * Returns:
284  * False when the controller is in the IDLE state.
285  * True when the controller is in the ACTIVE state.
286  */
287 static bool i2c_dw_is_controller_active(struct dw_i2c_dev *dev)
288 {
289 	u32 status;
290 
291 	regmap_read(dev->map, DW_IC_STATUS, &status);
292 	if (!(status & DW_IC_STATUS_MASTER_ACTIVITY))
293 		return false;
294 
295 	return regmap_read_poll_timeout(dev->map, DW_IC_STATUS, status,
296 				       !(status & DW_IC_STATUS_MASTER_ACTIVITY),
297 				       1100, 20000) != 0;
298 }
299 
300 static int i2c_dw_check_stopbit(struct dw_i2c_dev *dev)
301 {
302 	u32 val;
303 	int ret;
304 
305 	ret = regmap_read_poll_timeout(dev->map, DW_IC_INTR_STAT, val,
306 				       !(val & DW_IC_INTR_STOP_DET),
307 					1100, 20000);
308 	if (ret)
309 		dev_err(dev->dev, "i2c timeout error %d\n", ret);
310 
311 	return ret;
312 }
313 
314 static int i2c_dw_status(struct dw_i2c_dev *dev)
315 {
316 	int status;
317 
318 	status = i2c_dw_wait_bus_not_busy(dev);
319 	if (status)
320 		return status;
321 
322 	return i2c_dw_check_stopbit(dev);
323 }
324 
325 /*
326  * Initiate and continue master read/write transaction with polling
327  * based transfer routine afterward write messages into the Tx buffer.
328  */
329 static int amd_i2c_dw_xfer_quirk(struct i2c_adapter *adap, struct i2c_msg *msgs, int num_msgs)
330 {
331 	struct dw_i2c_dev *dev = i2c_get_adapdata(adap);
332 	int msg_wrt_idx, msg_itr_lmt, buf_len, data_idx;
333 	int cmd = 0, status;
334 	u8 *tx_buf;
335 	unsigned int val;
336 
337 	/*
338 	 * In order to enable the interrupt for UCSI i.e. AMD NAVI GPU card,
339 	 * it is mandatory to set the right value in specific register
340 	 * (offset:0x474) as per the hardware IP specification.
341 	 */
342 	regmap_write(dev->map, AMD_UCSI_INTR_REG, AMD_UCSI_INTR_EN);
343 
344 	dev->msgs = msgs;
345 	dev->msgs_num = num_msgs;
346 	i2c_dw_xfer_init(dev);
347 
348 	/* Initiate messages read/write transaction */
349 	for (msg_wrt_idx = 0; msg_wrt_idx < num_msgs; msg_wrt_idx++) {
350 		tx_buf = msgs[msg_wrt_idx].buf;
351 		buf_len = msgs[msg_wrt_idx].len;
352 
353 		if (!(msgs[msg_wrt_idx].flags & I2C_M_RD))
354 			regmap_write(dev->map, DW_IC_TX_TL, buf_len - 1);
355 		/*
356 		 * Initiate the i2c read/write transaction of buffer length,
357 		 * and poll for bus busy status. For the last message transfer,
358 		 * update the command with stop bit enable.
359 		 */
360 		for (msg_itr_lmt = buf_len; msg_itr_lmt > 0; msg_itr_lmt--) {
361 			if (msg_wrt_idx == num_msgs - 1 && msg_itr_lmt == 1)
362 				cmd |= BIT(9);
363 
364 			if (msgs[msg_wrt_idx].flags & I2C_M_RD) {
365 				/* Due to hardware bug, need to write the same command twice. */
366 				regmap_write(dev->map, DW_IC_DATA_CMD, 0x100);
367 				regmap_write(dev->map, DW_IC_DATA_CMD, 0x100 | cmd);
368 				if (cmd) {
369 					regmap_write(dev->map, DW_IC_TX_TL, 2 * (buf_len - 1));
370 					regmap_write(dev->map, DW_IC_RX_TL, 2 * (buf_len - 1));
371 					/*
372 					 * Need to check the stop bit. However, it cannot be
373 					 * detected from the registers so we check it always
374 					 * when read/write the last byte.
375 					 */
376 					status = i2c_dw_status(dev);
377 					if (status)
378 						return status;
379 
380 					for (data_idx = 0; data_idx < buf_len; data_idx++) {
381 						regmap_read(dev->map, DW_IC_DATA_CMD, &val);
382 						tx_buf[data_idx] = val;
383 					}
384 					status = i2c_dw_check_stopbit(dev);
385 					if (status)
386 						return status;
387 				}
388 			} else {
389 				regmap_write(dev->map, DW_IC_DATA_CMD, *tx_buf++ | cmd);
390 				usleep_range(AMD_TIMEOUT_MIN_US, AMD_TIMEOUT_MAX_US);
391 			}
392 		}
393 		status = i2c_dw_check_stopbit(dev);
394 		if (status)
395 			return status;
396 	}
397 
398 	return 0;
399 }
400 
401 /*
402  * Initiate (and continue) low level master read/write transaction.
403  * This function is only called from i2c_dw_isr(), and pumping i2c_msg
404  * messages into the tx buffer.  Even if the size of i2c_msg data is
405  * longer than the size of the tx buffer, it handles everything.
406  */
407 static void
408 i2c_dw_xfer_msg(struct dw_i2c_dev *dev)
409 {
410 	struct i2c_msg *msgs = dev->msgs;
411 	u32 intr_mask;
412 	int tx_limit, rx_limit;
413 	u32 addr = msgs[dev->msg_write_idx].addr;
414 	u32 buf_len = dev->tx_buf_len;
415 	u8 *buf = dev->tx_buf;
416 	bool need_restart = false;
417 	unsigned int flr;
418 
419 	intr_mask = DW_IC_INTR_MASTER_MASK;
420 
421 	for (; dev->msg_write_idx < dev->msgs_num; dev->msg_write_idx++) {
422 		u32 flags = msgs[dev->msg_write_idx].flags;
423 
424 		/*
425 		 * If target address has changed, we need to
426 		 * reprogram the target address in the I2C
427 		 * adapter when we are done with this transfer.
428 		 */
429 		if (msgs[dev->msg_write_idx].addr != addr) {
430 			dev_err(dev->dev,
431 				"%s: invalid target address\n", __func__);
432 			dev->msg_err = -EINVAL;
433 			break;
434 		}
435 
436 		if (!(dev->status & STATUS_WRITE_IN_PROGRESS)) {
437 			/* new i2c_msg */
438 			buf = msgs[dev->msg_write_idx].buf;
439 			buf_len = msgs[dev->msg_write_idx].len;
440 
441 			/*
442 			 * If both IC_EMPTYFIFO_HOLD_MASTER_EN and
443 			 * IC_RESTART_EN are set, we must manually
444 			 * set restart bit between messages.
445 			 */
446 			if ((dev->master_cfg & DW_IC_CON_RESTART_EN) &&
447 					(dev->msg_write_idx > 0))
448 				need_restart = true;
449 		}
450 
451 		regmap_read(dev->map, DW_IC_TXFLR, &flr);
452 		tx_limit = dev->tx_fifo_depth - flr;
453 
454 		regmap_read(dev->map, DW_IC_RXFLR, &flr);
455 		rx_limit = dev->rx_fifo_depth - flr;
456 
457 		while (buf_len > 0 && tx_limit > 0 && rx_limit > 0) {
458 			u32 cmd = 0;
459 
460 			/*
461 			 * If IC_EMPTYFIFO_HOLD_MASTER_EN is set we must
462 			 * manually set the stop bit. However, it cannot be
463 			 * detected from the registers so we set it always
464 			 * when writing/reading the last byte.
465 			 */
466 
467 			/*
468 			 * i2c-core always sets the buffer length of
469 			 * I2C_FUNC_SMBUS_BLOCK_DATA to 1. The length will
470 			 * be adjusted when receiving the first byte.
471 			 * Thus we can't stop the transaction here.
472 			 */
473 			if (dev->msg_write_idx == dev->msgs_num - 1 &&
474 			    buf_len == 1 && !(flags & I2C_M_RECV_LEN))
475 				cmd |= BIT(9);
476 
477 			if (need_restart) {
478 				cmd |= BIT(10);
479 				need_restart = false;
480 			}
481 
482 			if (msgs[dev->msg_write_idx].flags & I2C_M_RD) {
483 
484 				/* Avoid rx buffer overrun */
485 				if (dev->rx_outstanding >= dev->rx_fifo_depth)
486 					break;
487 
488 				regmap_write(dev->map, DW_IC_DATA_CMD,
489 					     cmd | 0x100);
490 				rx_limit--;
491 				dev->rx_outstanding++;
492 			} else {
493 				regmap_write(dev->map, DW_IC_DATA_CMD,
494 					     cmd | *buf++);
495 			}
496 			tx_limit--; buf_len--;
497 		}
498 
499 		dev->tx_buf = buf;
500 		dev->tx_buf_len = buf_len;
501 
502 		/*
503 		 * Because we don't know the buffer length in the
504 		 * I2C_FUNC_SMBUS_BLOCK_DATA case, we can't stop the
505 		 * transaction here. Also disable the TX_EMPTY IRQ
506 		 * while waiting for the data length byte to avoid the
507 		 * bogus interrupts flood.
508 		 */
509 		if (flags & I2C_M_RECV_LEN) {
510 			dev->status |= STATUS_WRITE_IN_PROGRESS;
511 			intr_mask &= ~DW_IC_INTR_TX_EMPTY;
512 			break;
513 		} else if (buf_len > 0) {
514 			/* more bytes to be written */
515 			dev->status |= STATUS_WRITE_IN_PROGRESS;
516 			break;
517 		} else
518 			dev->status &= ~STATUS_WRITE_IN_PROGRESS;
519 	}
520 
521 	/*
522 	 * If i2c_msg index search is completed, we don't need TX_EMPTY
523 	 * interrupt any more.
524 	 */
525 	if (dev->msg_write_idx == dev->msgs_num)
526 		intr_mask &= ~DW_IC_INTR_TX_EMPTY;
527 
528 	if (dev->msg_err)
529 		intr_mask = 0;
530 
531 	__i2c_dw_write_intr_mask(dev, intr_mask);
532 }
533 
534 static u8
535 i2c_dw_recv_len(struct dw_i2c_dev *dev, u8 len)
536 {
537 	struct i2c_msg *msgs = dev->msgs;
538 	u32 flags = msgs[dev->msg_read_idx].flags;
539 	unsigned int intr_mask;
540 
541 	/*
542 	 * Adjust the buffer length and mask the flag
543 	 * after receiving the first byte.
544 	 */
545 	len += (flags & I2C_CLIENT_PEC) ? 2 : 1;
546 	dev->tx_buf_len = len - min_t(u8, len, dev->rx_outstanding);
547 	msgs[dev->msg_read_idx].len = len;
548 	msgs[dev->msg_read_idx].flags &= ~I2C_M_RECV_LEN;
549 
550 	/*
551 	 * Received buffer length, re-enable TX_EMPTY interrupt
552 	 * to resume the SMBUS transaction.
553 	 */
554 	__i2c_dw_read_intr_mask(dev, &intr_mask);
555 	intr_mask |= DW_IC_INTR_TX_EMPTY;
556 	__i2c_dw_write_intr_mask(dev, intr_mask);
557 
558 	return len;
559 }
560 
561 static void
562 i2c_dw_read(struct dw_i2c_dev *dev)
563 {
564 	struct i2c_msg *msgs = dev->msgs;
565 	unsigned int rx_valid;
566 
567 	for (; dev->msg_read_idx < dev->msgs_num; dev->msg_read_idx++) {
568 		unsigned int tmp;
569 		u32 len;
570 		u8 *buf;
571 
572 		if (!(msgs[dev->msg_read_idx].flags & I2C_M_RD))
573 			continue;
574 
575 		if (!(dev->status & STATUS_READ_IN_PROGRESS)) {
576 			len = msgs[dev->msg_read_idx].len;
577 			buf = msgs[dev->msg_read_idx].buf;
578 		} else {
579 			len = dev->rx_buf_len;
580 			buf = dev->rx_buf;
581 		}
582 
583 		regmap_read(dev->map, DW_IC_RXFLR, &rx_valid);
584 
585 		for (; len > 0 && rx_valid > 0; len--, rx_valid--) {
586 			u32 flags = msgs[dev->msg_read_idx].flags;
587 
588 			regmap_read(dev->map, DW_IC_DATA_CMD, &tmp);
589 			tmp &= DW_IC_DATA_CMD_DAT;
590 			/* Ensure length byte is a valid value */
591 			if (flags & I2C_M_RECV_LEN) {
592 				/*
593 				 * if IC_EMPTYFIFO_HOLD_MASTER_EN is set, which cannot be
594 				 * detected from the registers, the controller can be
595 				 * disabled if the STOP bit is set. But it is only set
596 				 * after receiving block data response length in
597 				 * I2C_FUNC_SMBUS_BLOCK_DATA case. That needs to read
598 				 * another byte with STOP bit set when the block data
599 				 * response length is invalid to complete the transaction.
600 				 */
601 				if (!tmp || tmp > I2C_SMBUS_BLOCK_MAX)
602 					tmp = 1;
603 
604 				len = i2c_dw_recv_len(dev, tmp);
605 			}
606 			*buf++ = tmp;
607 			dev->rx_outstanding--;
608 		}
609 
610 		if (len > 0) {
611 			dev->status |= STATUS_READ_IN_PROGRESS;
612 			dev->rx_buf_len = len;
613 			dev->rx_buf = buf;
614 			return;
615 		} else
616 			dev->status &= ~STATUS_READ_IN_PROGRESS;
617 	}
618 }
619 
620 static u32 i2c_dw_read_clear_intrbits(struct dw_i2c_dev *dev)
621 {
622 	unsigned int stat, dummy;
623 
624 	/*
625 	 * The IC_INTR_STAT register just indicates "enabled" interrupts.
626 	 * The unmasked raw version of interrupt status bits is available
627 	 * in the IC_RAW_INTR_STAT register.
628 	 *
629 	 * That is,
630 	 *   stat = readl(IC_INTR_STAT);
631 	 * equals to,
632 	 *   stat = readl(IC_RAW_INTR_STAT) & readl(IC_INTR_MASK);
633 	 *
634 	 * The raw version might be useful for debugging purposes.
635 	 */
636 	if (!(dev->flags & ACCESS_POLLING)) {
637 		regmap_read(dev->map, DW_IC_INTR_STAT, &stat);
638 	} else {
639 		regmap_read(dev->map, DW_IC_RAW_INTR_STAT, &stat);
640 		stat &= dev->sw_mask;
641 	}
642 
643 	/*
644 	 * Do not use the IC_CLR_INTR register to clear interrupts, or
645 	 * you'll miss some interrupts, triggered during the period from
646 	 * readl(IC_INTR_STAT) to readl(IC_CLR_INTR).
647 	 *
648 	 * Instead, use the separately-prepared IC_CLR_* registers.
649 	 */
650 	if (stat & DW_IC_INTR_RX_UNDER)
651 		regmap_read(dev->map, DW_IC_CLR_RX_UNDER, &dummy);
652 	if (stat & DW_IC_INTR_RX_OVER)
653 		regmap_read(dev->map, DW_IC_CLR_RX_OVER, &dummy);
654 	if (stat & DW_IC_INTR_TX_OVER)
655 		regmap_read(dev->map, DW_IC_CLR_TX_OVER, &dummy);
656 	if (stat & DW_IC_INTR_RD_REQ)
657 		regmap_read(dev->map, DW_IC_CLR_RD_REQ, &dummy);
658 	if (stat & DW_IC_INTR_TX_ABRT) {
659 		/*
660 		 * The IC_TX_ABRT_SOURCE register is cleared whenever
661 		 * the IC_CLR_TX_ABRT is read.  Preserve it beforehand.
662 		 */
663 		regmap_read(dev->map, DW_IC_TX_ABRT_SOURCE, &dev->abort_source);
664 		regmap_read(dev->map, DW_IC_CLR_TX_ABRT, &dummy);
665 	}
666 	if (stat & DW_IC_INTR_RX_DONE)
667 		regmap_read(dev->map, DW_IC_CLR_RX_DONE, &dummy);
668 	if (stat & DW_IC_INTR_ACTIVITY)
669 		regmap_read(dev->map, DW_IC_CLR_ACTIVITY, &dummy);
670 	if ((stat & DW_IC_INTR_STOP_DET) &&
671 	    ((dev->rx_outstanding == 0) || (stat & DW_IC_INTR_RX_FULL)))
672 		regmap_read(dev->map, DW_IC_CLR_STOP_DET, &dummy);
673 	if (stat & DW_IC_INTR_START_DET)
674 		regmap_read(dev->map, DW_IC_CLR_START_DET, &dummy);
675 	if (stat & DW_IC_INTR_GEN_CALL)
676 		regmap_read(dev->map, DW_IC_CLR_GEN_CALL, &dummy);
677 
678 	return stat;
679 }
680 
681 static void i2c_dw_process_transfer(struct dw_i2c_dev *dev, unsigned int stat)
682 {
683 	if (stat & DW_IC_INTR_TX_ABRT) {
684 		dev->cmd_err |= DW_IC_ERR_TX_ABRT;
685 		dev->status &= ~STATUS_MASK;
686 		dev->rx_outstanding = 0;
687 
688 		/*
689 		 * Anytime TX_ABRT is set, the contents of the tx/rx
690 		 * buffers are flushed. Make sure to skip them.
691 		 */
692 		__i2c_dw_write_intr_mask(dev, 0);
693 		goto tx_aborted;
694 	}
695 
696 	if (stat & DW_IC_INTR_RX_FULL)
697 		i2c_dw_read(dev);
698 
699 	if (stat & DW_IC_INTR_TX_EMPTY)
700 		i2c_dw_xfer_msg(dev);
701 
702 	/*
703 	 * No need to modify or disable the interrupt mask here.
704 	 * i2c_dw_xfer_msg() will take care of it according to
705 	 * the current transmit status.
706 	 */
707 
708 tx_aborted:
709 	if (((stat & (DW_IC_INTR_TX_ABRT | DW_IC_INTR_STOP_DET)) || dev->msg_err) &&
710 	     (dev->rx_outstanding == 0))
711 		complete(&dev->cmd_complete);
712 	else if (unlikely(dev->flags & ACCESS_INTR_MASK)) {
713 		/* Workaround to trigger pending interrupt */
714 		__i2c_dw_read_intr_mask(dev, &stat);
715 		__i2c_dw_write_intr_mask(dev, 0);
716 		__i2c_dw_write_intr_mask(dev, stat);
717 	}
718 }
719 
720 /*
721  * Interrupt service routine. This gets called whenever an I2C master interrupt
722  * occurs.
723  */
724 static irqreturn_t i2c_dw_isr(int this_irq, void *dev_id)
725 {
726 	struct dw_i2c_dev *dev = dev_id;
727 	unsigned int stat, enabled;
728 
729 	regmap_read(dev->map, DW_IC_ENABLE, &enabled);
730 	regmap_read(dev->map, DW_IC_RAW_INTR_STAT, &stat);
731 	if (!enabled || !(stat & ~DW_IC_INTR_ACTIVITY))
732 		return IRQ_NONE;
733 	if (pm_runtime_suspended(dev->dev) || stat == GENMASK(31, 0))
734 		return IRQ_NONE;
735 	dev_dbg(dev->dev, "enabled=%#x stat=%#x\n", enabled, stat);
736 
737 	stat = i2c_dw_read_clear_intrbits(dev);
738 
739 	if (!(dev->status & STATUS_ACTIVE)) {
740 		/*
741 		 * Unexpected interrupt in driver point of view. State
742 		 * variables are either unset or stale so acknowledge and
743 		 * disable interrupts for suppressing further interrupts if
744 		 * interrupt really came from this HW (E.g. firmware has left
745 		 * the HW active).
746 		 */
747 		__i2c_dw_write_intr_mask(dev, 0);
748 		return IRQ_HANDLED;
749 	}
750 
751 	i2c_dw_process_transfer(dev, stat);
752 
753 	return IRQ_HANDLED;
754 }
755 
756 static int i2c_dw_wait_transfer(struct dw_i2c_dev *dev)
757 {
758 	unsigned long timeout = dev->adapter.timeout;
759 	unsigned int stat;
760 	int ret;
761 
762 	if (!(dev->flags & ACCESS_POLLING)) {
763 		ret = wait_for_completion_timeout(&dev->cmd_complete, timeout);
764 	} else {
765 		timeout += jiffies;
766 		do {
767 			ret = try_wait_for_completion(&dev->cmd_complete);
768 			if (ret)
769 				break;
770 
771 			stat = i2c_dw_read_clear_intrbits(dev);
772 			if (stat)
773 				i2c_dw_process_transfer(dev, stat);
774 			else
775 				/* Try save some power */
776 				usleep_range(3, 25);
777 		} while (time_before(jiffies, timeout));
778 	}
779 
780 	return ret ? 0 : -ETIMEDOUT;
781 }
782 
783 /*
784  * Prepare controller for a transaction and call i2c_dw_xfer_msg.
785  */
786 static int
787 i2c_dw_xfer(struct i2c_adapter *adap, struct i2c_msg msgs[], int num)
788 {
789 	struct dw_i2c_dev *dev = i2c_get_adapdata(adap);
790 	int ret;
791 
792 	dev_dbg(dev->dev, "%s: msgs: %d\n", __func__, num);
793 
794 	pm_runtime_get_sync(dev->dev);
795 
796 	switch (dev->flags & MODEL_MASK) {
797 	case MODEL_AMD_NAVI_GPU:
798 		ret = amd_i2c_dw_xfer_quirk(adap, msgs, num);
799 		goto done_nolock;
800 	default:
801 		break;
802 	}
803 
804 	reinit_completion(&dev->cmd_complete);
805 	dev->msgs = msgs;
806 	dev->msgs_num = num;
807 	dev->cmd_err = 0;
808 	dev->msg_write_idx = 0;
809 	dev->msg_read_idx = 0;
810 	dev->msg_err = 0;
811 	dev->status = 0;
812 	dev->abort_source = 0;
813 	dev->rx_outstanding = 0;
814 
815 	ret = i2c_dw_acquire_lock(dev);
816 	if (ret)
817 		goto done_nolock;
818 
819 	ret = i2c_dw_wait_bus_not_busy(dev);
820 	if (ret < 0)
821 		goto done;
822 
823 	/* Start the transfers */
824 	i2c_dw_xfer_init(dev);
825 
826 	/* Wait for tx to complete */
827 	ret = i2c_dw_wait_transfer(dev);
828 	if (ret) {
829 		dev_err(dev->dev, "controller timed out\n");
830 		/* i2c_dw_init_master() implicitly disables the adapter */
831 		i2c_recover_bus(&dev->adapter);
832 		i2c_dw_init_master(dev);
833 		goto done;
834 	}
835 
836 	/*
837 	 * This happens rarely (~1:500) and is hard to reproduce. Debug trace
838 	 * showed that IC_STATUS had value of 0x23 when STOP_DET occurred,
839 	 * if disable IC_ENABLE.ENABLE immediately that can result in
840 	 * IC_RAW_INTR_STAT.MASTER_ON_HOLD holding SCL low. Check if
841 	 * controller is still ACTIVE before disabling I2C.
842 	 */
843 	if (i2c_dw_is_controller_active(dev))
844 		dev_err(dev->dev, "controller active\n");
845 
846 	/*
847 	 * We must disable the adapter before returning and signaling the end
848 	 * of the current transfer. Otherwise the hardware might continue
849 	 * generating interrupts which in turn causes a race condition with
850 	 * the following transfer. Needs some more investigation if the
851 	 * additional interrupts are a hardware bug or this driver doesn't
852 	 * handle them correctly yet.
853 	 */
854 	__i2c_dw_disable_nowait(dev);
855 
856 	if (dev->msg_err) {
857 		ret = dev->msg_err;
858 		goto done;
859 	}
860 
861 	/* No error */
862 	if (likely(!dev->cmd_err && !dev->status)) {
863 		ret = num;
864 		goto done;
865 	}
866 
867 	/* We have an error */
868 	if (dev->cmd_err == DW_IC_ERR_TX_ABRT) {
869 		ret = i2c_dw_handle_tx_abort(dev);
870 		goto done;
871 	}
872 
873 	if (dev->status)
874 		dev_err(dev->dev,
875 			"transfer terminated early - interrupt latency too high?\n");
876 
877 	ret = -EIO;
878 
879 done:
880 	i2c_dw_release_lock(dev);
881 
882 done_nolock:
883 	pm_runtime_mark_last_busy(dev->dev);
884 	pm_runtime_put_autosuspend(dev->dev);
885 
886 	return ret;
887 }
888 
889 static const struct i2c_algorithm i2c_dw_algo = {
890 	.master_xfer = i2c_dw_xfer,
891 	.functionality = i2c_dw_func,
892 };
893 
894 static const struct i2c_adapter_quirks i2c_dw_quirks = {
895 	.flags = I2C_AQ_NO_ZERO_LEN,
896 };
897 
898 void i2c_dw_configure_master(struct dw_i2c_dev *dev)
899 {
900 	struct i2c_timings *t = &dev->timings;
901 
902 	dev->functionality = I2C_FUNC_10BIT_ADDR | DW_IC_DEFAULT_FUNCTIONALITY;
903 
904 	dev->master_cfg = DW_IC_CON_MASTER | DW_IC_CON_SLAVE_DISABLE |
905 			  DW_IC_CON_RESTART_EN;
906 
907 	dev->mode = DW_IC_MASTER;
908 
909 	switch (t->bus_freq_hz) {
910 	case I2C_MAX_STANDARD_MODE_FREQ:
911 		dev->master_cfg |= DW_IC_CON_SPEED_STD;
912 		break;
913 	case I2C_MAX_HIGH_SPEED_MODE_FREQ:
914 		dev->master_cfg |= DW_IC_CON_SPEED_HIGH;
915 		break;
916 	default:
917 		dev->master_cfg |= DW_IC_CON_SPEED_FAST;
918 	}
919 }
920 EXPORT_SYMBOL_GPL(i2c_dw_configure_master);
921 
922 static void i2c_dw_prepare_recovery(struct i2c_adapter *adap)
923 {
924 	struct dw_i2c_dev *dev = i2c_get_adapdata(adap);
925 
926 	i2c_dw_disable(dev);
927 	reset_control_assert(dev->rst);
928 	i2c_dw_prepare_clk(dev, false);
929 }
930 
931 static void i2c_dw_unprepare_recovery(struct i2c_adapter *adap)
932 {
933 	struct dw_i2c_dev *dev = i2c_get_adapdata(adap);
934 
935 	i2c_dw_prepare_clk(dev, true);
936 	reset_control_deassert(dev->rst);
937 	i2c_dw_init_master(dev);
938 }
939 
940 static int i2c_dw_init_recovery_info(struct dw_i2c_dev *dev)
941 {
942 	struct i2c_bus_recovery_info *rinfo = &dev->rinfo;
943 	struct i2c_adapter *adap = &dev->adapter;
944 	struct gpio_desc *gpio;
945 
946 	gpio = devm_gpiod_get_optional(dev->dev, "scl", GPIOD_OUT_HIGH);
947 	if (IS_ERR_OR_NULL(gpio))
948 		return PTR_ERR_OR_ZERO(gpio);
949 
950 	rinfo->scl_gpiod = gpio;
951 
952 	gpio = devm_gpiod_get_optional(dev->dev, "sda", GPIOD_IN);
953 	if (IS_ERR(gpio))
954 		return PTR_ERR(gpio);
955 	rinfo->sda_gpiod = gpio;
956 
957 	rinfo->pinctrl = devm_pinctrl_get(dev->dev);
958 	if (IS_ERR(rinfo->pinctrl)) {
959 		if (PTR_ERR(rinfo->pinctrl) == -EPROBE_DEFER)
960 			return PTR_ERR(rinfo->pinctrl);
961 
962 		rinfo->pinctrl = NULL;
963 		dev_err(dev->dev, "getting pinctrl info failed: bus recovery might not work\n");
964 	} else if (!rinfo->pinctrl) {
965 		dev_dbg(dev->dev, "pinctrl is disabled, bus recovery might not work\n");
966 	}
967 
968 	rinfo->recover_bus = i2c_generic_scl_recovery;
969 	rinfo->prepare_recovery = i2c_dw_prepare_recovery;
970 	rinfo->unprepare_recovery = i2c_dw_unprepare_recovery;
971 	adap->bus_recovery_info = rinfo;
972 
973 	dev_info(dev->dev, "running with GPIO recovery mode! scl%s",
974 		 rinfo->sda_gpiod ? ",sda" : "");
975 
976 	return 0;
977 }
978 
979 int i2c_dw_probe_master(struct dw_i2c_dev *dev)
980 {
981 	struct i2c_adapter *adap = &dev->adapter;
982 	unsigned long irq_flags;
983 	unsigned int ic_con;
984 	int ret;
985 
986 	init_completion(&dev->cmd_complete);
987 
988 	dev->init = i2c_dw_init_master;
989 
990 	ret = i2c_dw_init_regmap(dev);
991 	if (ret)
992 		return ret;
993 
994 	ret = i2c_dw_set_timings_master(dev);
995 	if (ret)
996 		return ret;
997 
998 	ret = i2c_dw_set_fifo_size(dev);
999 	if (ret)
1000 		return ret;
1001 
1002 	/* Lock the bus for accessing DW_IC_CON */
1003 	ret = i2c_dw_acquire_lock(dev);
1004 	if (ret)
1005 		return ret;
1006 
1007 	/*
1008 	 * On AMD platforms BIOS advertises the bus clear feature
1009 	 * and enables the SCL/SDA stuck low. SMU FW does the
1010 	 * bus recovery process. Driver should not ignore this BIOS
1011 	 * advertisement of bus clear feature.
1012 	 */
1013 	ret = regmap_read(dev->map, DW_IC_CON, &ic_con);
1014 	i2c_dw_release_lock(dev);
1015 	if (ret)
1016 		return ret;
1017 
1018 	if (ic_con & DW_IC_CON_BUS_CLEAR_CTRL)
1019 		dev->master_cfg |= DW_IC_CON_BUS_CLEAR_CTRL;
1020 
1021 	ret = dev->init(dev);
1022 	if (ret)
1023 		return ret;
1024 
1025 	snprintf(adap->name, sizeof(adap->name),
1026 		 "Synopsys DesignWare I2C adapter");
1027 	adap->retries = 3;
1028 	adap->algo = &i2c_dw_algo;
1029 	adap->quirks = &i2c_dw_quirks;
1030 	adap->dev.parent = dev->dev;
1031 	i2c_set_adapdata(adap, dev);
1032 
1033 	if (dev->flags & ACCESS_NO_IRQ_SUSPEND) {
1034 		irq_flags = IRQF_NO_SUSPEND;
1035 	} else {
1036 		irq_flags = IRQF_SHARED | IRQF_COND_SUSPEND;
1037 	}
1038 
1039 	ret = i2c_dw_acquire_lock(dev);
1040 	if (ret)
1041 		return ret;
1042 
1043 	__i2c_dw_write_intr_mask(dev, 0);
1044 	i2c_dw_release_lock(dev);
1045 
1046 	if (!(dev->flags & ACCESS_POLLING)) {
1047 		ret = devm_request_irq(dev->dev, dev->irq, i2c_dw_isr,
1048 				       irq_flags, dev_name(dev->dev), dev);
1049 		if (ret) {
1050 			dev_err(dev->dev, "failure requesting irq %i: %d\n",
1051 				dev->irq, ret);
1052 			return ret;
1053 		}
1054 	}
1055 
1056 	ret = i2c_dw_init_recovery_info(dev);
1057 	if (ret)
1058 		return ret;
1059 
1060 	/*
1061 	 * Increment PM usage count during adapter registration in order to
1062 	 * avoid possible spurious runtime suspend when adapter device is
1063 	 * registered to the device core and immediate resume in case bus has
1064 	 * registered I2C slaves that do I2C transfers in their probe.
1065 	 */
1066 	pm_runtime_get_noresume(dev->dev);
1067 	ret = i2c_add_numbered_adapter(adap);
1068 	if (ret)
1069 		dev_err(dev->dev, "failure adding adapter: %d\n", ret);
1070 	pm_runtime_put_noidle(dev->dev);
1071 
1072 	return ret;
1073 }
1074 EXPORT_SYMBOL_GPL(i2c_dw_probe_master);
1075 
1076 MODULE_DESCRIPTION("Synopsys DesignWare I2C bus master adapter");
1077 MODULE_LICENSE("GPL");
1078 MODULE_IMPORT_NS(I2C_DW_COMMON);
1079