summaryrefslogtreecommitdiff
path: root/chip/lm4/i2c.c
blob: 510b8aaa1d06d3a5d90c597f64e69df1fce4027d (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
/* Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

/* I2C port module for Chrome EC */

#include "clock.h"
#include "common.h"
#include "console.h"
#include "gpio.h"
#include "hooks.h"
#include "i2c.h"
#include "registers.h"
#include "task.h"
#include "timer.h"
#include "util.h"

#define CPUTS(outstr) cputs(CC_I2C, outstr)
#define CPRINTF(format, args...) cprintf(CC_I2C, format, ## args)

/* Flags for writes to MCS */
#define LM4_I2C_MCS_RUN   (1 << 0)
#define LM4_I2C_MCS_START (1 << 1)
#define LM4_I2C_MCS_STOP  (1 << 2)
#define LM4_I2C_MCS_ACK   (1 << 3)
#define LM4_I2C_MCS_HS    (1 << 4)
#define LM4_I2C_MCS_QCMD  (1 << 5)

/* Flags for reads from MCS */
#define LM4_I2C_MCS_BUSY   (1 << 0)
#define LM4_I2C_MCS_ERROR  (1 << 1)
#define LM4_I2C_MCS_ADRACK (1 << 2)
#define LM4_I2C_MCS_DATACK (1 << 3)
#define LM4_I2C_MCS_ARBLST (1 << 4)
#define LM4_I2C_MCS_IDLE   (1 << 5)
#define LM4_I2C_MCS_BUSBSY (1 << 6)
#define LM4_I2C_MCS_CLKTO  (1 << 7)

/*
 * Minimum delay between resetting the port or sending a stop condition, and
 * when the port can be expected to be back in an idle state (and the slave
 * has had long enough to see the start/stop condition edges).
 *
 * 500 us = 50 clocks at 100 KHz bus speed.  This has been experimentally
 * determined to be enough.
 */
#define I2C_IDLE_US 500

/* Maximum time we allow for an I2C transfer */
#define I2C_TIMEOUT_US SECOND

/* IRQ for each port */
static const uint32_t i2c_irqs[] = {LM4_IRQ_I2C0, LM4_IRQ_I2C1, LM4_IRQ_I2C2,
				    LM4_IRQ_I2C3, LM4_IRQ_I2C4, LM4_IRQ_I2C5};
BUILD_ASSERT(ARRAY_SIZE(i2c_irqs) == I2C_PORT_COUNT);

/* I2C port state data */
struct i2c_port_data {
	const uint8_t *out;	/* Output data pointer */
	int out_size;		/* Output data to transfer, in bytes */
	uint8_t *in;		/* Input data pointer */
	int in_size;		/* Input data to transfer, in bytes */
	int flags;		/* Flags (I2C_XFER_*) */
	int idx;		/* Index into input/output data */
	int err;		/* Error code, if any */

	/* Task waiting on port, or TASK_ID_INVALID if none. */
	int task_waiting;
};
static struct i2c_port_data pdata[I2C_PORT_COUNT];

/**
 * I2C transfer engine.
 *
 * @return Zero when done with transfer (ready to wake task).
 *
 * MCS sequence on multi-byte write:
 *     0x3 0x1 0x1 ... 0x1 0x5
 * Single byte write:
 *     0x7
 *
 * MCS receive sequence on multi-byte read:
 *     0xb 0x9 0x9 ... 0x9 0x5
 * Single byte read:
 *     0x7
 */
int i2c_do_work(int port)
{
	struct i2c_port_data *pd = pdata + port;
	uint32_t reg_mcs = LM4_I2C_MCS_RUN;

	if (pd->flags & I2C_XFER_START) {
		/* Set start bit on first byte */
		reg_mcs |= LM4_I2C_MCS_START;
		pd->flags &= ~I2C_XFER_START;
	} else if (LM4_I2C_MCS(port) & (LM4_I2C_MCS_CLKTO | LM4_I2C_MCS_ARBLST |
					LM4_I2C_MCS_ERROR)) {
		/*
		 * Error after starting; abort transfer.  Ignore errors at
		 * start because arbitration and timeout errors are taken care
		 * of in i2c_xfer(), and slave ack failures will automatically
		 * clear once we send a start condition.
		 */
		pd->err = EC_ERROR_UNKNOWN;
		return 0;
	}

	if (pd->out_size) {
		/* Send next byte of output */
		LM4_I2C_MDR(port) = *(pd->out++);
		pd->idx++;

		/* Handle starting to send last byte */
		if (pd->idx == pd->out_size) {

			/* Done with output after this */
			pd->out_size = 0;
			pd->idx = 0;

			/* Resend start bit when changing direction */
			pd->flags |= I2C_XFER_START;

			/*
			 * Send stop bit after last byte if the stop flag is
			 * on, and caller doesn't expect to receive data.
			 */
			if ((pd->flags & I2C_XFER_STOP) && pd->in_size == 0)
				reg_mcs |= LM4_I2C_MCS_STOP;
		}

		LM4_I2C_MCS(port) = reg_mcs;
		return 1;

	} else if (pd->in_size) {
		if (pd->idx) {
			/* Copy the byte we just read */
			*(pd->in++) = LM4_I2C_MDR(port) & 0xff;
		} else {
			/* Starting receive; switch to receive address */
			LM4_I2C_MSA(port) |= 0x01;
		}

		if (pd->idx < pd->in_size) {
			/* More data to read */
			pd->idx++;

			/* ACK all bytes except the last one */
			if ((pd->flags & I2C_XFER_STOP) &&
			    pd->idx == pd->in_size)
				reg_mcs |= LM4_I2C_MCS_STOP;
			else
				reg_mcs |= LM4_I2C_MCS_ACK;

			LM4_I2C_MCS(port) = reg_mcs;
			return 1;
		}
	}

	/* If we're still here, done with transfer */
	return 0;
}

int i2c_get_line_levels(int port)
{
	/* Conveniently, MBMON bit (1 << 1) is SDA and (1 << 0) is SCL. */
	return LM4_I2C_MBMON(port) & 0x03;
}

int i2c_xfer(int port, int slave_addr, const uint8_t *out, int out_size,
	     uint8_t *in, int in_size, int flags)
{
	struct i2c_port_data *pd = pdata + port;
	uint32_t reg_mcs = LM4_I2C_MCS(port);
	int events = 0;
	int other_events = 0;

	if (out_size == 0 && in_size == 0)
		return EC_SUCCESS;

	/* Copy data to port struct */
	pd->out = out;
	pd->out_size = out_size;
	pd->in = in;
	pd->in_size = in_size;
	pd->flags = flags;
	pd->idx = 0;
	pd->err = 0;

	/* Make sure we're in a good state to start */
	if ((flags & I2C_XFER_START) &&
	    (reg_mcs & (LM4_I2C_MCS_CLKTO | LM4_I2C_MCS_ARBLST))) {
		uint32_t tpr = LM4_I2C_MTPR(port);

		CPRINTF("[%T I2C%d bad status 0x%02x]\n", port, reg_mcs);

		/* Clock timeout or arbitration lost.  Reset port to clear. */
		LM4_SYSTEM_SRI2C |= (1 << port);
		clock_wait_cycles(3);
		LM4_SYSTEM_SRI2C &= ~(1 << port);
		clock_wait_cycles(3);

		/* Restore settings */
		LM4_I2C_MCR(port) = 0x10;
		LM4_I2C_MTPR(port) = tpr;

		/*
		 * We don't know what edges the slave saw, so sleep long enough
		 * that the slave will see the new start condition below.
		 */
		usleep(I2C_IDLE_US);
	}

	/* Set slave address for transmit */
	LM4_I2C_MSA(port) = slave_addr & 0xff;

	/* Enable interrupts */
	pd->task_waiting = task_get_current();
	LM4_I2C_MICR(port) = 0x03;
	LM4_I2C_MIMR(port) = 0x03;

	/* Kick the port interrupt handler to start the transfer */
	task_trigger_irq(i2c_irqs[port]);

	/* Wait for transfer complete or timeout */
	while (!(events & (TASK_EVENT_I2C_IDLE | TASK_EVENT_TIMER))) {
		/*
		 * We could be clever and track how long we were actually
		 * asleep, and wait for the remainder if we were woken up
		 * for some other event.  But that would consume additional
		 * stack space and processing time for the infrequent case
		 * of an I2C timeout, so isn't worth it.
		 */
		events = task_wait_event(I2C_TIMEOUT_US);

		/*
		 * We want to wait here quietly until the transaction is
		 * complete, but we don't want to lose any pending events that
		 * will be needed by the task that started the I2C transaction
		 * in the first place. So we save them up and restore them on
		 * completion or timeout. See the usleep() implementation for a
		 * similar situation.
		 */
		other_events |= events &
			~(TASK_EVENT_I2C_IDLE | TASK_EVENT_TIMER);
	}

	/* Disable interrupts */
	LM4_I2C_MIMR(port) = 0x00;
	pd->task_waiting = TASK_ID_INVALID;

	/* Restore any events that we saw while waiting */
	task_set_event(task_get_current(), other_events, 0);

	/* Handle timeout */
	if (events & TASK_EVENT_TIMER)
		pd->err = EC_ERROR_TIMEOUT;

	if (pd->err) {
		/* Force port back idle */
		LM4_I2C_MCS(port) = LM4_I2C_MCS_STOP;
		usleep(I2C_IDLE_US);
	}

	return pd->err;
}

int i2c_read_string(int port, int slave_addr, int offset, uint8_t *data,
		    int len)
{
	int rv;
	uint8_t reg, block_length;

	i2c_lock(port, 1);

	reg = offset;
	/*
	 * Send device reg space offset, and read back block length.  Keep this
	 * session open without a stop.
	 */
	rv = i2c_xfer(port, slave_addr, &reg, 1, &block_length, 1,
		      I2C_XFER_START);
	if (rv)
		goto exit;

	if (len && block_length > (len - 1))
		block_length = len - 1;

	rv = i2c_xfer(port, slave_addr, 0, 0, data, block_length,
		      I2C_XFER_STOP);
	data[block_length] = 0;

exit:
	i2c_lock(port, 0);
	return rv;
}

/*****************************************************************************/
/* Hooks */

static void i2c_freq_changed(void)
{
	int freq = clock_get_freq();
	int i;

	for (i = 0; i < i2c_ports_used; i++) {
		/*
		 * From datasheet:
		 *     SCL_PRD = 2 * (1 + TPR) * (SCL_LP + SCL_HP) * CLK_PRD
		 *
		 * so:
		 *     TPR = SCL_PRD / (2 * (SCL_LP + SCL_HP) * CLK_PRD) - 1
		 *
		 * converting from period to frequency:
		 *     TPR = CLK_FREQ / (SCL_FREQ * 2 * (SCL_LP + SCL_HP)) - 1
		 */
		const int d = 2 * (6 + 4) * (i2c_ports[i].kbps * 1000);

		/* Round TPR up, so desired kbps is an upper bound */
		const int tpr = (freq + d - 1) / d - 1;

#ifdef PRINT_I2C_SPEEDS
		const int f = freq / (2 * (1 + tpr) * (6 + 4));
		CPRINTF("[%T I2C%d clk=%d tpr=%d freq=%d]\n",
			i2c_ports[i].port, freq, tpr, f);
#endif

		LM4_I2C_MTPR(i2c_ports[i].port) = tpr;
	}
}
DECLARE_HOOK(HOOK_FREQ_CHANGE, i2c_freq_changed, HOOK_PRIO_DEFAULT);

static void i2c_init(void)
{
	uint32_t mask = 0;
	int i;

	/* Enable I2C modules in run and sleep modes. */
	for (i = 0; i < i2c_ports_used; i++)
		mask |= 1 << i2c_ports[i].port;

	clock_enable_peripheral(CGC_OFFSET_I2C, mask,
			CGC_MODE_RUN | CGC_MODE_SLEEP);

	/* Configure GPIOs */
	gpio_config_module(MODULE_I2C, 1);

	/* Initialize ports as master, with interrupts enabled */
	for (i = 0; i < i2c_ports_used; i++)
		LM4_I2C_MCR(i2c_ports[i].port) = 0x10;

	/* Set initial clock frequency */
	i2c_freq_changed();

	/* Enable IRQs; no tasks are waiting on ports */
	for (i = 0; i < I2C_PORT_COUNT; i++) {
		pdata[i].task_waiting = TASK_ID_INVALID;
		task_enable_irq(i2c_irqs[i]);
	}
}
DECLARE_HOOK(HOOK_INIT, i2c_init, HOOK_PRIO_DEFAULT);

/**
 * Handle an interrupt on the specified port.
 *
 * @param port		I2C port generating interrupt
 */
static void handle_interrupt(int port)
{
	int id = pdata[port].task_waiting;

	/* Clear the interrupt status */
	LM4_I2C_MICR(port) = LM4_I2C_MMIS(port);

	/* If no task is waiting, just return */
	if (id == TASK_ID_INVALID)
		return;

	/* If done doing work, wake up the task waiting for the transfer */
	if (!i2c_do_work(port))
		task_set_event(id, TASK_EVENT_I2C_IDLE, 0);
}

static void i2c0_interrupt(void) { handle_interrupt(0); }
static void i2c1_interrupt(void) { handle_interrupt(1); }
static void i2c2_interrupt(void) { handle_interrupt(2); }
static void i2c3_interrupt(void) { handle_interrupt(3); }
static void i2c4_interrupt(void) { handle_interrupt(4); }
static void i2c5_interrupt(void) { handle_interrupt(5); }

DECLARE_IRQ(LM4_IRQ_I2C0, i2c0_interrupt, 2);
DECLARE_IRQ(LM4_IRQ_I2C1, i2c1_interrupt, 2);
DECLARE_IRQ(LM4_IRQ_I2C2, i2c2_interrupt, 2);
DECLARE_IRQ(LM4_IRQ_I2C3, i2c3_interrupt, 2);
DECLARE_IRQ(LM4_IRQ_I2C4, i2c4_interrupt, 2);
DECLARE_IRQ(LM4_IRQ_I2C5, i2c5_interrupt, 2);