1 /*
2  * Copyright (c) 2017 Linaro Limited
3  * Copyright (c) 2016 Nordic Semiconductor ASA
4  * Copyright (c) 2015-2016 Intel Corporation
5  *
6  * SPDX-License-Identifier: Apache-2.0
7  */
8 
9 #include <errno.h>
10 #include <stddef.h>
11 #include <stdio.h>
12 
13 #include <zephyr/kernel.h>
14 #include <zephyr/sys/byteorder.h>
15 #include <zephyr/logging/log.h>
16 #include <zephyr/debug/stack.h>
17 
18 #include <zephyr/device.h>
19 #include <zephyr/init.h>
20 #include <zephyr/drivers/gpio.h>
21 #include <zephyr/drivers/spi.h>
22 
23 #include <zephyr/net/buf.h>
24 #include <zephyr/bluetooth/bluetooth.h>
25 #include <zephyr/bluetooth/l2cap.h>
26 #include <zephyr/bluetooth/hci.h>
27 #include <zephyr/bluetooth/buf.h>
28 #include <zephyr/bluetooth/hci_raw.h>
29 
30 #define LOG_MODULE_NAME hci_spi
31 LOG_MODULE_REGISTER(LOG_MODULE_NAME);
32 
33 #define HCI_CMD                0x01
34 #define HCI_ACL                0x02
35 #define HCI_SCO                0x03
36 #define HCI_EVT                0x04
37 
38 /* Special Values */
39 #define SPI_WRITE              0x0A
40 #define SPI_READ               0x0B
41 #define READY_NOW              0x02
42 #define SANITY_CHECK           0x02
43 
44 /* Offsets */
45 #define STATUS_HEADER_READY    0
46 #define STATUS_HEADER_TOREAD   3
47 
48 #define PACKET_TYPE            0
49 #define EVT_BLUE_INITIALIZED   0x01
50 
51 /* Needs to be aligned with the SPI master buffer size */
52 #define SPI_MAX_MSG_LEN        255
53 
54 static uint8_t rxmsg[SPI_MAX_MSG_LEN];
55 static struct spi_buf rx;
56 const static struct spi_buf_set rx_bufs = {
57 	.buffers = &rx,
58 	.count = 1,
59 };
60 
61 static uint8_t txmsg[SPI_MAX_MSG_LEN];
62 static struct spi_buf tx;
63 const static struct spi_buf_set tx_bufs = {
64 	.buffers = &tx,
65 	.count = 1,
66 };
67 
68 /* HCI buffer pools */
69 #define CMD_BUF_SIZE BT_BUF_RX_SIZE
70 
71 /*
72  * This finds an arbitrary node with compatible
73  * "zephyr,bt-hci-spi-slave". There should just be one in the
74  * devicetree.
75  *
76  * If for some reason you have more than one of these in your
77  * devicetree, replace this macro definition to pick one, e.g. using
78  * DT_NODELABEL().
79  */
80 #define HCI_SPI_NODE           DT_COMPAT_GET_ANY_STATUS_OKAY(zephyr_bt_hci_spi_slave)
81 
82 /*
83  * This is the SPI bus controller device used to exchange data with
84  * the SPI-based BT controller.
85  */
86 static const struct device *const spi_hci_dev = DEVICE_DT_GET(DT_BUS(HCI_SPI_NODE));
87 static struct spi_config spi_cfg = {
88 	.operation = SPI_WORD_SET(8) | SPI_OP_MODE_SLAVE,
89 };
90 
91 /*
92  * The GPIO used to send interrupts to the host,
93  * configured in the 'irq-gpios' property in HCI_SPI_NODE.
94  */
95 static const struct gpio_dt_spec irq = GPIO_DT_SPEC_GET(HCI_SPI_NODE, irq_gpios);
96 
97 static K_THREAD_STACK_DEFINE(bt_tx_thread_stack, CONFIG_BT_HCI_TX_STACK_SIZE);
98 static struct k_thread bt_tx_thread_data;
99 
100 static K_SEM_DEFINE(sem_spi_rx, 0, 1);
101 static K_SEM_DEFINE(sem_spi_tx, 0, 1);
102 
spi_send(struct net_buf * buf)103 static inline int spi_send(struct net_buf *buf)
104 {
105 	uint8_t header_master[5] = { 0 };
106 	uint8_t header_slave[5] = { READY_NOW, SANITY_CHECK,
107 				    0x00, 0x00, 0x00 };
108 	int ret;
109 
110 	LOG_DBG("buf %p type %u len %u", buf, bt_buf_get_type(buf), buf->len);
111 
112 	switch (bt_buf_get_type(buf)) {
113 	case BT_BUF_ACL_IN:
114 		net_buf_push_u8(buf, HCI_ACL);
115 		break;
116 	case BT_BUF_EVT:
117 		net_buf_push_u8(buf, HCI_EVT);
118 		break;
119 	default:
120 		LOG_ERR("Unknown type %u", bt_buf_get_type(buf));
121 		net_buf_unref(buf);
122 		return -EINVAL;
123 	}
124 
125 	if (buf->len > SPI_MAX_MSG_LEN) {
126 		LOG_ERR("TX message too long");
127 		net_buf_unref(buf);
128 		return -EINVAL;
129 	}
130 	header_slave[STATUS_HEADER_TOREAD] = buf->len;
131 
132 	gpio_pin_set(irq.port, irq.pin, 1);
133 
134 	/* Coordinate transfer lock with the spi rx thread */
135 	k_sem_take(&sem_spi_tx, K_FOREVER);
136 
137 	tx.buf = header_slave;
138 	tx.len = 5;
139 	rx.buf = header_master;
140 	rx.len = 5;
141 	do {
142 		ret = spi_transceive(spi_hci_dev, &spi_cfg, &tx_bufs, &rx_bufs);
143 		if (ret < 0) {
144 			LOG_ERR("SPI transceive error: %d", ret);
145 		}
146 	} while (header_master[STATUS_HEADER_READY] != SPI_READ);
147 
148 	tx.buf = buf->data;
149 	tx.len = buf->len;
150 
151 	ret = spi_write(spi_hci_dev, &spi_cfg, &tx_bufs);
152 	if (ret < 0) {
153 		LOG_ERR("SPI transceive error: %d", ret);
154 	}
155 	net_buf_unref(buf);
156 
157 	gpio_pin_set(irq.port, irq.pin, 0);
158 	k_sem_give(&sem_spi_rx);
159 
160 	return 0;
161 }
162 
bt_tx_thread(void * p1,void * p2,void * p3)163 static void bt_tx_thread(void *p1, void *p2, void *p3)
164 {
165 	uint8_t header_master[5];
166 	uint8_t header_slave[5] = { READY_NOW, SANITY_CHECK,
167 				    0x00, 0x00, 0x00 };
168 	struct net_buf *buf = NULL;
169 
170 	union {
171 		struct bt_hci_cmd_hdr *cmd_hdr;
172 		struct bt_hci_acl_hdr *acl_hdr;
173 	} hci_hdr;
174 	hci_hdr.cmd_hdr = (struct bt_hci_cmd_hdr *)&rxmsg[1];
175 	int ret;
176 
177 	ARG_UNUSED(p1);
178 	ARG_UNUSED(p2);
179 	ARG_UNUSED(p3);
180 
181 	(void)memset(txmsg, 0xFF, SPI_MAX_MSG_LEN);
182 
183 	while (1) {
184 		tx.buf = header_slave;
185 		tx.len = 5;
186 		rx.buf = header_master;
187 		rx.len = 5;
188 
189 		do {
190 			ret = spi_transceive(spi_hci_dev, &spi_cfg,
191 					     &tx_bufs, &rx_bufs);
192 			if (ret < 0) {
193 				LOG_ERR("SPI transceive error: %d", ret);
194 			}
195 		} while ((header_master[STATUS_HEADER_READY] != SPI_READ) &&
196 			 (header_master[STATUS_HEADER_READY] != SPI_WRITE));
197 
198 		if (header_master[STATUS_HEADER_READY] == SPI_READ) {
199 			/* Unblock the spi tx thread and wait for it */
200 			k_sem_give(&sem_spi_tx);
201 			k_sem_take(&sem_spi_rx, K_FOREVER);
202 			continue;
203 		}
204 
205 		tx.buf = txmsg;
206 		tx.len = SPI_MAX_MSG_LEN;
207 		rx.buf = rxmsg;
208 		rx.len = SPI_MAX_MSG_LEN;
209 
210 		/* Receiving data from the SPI Host */
211 		ret = spi_transceive(spi_hci_dev, &spi_cfg,
212 				     &tx_bufs, &rx_bufs);
213 		if (ret < 0) {
214 			LOG_ERR("SPI transceive error: %d", ret);
215 			continue;
216 		}
217 
218 		switch (rxmsg[PACKET_TYPE]) {
219 		case HCI_CMD:
220 			buf = bt_buf_get_tx(BT_BUF_CMD, K_NO_WAIT,
221 					    hci_hdr.cmd_hdr,
222 					    sizeof(*hci_hdr.cmd_hdr));
223 			if (buf) {
224 				net_buf_add_mem(buf, &rxmsg[4],
225 						hci_hdr.cmd_hdr->param_len);
226 			} else {
227 				LOG_ERR("No available command buffers!");
228 				continue;
229 			}
230 			break;
231 		case HCI_ACL:
232 			buf = bt_buf_get_tx(BT_BUF_ACL_OUT, K_NO_WAIT,
233 					    hci_hdr.acl_hdr,
234 					    sizeof(*hci_hdr.acl_hdr));
235 			if (buf) {
236 				net_buf_add_mem(buf, &rxmsg[5],
237 						sys_le16_to_cpu(hci_hdr.acl_hdr->len));
238 			} else {
239 				LOG_ERR("No available ACL buffers!");
240 				continue;
241 			}
242 			break;
243 		default:
244 			LOG_ERR("Unknown BT HCI buf type");
245 			continue;
246 		}
247 
248 		LOG_DBG("buf %p type %u len %u",
249 			buf, bt_buf_get_type(buf), buf->len);
250 
251 		ret = bt_send(buf);
252 		if (ret) {
253 			LOG_ERR("Unable to send (ret %d)", ret);
254 			net_buf_unref(buf);
255 		}
256 
257 		/* Make sure other threads get a chance to run */
258 		k_yield();
259 	}
260 }
261 
hci_spi_init(void)262 static int hci_spi_init(void)
263 {
264 
265 	LOG_DBG("");
266 
267 	if (!device_is_ready(spi_hci_dev)) {
268 		LOG_ERR("SPI bus %s is not ready", spi_hci_dev->name);
269 		return -EINVAL;
270 	}
271 
272 	if (!gpio_is_ready_dt(&irq)) {
273 		LOG_ERR("IRQ GPIO port %s is not ready", irq.port->name);
274 		return -EINVAL;
275 	}
276 	gpio_pin_configure_dt(&irq, GPIO_OUTPUT_INACTIVE);
277 
278 	return 0;
279 }
280 
281 SYS_INIT(hci_spi_init, APPLICATION, CONFIG_KERNEL_INIT_PRIORITY_DEVICE);
282 
main(void)283 int main(void)
284 {
285 	static K_FIFO_DEFINE(rx_queue);
286 	struct bt_hci_evt_hdr *evt_hdr;
287 	struct net_buf *buf;
288 	k_tid_t tx_id;
289 	int err;
290 
291 	LOG_DBG("Start");
292 
293 	err = bt_enable_raw(&rx_queue);
294 	if (err) {
295 		LOG_ERR("bt_enable_raw: %d; aborting", err);
296 		return 0;
297 	}
298 
299 	/* Spawn the TX thread, which feeds cmds and data to the controller */
300 	tx_id = k_thread_create(&bt_tx_thread_data, bt_tx_thread_stack,
301 				K_THREAD_STACK_SIZEOF(bt_tx_thread_stack),
302 				bt_tx_thread, NULL, NULL, NULL, K_PRIO_COOP(7),
303 				0, K_NO_WAIT);
304 	k_thread_name_set(&bt_tx_thread_data, "bt_tx_thread");
305 
306 	/* Send a vendor event to announce that the slave is initialized */
307 	buf = bt_buf_get_rx(BT_BUF_EVT, K_FOREVER);
308 	evt_hdr = net_buf_add(buf, sizeof(*evt_hdr));
309 	evt_hdr->evt = BT_HCI_EVT_VENDOR;
310 	evt_hdr->len = 2U;
311 	net_buf_add_le16(buf, EVT_BLUE_INITIALIZED);
312 	err = spi_send(buf);
313 	if (err) {
314 		LOG_ERR("can't send initialization event; aborting");
315 		k_thread_abort(tx_id);
316 		return 0;
317 	}
318 
319 	while (1) {
320 		buf = net_buf_get(&rx_queue, K_FOREVER);
321 		err = spi_send(buf);
322 		if (err) {
323 			LOG_ERR("Failed to send");
324 		}
325 		/* Ensure that the IRQ line is de-asserted for some minimum
326 		 * duration between buffers, so that the HCI controller has
327 		 * time to observe the edge.
328 		 */
329 		k_sleep(K_TICKS(1));
330 	}
331 	return 0;
332 }
333