1 /* spi.c - SPI based Bluetooth driver */
2 
3 #define DT_DRV_COMPAT zephyr_bt_hci_spi
4 
5 /*
6  * Copyright (c) 2017 Linaro Ltd.
7  *
8  * SPDX-License-Identifier: Apache-2.0
9  */
10 
11 #include <zephyr/drivers/gpio.h>
12 #include <zephyr/init.h>
13 #include <zephyr/drivers/spi.h>
14 #include <zephyr/sys/byteorder.h>
15 #include <zephyr/sys/util.h>
16 
17 #include <zephyr/bluetooth/hci.h>
18 #include <zephyr/drivers/bluetooth.h>
19 
20 #define LOG_LEVEL CONFIG_BT_HCI_DRIVER_LOG_LEVEL
21 #include <zephyr/logging/log.h>
22 LOG_MODULE_REGISTER(bt_driver);
23 
24 /* Special Values */
25 #define SPI_WRITE		0x0A
26 #define SPI_READ		0x0B
27 #define READY_NOW		0x02
28 
29 #define EVT_BLUE_INITIALIZED	0x01
30 
31 /* Offsets */
32 #define STATUS_HEADER_READY	0
33 #define STATUS_HEADER_TOREAD	3
34 #define STATUS_HEADER_TOWRITE	1
35 
36 #define PACKET_TYPE		0
37 #define EVT_HEADER_TYPE		0
38 #define EVT_HEADER_EVENT	1
39 #define EVT_HEADER_SIZE		2
40 #define EVT_LE_META_SUBEVENT	3
41 #define EVT_VENDOR_CODE_LSB	3
42 #define EVT_VENDOR_CODE_MSB	4
43 
44 #define CMD_OGF			1
45 #define CMD_OCF			2
46 
47 /* Max SPI buffer length for transceive operations.
48  *
49  * Buffer size needs to be at least the size of the larger RX/TX buffer
50  * required by the SPI slave, as the legacy spi_transceive requires both RX/TX
51  * to be the same length. Size also needs to be compatible with the
52  * slave device used (e.g. nRF5X max buffer length for SPIS is 255).
53  */
54 #define SPI_MAX_MSG_LEN		255 /* As defined by X-NUCLEO-IDB04A1 BSP */
55 
56 #define DATA_DELAY_US DT_INST_PROP(0, controller_data_delay_us)
57 
58 /* Single byte header denoting the buffer type */
59 #define H4_HDR_SIZE 1
60 
61 /* Maximum L2CAP MTU that can fit in a single packet */
62 #define MAX_MTU (SPI_MAX_MSG_LEN - H4_HDR_SIZE - BT_L2CAP_HDR_SIZE - BT_HCI_ACL_HDR_SIZE)
63 
64 #if CONFIG_BT_L2CAP_TX_MTU > MAX_MTU
65 #warning CONFIG_BT_L2CAP_TX_MTU is too large and can result in packets that cannot \
66 	be transmitted across this HCI link
67 #endif /* CONFIG_BT_L2CAP_TX_MTU > MAX_MTU */
68 
69 struct bt_spi_data {
70 	bt_hci_recv_t recv;
71 };
72 
73 static uint8_t __noinit rxmsg[SPI_MAX_MSG_LEN];
74 static uint8_t __noinit txmsg[SPI_MAX_MSG_LEN];
75 
76 static const struct gpio_dt_spec irq_gpio = GPIO_DT_SPEC_INST_GET(0, irq_gpios);
77 static const struct gpio_dt_spec rst_gpio = GPIO_DT_SPEC_INST_GET(0, reset_gpios);
78 
79 static struct gpio_callback	gpio_cb;
80 
81 static K_SEM_DEFINE(sem_initialised, 0, 1);
82 static K_SEM_DEFINE(sem_request, 0, 1);
83 static K_SEM_DEFINE(sem_busy, 1, 1);
84 
85 static K_KERNEL_STACK_DEFINE(spi_rx_stack, CONFIG_BT_DRV_RX_STACK_SIZE);
86 static struct k_thread spi_rx_thread_data;
87 
88 static const struct spi_dt_spec bus = SPI_DT_SPEC_INST_GET(
89 	0, SPI_OP_MODE_MASTER | SPI_TRANSFER_MSB | SPI_WORD_SET(8), 0);
90 
91 static struct spi_buf spi_tx_buf;
92 static struct spi_buf spi_rx_buf;
93 static const struct spi_buf_set spi_tx = {
94 	.buffers = &spi_tx_buf,
95 	.count = 1
96 };
97 static const struct spi_buf_set spi_rx = {
98 	.buffers = &spi_rx_buf,
99 	.count = 1
100 };
101 
bt_spi_transceive(void * tx,uint32_t tx_len,void * rx,uint32_t rx_len)102 static inline int bt_spi_transceive(void *tx, uint32_t tx_len,
103 				    void *rx, uint32_t rx_len)
104 {
105 	spi_tx_buf.buf = tx;
106 	spi_tx_buf.len = (size_t)tx_len;
107 	spi_rx_buf.buf = rx;
108 	spi_rx_buf.len = (size_t)rx_len;
109 	return spi_transceive_dt(&bus, &spi_tx, &spi_rx);
110 }
111 
bt_spi_get_cmd(uint8_t * msg)112 static inline uint16_t bt_spi_get_cmd(uint8_t *msg)
113 {
114 	return (msg[CMD_OCF] << 8) | msg[CMD_OGF];
115 }
116 
bt_spi_get_evt(uint8_t * msg)117 static inline uint16_t bt_spi_get_evt(uint8_t *msg)
118 {
119 	return (msg[EVT_VENDOR_CODE_MSB] << 8) | msg[EVT_VENDOR_CODE_LSB];
120 }
121 
bt_spi_isr(const struct device * unused1,struct gpio_callback * unused2,uint32_t unused3)122 static void bt_spi_isr(const struct device *unused1,
123 		       struct gpio_callback *unused2,
124 		       uint32_t unused3)
125 {
126 	LOG_DBG("");
127 
128 	k_sem_give(&sem_request);
129 }
130 
bt_spi_handle_vendor_evt(uint8_t * msg)131 static bool bt_spi_handle_vendor_evt(uint8_t *msg)
132 {
133 	bool handled = false;
134 
135 	switch (bt_spi_get_evt(msg)) {
136 	case EVT_BLUE_INITIALIZED: {
137 		k_sem_give(&sem_initialised);
138 		handled = true;
139 	}
140 	default:
141 		break;
142 	}
143 	return handled;
144 }
145 
bt_spi_get_header(uint8_t op,uint16_t * size)146 static int bt_spi_get_header(uint8_t op, uint16_t *size)
147 {
148 	uint8_t header_master[5] = {op, 0, 0, 0, 0};
149 	uint8_t header_slave[5];
150 	bool reading = (op == SPI_READ);
151 	bool loop_cond;
152 	uint8_t size_offset;
153 	int ret;
154 
155 	if (!(op == SPI_READ || op == SPI_WRITE)) {
156 		return -EINVAL;
157 	}
158 	if (reading) {
159 		size_offset = STATUS_HEADER_TOREAD;
160 	}
161 
162 	do {
163 		ret = bt_spi_transceive(header_master, 5, header_slave, 5);
164 		if (ret) {
165 			break;
166 		}
167 		if (reading) {
168 			/* When reading, keep looping if there is not yet any data */
169 			loop_cond = header_slave[STATUS_HEADER_TOREAD] == 0U;
170 		} else {
171 			/* When writing, keep looping if all bytes are zero */
172 			loop_cond = ((header_slave[1] | header_slave[2] | header_slave[3] |
173 					header_slave[4]) == 0U);
174 		}
175 	} while ((header_slave[STATUS_HEADER_READY] != READY_NOW) || loop_cond);
176 
177 	*size = (reading ? header_slave[size_offset] : SPI_MAX_MSG_LEN);
178 
179 	return ret;
180 }
181 
bt_spi_rx_buf_construct(uint8_t * msg)182 static struct net_buf *bt_spi_rx_buf_construct(uint8_t *msg)
183 {
184 	bool discardable = false;
185 	k_timeout_t timeout = K_FOREVER;
186 	struct bt_hci_acl_hdr acl_hdr;
187 	struct net_buf *buf;
188 	int len;
189 
190 	switch (msg[PACKET_TYPE]) {
191 	case BT_HCI_H4_EVT:
192 		switch (msg[EVT_HEADER_EVENT]) {
193 		case BT_HCI_EVT_VENDOR:
194 			/* Run event through interface handler */
195 			if (bt_spi_handle_vendor_evt(msg)) {
196 				return NULL;
197 			}
198 			/* Event has not yet been handled */
199 			__fallthrough;
200 		default:
201 			if (msg[EVT_HEADER_EVENT] == BT_HCI_EVT_LE_META_EVENT &&
202 			    (msg[EVT_LE_META_SUBEVENT] == BT_HCI_EVT_LE_ADVERTISING_REPORT)) {
203 				discardable = true;
204 				timeout = K_NO_WAIT;
205 			}
206 			buf = bt_buf_get_evt(msg[EVT_HEADER_EVENT],
207 					     discardable, timeout);
208 			if (!buf) {
209 				LOG_DBG("Discard adv report due to insufficient buf");
210 				return NULL;
211 			}
212 		}
213 
214 		len = sizeof(struct bt_hci_evt_hdr) + msg[EVT_HEADER_SIZE];
215 		if (len > net_buf_tailroom(buf)) {
216 			LOG_ERR("Event too long: %d", len);
217 			net_buf_unref(buf);
218 			return NULL;
219 		}
220 		net_buf_add_mem(buf, &msg[1], len);
221 		break;
222 	case BT_HCI_H4_ACL:
223 		buf = bt_buf_get_rx(BT_BUF_ACL_IN, K_FOREVER);
224 		memcpy(&acl_hdr, &msg[1], sizeof(acl_hdr));
225 		len = sizeof(acl_hdr) + sys_le16_to_cpu(acl_hdr.len);
226 		if (len > net_buf_tailroom(buf)) {
227 			LOG_ERR("ACL too long: %d", len);
228 			net_buf_unref(buf);
229 			return NULL;
230 		}
231 		net_buf_add_mem(buf, &msg[1], len);
232 		break;
233 	default:
234 		LOG_ERR("Unknown BT buf type %d", msg[0]);
235 		return NULL;
236 	}
237 
238 	return buf;
239 }
240 
bt_spi_rx_thread(void * p1,void * p2,void * p3)241 static void bt_spi_rx_thread(void *p1, void *p2, void *p3)
242 {
243 	const struct device *dev = p1;
244 	struct bt_spi_data *hci = dev->data;
245 
246 	ARG_UNUSED(p2);
247 	ARG_UNUSED(p3);
248 
249 	struct net_buf *buf;
250 	uint16_t size = 0U;
251 	int ret;
252 
253 	(void)memset(&txmsg, 0xFF, SPI_MAX_MSG_LEN);
254 	while (true) {
255 
256 		/* Wait for interrupt pin to be active */
257 		k_sem_take(&sem_request, K_FOREVER);
258 
259 		LOG_DBG("");
260 
261 		/* Wait for SPI bus to be available */
262 		k_sem_take(&sem_busy, K_FOREVER);
263 		ret = bt_spi_get_header(SPI_READ, &size);
264 
265 		/* Delay here is rounded up to next tick */
266 		k_sleep(K_USEC(DATA_DELAY_US));
267 		/* Read data */
268 		if (ret == 0 && size != 0) {
269 			do {
270 				ret = bt_spi_transceive(&txmsg, size,
271 							&rxmsg, size);
272 				if (rxmsg[0] == 0U) {
273 					/* Consider increasing controller-data-delay-us
274 					 * if this message is extremely common.
275 					 */
276 					LOG_DBG("Controller not ready for SPI transaction "
277 						"of %d bytes", size);
278 				}
279 			} while (rxmsg[0] == 0U && ret == 0);
280 		}
281 
282 		k_sem_give(&sem_busy);
283 
284 		if (ret || size == 0) {
285 			if (ret) {
286 				LOG_ERR("Error %d", ret);
287 			}
288 			continue;
289 		}
290 
291 		LOG_HEXDUMP_DBG(rxmsg, size, "SPI RX");
292 
293 		/* Construct net_buf from SPI data */
294 		buf = bt_spi_rx_buf_construct(rxmsg);
295 		if (buf) {
296 			/* Handle the received HCI data */
297 			hci->recv(dev, buf);
298 		}
299 	}
300 }
301 
bt_spi_send(const struct device * dev,struct net_buf * buf)302 static int bt_spi_send(const struct device *dev, struct net_buf *buf)
303 {
304 	uint16_t size;
305 	uint8_t rx_first[1];
306 	int ret;
307 
308 	ARG_UNUSED(dev);
309 
310 	LOG_DBG("");
311 
312 	/* Buffer needs an additional byte for type */
313 	if (buf->len >= SPI_MAX_MSG_LEN) {
314 		LOG_ERR("Message too long (%d)", buf->len);
315 		return -EINVAL;
316 	}
317 
318 	/* Wait for SPI bus to be available */
319 	k_sem_take(&sem_busy, K_FOREVER);
320 
321 	switch (bt_buf_get_type(buf)) {
322 	case BT_BUF_ACL_OUT:
323 		net_buf_push_u8(buf, BT_HCI_H4_ACL);
324 		break;
325 	case BT_BUF_CMD:
326 		net_buf_push_u8(buf, BT_HCI_H4_CMD);
327 		break;
328 	default:
329 		LOG_ERR("Unsupported type");
330 		k_sem_give(&sem_busy);
331 		return -EINVAL;
332 	}
333 
334 	ret = bt_spi_get_header(SPI_WRITE, &size);
335 	size = MIN(buf->len, size);
336 
337 	if (size < buf->len) {
338 		LOG_WRN("Unable to write full data, skipping");
339 		size = 0;
340 		ret = -ECANCELED;
341 	}
342 
343 	if (!ret) {
344 		/* Delay here is rounded up to next tick */
345 		k_sleep(K_USEC(DATA_DELAY_US));
346 		/* Transmit the message */
347 		while (true) {
348 			ret = bt_spi_transceive(buf->data, size,
349 						rx_first, 1);
350 			if (rx_first[0] != 0U || ret) {
351 				break;
352 			}
353 			/* Consider increasing controller-data-delay-us
354 			 * if this message is extremely common.
355 			 */
356 			LOG_DBG("Controller not ready for SPI transaction of %d bytes", size);
357 		}
358 	}
359 
360 	k_sem_give(&sem_busy);
361 
362 	if (ret) {
363 		LOG_ERR("Error %d", ret);
364 		goto out;
365 	}
366 
367 	LOG_HEXDUMP_DBG(buf->data, buf->len, "SPI TX");
368 
369 out:
370 	net_buf_unref(buf);
371 
372 	return ret;
373 }
374 
bt_spi_open(const struct device * dev,bt_hci_recv_t recv)375 static int bt_spi_open(const struct device *dev, bt_hci_recv_t recv)
376 {
377 	struct bt_spi_data *hci = dev->data;
378 	int err;
379 
380 	/* Configure RST pin and hold BLE in Reset */
381 	err = gpio_pin_configure_dt(&rst_gpio, GPIO_OUTPUT_ACTIVE);
382 	if (err) {
383 		return err;
384 	}
385 
386 	/* Configure IRQ pin and the IRQ call-back/handler */
387 	err = gpio_pin_configure_dt(&irq_gpio, GPIO_INPUT);
388 	if (err) {
389 		return err;
390 	}
391 
392 	gpio_init_callback(&gpio_cb, bt_spi_isr, BIT(irq_gpio.pin));
393 	err = gpio_add_callback(irq_gpio.port, &gpio_cb);
394 	if (err) {
395 		return err;
396 	}
397 
398 	/* Enable the interrupt line */
399 	err = gpio_pin_interrupt_configure_dt(&irq_gpio, GPIO_INT_EDGE_TO_ACTIVE);
400 	if (err) {
401 		return err;
402 	}
403 
404 	hci->recv = recv;
405 
406 	/* Take BLE out of reset */
407 	k_sleep(K_MSEC(DT_INST_PROP_OR(0, reset_assert_duration_ms, 0)));
408 	gpio_pin_set_dt(&rst_gpio, 0);
409 
410 	/* Start RX thread */
411 	k_thread_create(&spi_rx_thread_data, spi_rx_stack,
412 			K_KERNEL_STACK_SIZEOF(spi_rx_stack),
413 			bt_spi_rx_thread, (void *)dev, NULL, NULL,
414 			K_PRIO_COOP(CONFIG_BT_DRIVER_RX_HIGH_PRIO),
415 			0, K_NO_WAIT);
416 	k_thread_name_set(&spi_rx_thread_data, "bt_spi_rx_thread");
417 
418 	/* Device will let us know when it's ready */
419 	k_sem_take(&sem_initialised, K_FOREVER);
420 
421 	return 0;
422 }
423 
424 static DEVICE_API(bt_hci, drv) = {
425 	.open		= bt_spi_open,
426 	.send		= bt_spi_send,
427 };
428 
bt_spi_init(const struct device * dev)429 static int bt_spi_init(const struct device *dev)
430 {
431 	ARG_UNUSED(dev);
432 
433 	if (!spi_is_ready_dt(&bus)) {
434 		LOG_ERR("SPI device not ready");
435 		return -ENODEV;
436 	}
437 
438 	if (!gpio_is_ready_dt(&irq_gpio)) {
439 		LOG_ERR("IRQ GPIO device not ready");
440 		return -ENODEV;
441 	}
442 
443 	if (!gpio_is_ready_dt(&rst_gpio)) {
444 		LOG_ERR("Reset GPIO device not ready");
445 		return -ENODEV;
446 	}
447 
448 	LOG_DBG("BT SPI initialized");
449 
450 	return 0;
451 }
452 
453 #define HCI_DEVICE_INIT(inst) \
454 	static struct bt_spi_data hci_data_##inst = { \
455 	}; \
456 	DEVICE_DT_INST_DEFINE(inst, bt_spi_init, NULL, &hci_data_##inst, NULL, \
457 			      POST_KERNEL, CONFIG_BT_SPI_INIT_PRIORITY, &drv)
458 
459 /* Only one instance supported right now */
460 HCI_DEVICE_INIT(0)
461