summaryrefslogtreecommitdiffstats
path: root/src/ec/google/chromeec/ec_spi.c
blob: ecf1b420fe9304733e8327df320203c27c6a6152 (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
/* SPDX-License-Identifier: GPL-2.0-only */

#include <console/console.h>
#include <delay.h>
#include "ec.h"
#include "ec_commands.h"
#include <spi-generic.h>
#include <timer.h>

static struct stopwatch cs_cooldown_sw;
static const long cs_cooldown_us = 200;

static const uint8_t EcFramingByte = 0xec;

#define PROTO3_MAX_PACKET_SIZE 268

static uint8_t req_buf[PROTO3_MAX_PACKET_SIZE];
static uint8_t resp_buf[PROTO3_MAX_PACKET_SIZE];

void *crosec_get_buffer(size_t size, int req)
{
	if (size > PROTO3_MAX_PACKET_SIZE) {
		printk(BIOS_DEBUG, "Proto v3 buffer request too large: %zu!\n",
			size);
		return NULL;
	}

	if (req)
		return req_buf;
	else
		return resp_buf;
}

static int crosec_spi_io(size_t req_size, size_t resp_size, void *context)
{
	struct spi_slave *slave = (struct spi_slave *)context;
	int ret = 0;

	/* Wait minimum delay between CS assertions. */
	stopwatch_wait_until_expired(&cs_cooldown_sw);

	spi_claim_bus(slave);

	 /* Allow EC to ramp up clock after being awaken.
	  * See chrome-os-partner:32223 for more details. */
	udelay(CONFIG_EC_GOOGLE_CHROMEEC_SPI_WAKEUP_DELAY_US);

	if (spi_xfer(slave, req_buf, req_size, NULL, 0)) {
		printk(BIOS_ERR, "%s: Failed to send request.\n", __func__);
		ret = -1;
		goto out;
	}

	uint8_t byte;
	struct stopwatch sw;
	// Wait 1s for a framing byte.
	stopwatch_init_usecs_expire(&sw, USECS_PER_SEC);
	while (1) {
		if (spi_xfer(slave, NULL, 0, &byte, sizeof(byte))) {
			printk(BIOS_ERR, "%s: Failed to receive byte.\n",
			       __func__);
			ret = -1;
			goto out;
		}
		if (byte == EcFramingByte)
			break;

		if (stopwatch_expired(&sw)) {
			printk(BIOS_ERR,
			       "%s: Timeout waiting for framing byte.\n",
			       __func__);
			ret = -1;
			goto out;
		}
	}

	if (spi_xfer(slave, NULL, 0, resp_buf, resp_size)) {
		printk(BIOS_ERR, "%s: Failed to receive response.\n", __func__);
		ret = -1;
	}

out:
	spi_release_bus(slave);
	stopwatch_init_usecs_expire(&cs_cooldown_sw, cs_cooldown_us);
	return ret;
}

int google_chromeec_command(struct chromeec_command *cec_command)
{
	static int done = 0;
	static struct spi_slave slave;

	if (!done) {
		if (spi_setup_slave(CONFIG_EC_GOOGLE_CHROMEEC_SPI_BUS,
				    CONFIG_EC_GOOGLE_CHROMEEC_SPI_CHIP, &slave))
			return -1;
		stopwatch_init(&cs_cooldown_sw);
		done = 1;
	}
	return crosec_command_proto(cec_command, crosec_spi_io, &slave);
}

u8 google_chromeec_get_event(void)
{
	printk(BIOS_ERR, "%s: Not supported.\n", __func__);
	return 0;
}