1 /*
2  * Copyright (c) 2016 Nordic Semiconductor ASA
3  * Copyright (c) 2015-2016 Intel Corporation
4  *
5  * SPDX-License-Identifier: Apache-2.0
6  */
7 
8 #include <errno.h>
9 #include <stddef.h>
10 #include <stdio.h>
11 #include <string.h>
12 
13 #include <zephyr/kernel.h>
14 #include <zephyr/arch/cpu.h>
15 #include <zephyr/sys/byteorder.h>
16 #include <zephyr/logging/log.h>
17 #include <zephyr/sys/util.h>
18 
19 #include <zephyr/device.h>
20 #include <zephyr/init.h>
21 #include <zephyr/drivers/uart.h>
22 
23 #include <zephyr/usb/usb_device.h>
24 
25 #include <zephyr/net/buf.h>
26 #include <zephyr/bluetooth/bluetooth.h>
27 #include <zephyr/bluetooth/l2cap.h>
28 #include <zephyr/bluetooth/hci.h>
29 #include <zephyr/bluetooth/buf.h>
30 #include <zephyr/bluetooth/hci_raw.h>
31 
32 #define LOG_MODULE_NAME hci_uart
33 LOG_MODULE_REGISTER(LOG_MODULE_NAME);
34 
35 static const struct device *const hci_uart_dev =
36 	DEVICE_DT_GET(DT_CHOSEN(zephyr_bt_c2h_uart));
37 static K_THREAD_STACK_DEFINE(tx_thread_stack, CONFIG_BT_HCI_TX_STACK_SIZE);
38 static struct k_thread tx_thread_data;
39 static K_FIFO_DEFINE(tx_queue);
40 
41 /* RX in terms of bluetooth communication */
42 static K_FIFO_DEFINE(uart_tx_queue);
43 
44 #define H4_CMD 0x01
45 #define H4_ACL 0x02
46 #define H4_SCO 0x03
47 #define H4_EVT 0x04
48 #define H4_ISO 0x05
49 
50 /* Receiver states. */
51 #define ST_IDLE 0	/* Waiting for packet type. */
52 #define ST_HDR 1	/* Receiving packet header. */
53 #define ST_PAYLOAD 2	/* Receiving packet payload. */
54 #define ST_DISCARD 3	/* Dropping packet. */
55 
56 /* Length of a discard/flush buffer.
57  * This is sized to align with a BLE HCI packet:
58  * 1 byte H:4 header + 32 bytes ACL/event data
59  * Bigger values might overflow the stack since this is declared as a local
60  * variable, smaller ones will force the caller to call into discard more
61  * often.
62  */
63 #define H4_DISCARD_LEN 33
64 
h4_read(const struct device * uart,uint8_t * buf,size_t len)65 static int h4_read(const struct device *uart, uint8_t *buf, size_t len)
66 {
67 	int rx = uart_fifo_read(uart, buf, len);
68 
69 	LOG_DBG("read %d req %d", rx, len);
70 
71 	return rx;
72 }
73 
valid_type(uint8_t type)74 static bool valid_type(uint8_t type)
75 {
76 	return (type == H4_CMD) | (type == H4_ACL) | (type == H4_ISO);
77 }
78 
79 /* Function expects that type is validated and only CMD, ISO or ACL will be used. */
get_len(const uint8_t * hdr_buf,uint8_t type)80 static uint32_t get_len(const uint8_t *hdr_buf, uint8_t type)
81 {
82 	switch (type) {
83 	case H4_CMD:
84 		return ((const struct bt_hci_cmd_hdr *)hdr_buf)->param_len;
85 	case H4_ISO:
86 		return bt_iso_hdr_len(
87 			sys_le16_to_cpu(((const struct bt_hci_iso_hdr *)hdr_buf)->len));
88 	case H4_ACL:
89 		return sys_le16_to_cpu(((const struct bt_hci_acl_hdr *)hdr_buf)->len);
90 	default:
91 		LOG_ERR("Invalid type: %u", type);
92 		return 0;
93 	}
94 }
95 
96 /* Function expects that type is validated and only CMD, ISO or ACL will be used. */
hdr_len(uint8_t type)97 static int hdr_len(uint8_t type)
98 {
99 	switch (type) {
100 	case H4_CMD:
101 		return sizeof(struct bt_hci_cmd_hdr);
102 	case H4_ISO:
103 		return sizeof(struct bt_hci_iso_hdr);
104 	case H4_ACL:
105 		return sizeof(struct bt_hci_acl_hdr);
106 	default:
107 		LOG_ERR("Invalid type: %u", type);
108 		return 0;
109 	}
110 }
111 
rx_isr(void)112 static void rx_isr(void)
113 {
114 	static struct net_buf *buf;
115 	static int remaining;
116 	static uint8_t state;
117 	static uint8_t type;
118 	static uint8_t hdr_buf[MAX(sizeof(struct bt_hci_cmd_hdr),
119 			sizeof(struct bt_hci_acl_hdr))];
120 	int read;
121 
122 	do {
123 		switch (state) {
124 		case ST_IDLE:
125 			/* Get packet type */
126 			read = h4_read(hci_uart_dev, &type, sizeof(type));
127 			/* since we read in loop until no data is in the fifo,
128 			 * it is possible that read = 0.
129 			 */
130 			if (read) {
131 				if (valid_type(type)) {
132 					/* Get expected header size and switch
133 					 * to receiving header.
134 					 */
135 					remaining = hdr_len(type);
136 					state = ST_HDR;
137 				} else {
138 					LOG_WRN("Unknown header %d", type);
139 				}
140 			}
141 			break;
142 		case ST_HDR:
143 			read = h4_read(hci_uart_dev,
144 				       &hdr_buf[hdr_len(type) - remaining],
145 				       remaining);
146 			remaining -= read;
147 			if (remaining == 0) {
148 				/* Header received. Allocate buffer and get
149 				 * payload length. If allocation fails leave
150 				 * interrupt. On failed allocation state machine
151 				 * is reset.
152 				 */
153 				buf = bt_buf_get_tx(BT_BUF_H4, K_NO_WAIT,
154 						    &type, sizeof(type));
155 				if (!buf) {
156 					LOG_ERR("No available command buffers!");
157 					state = ST_IDLE;
158 					return;
159 				}
160 
161 				remaining = get_len(hdr_buf, type);
162 
163 				net_buf_add_mem(buf, hdr_buf, hdr_len(type));
164 				if (remaining > net_buf_tailroom(buf)) {
165 					LOG_ERR("Not enough space in buffer");
166 					net_buf_unref(buf);
167 					state = ST_DISCARD;
168 				} else {
169 					state = ST_PAYLOAD;
170 				}
171 
172 			}
173 			break;
174 		case ST_PAYLOAD:
175 			read = h4_read(hci_uart_dev, net_buf_tail(buf),
176 				       remaining);
177 			buf->len += read;
178 			remaining -= read;
179 			if (remaining == 0) {
180 				/* Packet received */
181 				LOG_DBG("putting RX packet in queue.");
182 				net_buf_put(&tx_queue, buf);
183 				state = ST_IDLE;
184 			}
185 			break;
186 		case ST_DISCARD:
187 		{
188 			uint8_t discard[H4_DISCARD_LEN];
189 			size_t to_read = MIN(remaining, sizeof(discard));
190 
191 			read = h4_read(hci_uart_dev, discard, to_read);
192 			remaining -= read;
193 			if (remaining == 0) {
194 				state = ST_IDLE;
195 			}
196 
197 			break;
198 
199 		}
200 		default:
201 			read = 0;
202 			__ASSERT_NO_MSG(0);
203 			break;
204 
205 		}
206 	} while (read);
207 }
208 
tx_isr(void)209 static void tx_isr(void)
210 {
211 	static struct net_buf *buf;
212 	int len;
213 
214 	if (!buf) {
215 		buf = net_buf_get(&uart_tx_queue, K_NO_WAIT);
216 		if (!buf) {
217 			uart_irq_tx_disable(hci_uart_dev);
218 			return;
219 		}
220 	}
221 
222 	len = uart_fifo_fill(hci_uart_dev, buf->data, buf->len);
223 	net_buf_pull(buf, len);
224 	if (!buf->len) {
225 		net_buf_unref(buf);
226 		buf = NULL;
227 	}
228 }
229 
bt_uart_isr(const struct device * unused,void * user_data)230 static void bt_uart_isr(const struct device *unused, void *user_data)
231 {
232 	ARG_UNUSED(unused);
233 	ARG_UNUSED(user_data);
234 
235 	if (!(uart_irq_rx_ready(hci_uart_dev) ||
236 	      uart_irq_tx_ready(hci_uart_dev))) {
237 		LOG_DBG("spurious interrupt");
238 	}
239 
240 	if (uart_irq_tx_ready(hci_uart_dev)) {
241 		tx_isr();
242 	}
243 
244 	if (uart_irq_rx_ready(hci_uart_dev)) {
245 		rx_isr();
246 	}
247 }
248 
tx_thread(void * p1,void * p2,void * p3)249 static void tx_thread(void *p1, void *p2, void *p3)
250 {
251 	while (1) {
252 		struct net_buf *buf;
253 		int err;
254 
255 		/* Wait until a buffer is available */
256 		buf = net_buf_get(&tx_queue, K_FOREVER);
257 		/* Pass buffer to the stack */
258 		err = bt_send(buf);
259 		if (err) {
260 			LOG_ERR("Unable to send (err %d)", err);
261 			net_buf_unref(buf);
262 		}
263 
264 		/* Give other threads a chance to run if tx_queue keeps getting
265 		 * new data all the time.
266 		 */
267 		k_yield();
268 	}
269 }
270 
h4_send(struct net_buf * buf)271 static int h4_send(struct net_buf *buf)
272 {
273 	LOG_DBG("buf %p type %u len %u", buf, bt_buf_get_type(buf),
274 		    buf->len);
275 
276 	net_buf_put(&uart_tx_queue, buf);
277 	uart_irq_tx_enable(hci_uart_dev);
278 
279 	return 0;
280 }
281 
282 #if defined(CONFIG_BT_CTLR_ASSERT_HANDLER)
bt_ctlr_assert_handle(char * file,uint32_t line)283 void bt_ctlr_assert_handle(char *file, uint32_t line)
284 {
285 	uint32_t len = 0U, pos = 0U;
286 
287 	/* Disable interrupts, this is unrecoverable */
288 	(void)irq_lock();
289 
290 	uart_irq_rx_disable(hci_uart_dev);
291 	uart_irq_tx_disable(hci_uart_dev);
292 
293 	if (file) {
294 		while (file[len] != '\0') {
295 			if (file[len] == '/') {
296 				pos = len + 1;
297 			}
298 			len++;
299 		}
300 		file += pos;
301 		len -= pos;
302 	}
303 
304 	uart_poll_out(hci_uart_dev, H4_EVT);
305 	/* Vendor-Specific debug event */
306 	uart_poll_out(hci_uart_dev, 0xff);
307 	/* 0xAA + strlen + \0 + 32-bit line number */
308 	uart_poll_out(hci_uart_dev, 1 + len + 1 + 4);
309 	uart_poll_out(hci_uart_dev, 0xAA);
310 
311 	if (len) {
312 		while (*file != '\0') {
313 			uart_poll_out(hci_uart_dev, *file);
314 			file++;
315 		}
316 		uart_poll_out(hci_uart_dev, 0x00);
317 	}
318 
319 	uart_poll_out(hci_uart_dev, line >> 0 & 0xff);
320 	uart_poll_out(hci_uart_dev, line >> 8 & 0xff);
321 	uart_poll_out(hci_uart_dev, line >> 16 & 0xff);
322 	uart_poll_out(hci_uart_dev, line >> 24 & 0xff);
323 
324 	while (1) {
325 	}
326 }
327 #endif /* CONFIG_BT_CTLR_ASSERT_HANDLER */
328 
hci_uart_init(void)329 static int hci_uart_init(void)
330 {
331 	LOG_DBG("");
332 
333 	if (IS_ENABLED(CONFIG_USB_CDC_ACM)) {
334 		if (usb_enable(NULL)) {
335 			LOG_ERR("Failed to enable USB");
336 			return -EINVAL;
337 		}
338 	}
339 
340 	if (!device_is_ready(hci_uart_dev)) {
341 		LOG_ERR("HCI UART %s is not ready", hci_uart_dev->name);
342 		return -EINVAL;
343 	}
344 
345 	uart_irq_rx_disable(hci_uart_dev);
346 	uart_irq_tx_disable(hci_uart_dev);
347 
348 	uart_irq_callback_set(hci_uart_dev, bt_uart_isr);
349 
350 	uart_irq_rx_enable(hci_uart_dev);
351 
352 	return 0;
353 }
354 
355 SYS_INIT(hci_uart_init, APPLICATION, CONFIG_KERNEL_INIT_PRIORITY_DEVICE);
356 
main(void)357 int main(void)
358 {
359 	/* incoming events and data from the controller */
360 	static K_FIFO_DEFINE(rx_queue);
361 	int err;
362 
363 	LOG_DBG("Start");
364 	__ASSERT(hci_uart_dev, "UART device is NULL");
365 
366 	/* Enable the raw interface, this will in turn open the HCI driver */
367 	bt_enable_raw(&rx_queue);
368 
369 	if (IS_ENABLED(CONFIG_BT_WAIT_NOP)) {
370 		/* Issue a Command Complete with NOP */
371 		int i;
372 
373 		const struct {
374 			const uint8_t h4;
375 			const struct bt_hci_evt_hdr hdr;
376 			const struct bt_hci_evt_cmd_complete cc;
377 		} __packed cc_evt = {
378 			.h4 = H4_EVT,
379 			.hdr = {
380 				.evt = BT_HCI_EVT_CMD_COMPLETE,
381 				.len = sizeof(struct bt_hci_evt_cmd_complete),
382 			},
383 			.cc = {
384 				.ncmd = 1,
385 				.opcode = sys_cpu_to_le16(BT_OP_NOP),
386 			},
387 		};
388 
389 		for (i = 0; i < sizeof(cc_evt); i++) {
390 			uart_poll_out(hci_uart_dev,
391 				      *(((const uint8_t *)&cc_evt)+i));
392 		}
393 	}
394 
395 	/* Spawn the TX thread and start feeding commands and data to the
396 	 * controller
397 	 */
398 	k_thread_create(&tx_thread_data, tx_thread_stack,
399 			K_THREAD_STACK_SIZEOF(tx_thread_stack), tx_thread,
400 			NULL, NULL, NULL, K_PRIO_COOP(7), 0, K_NO_WAIT);
401 	k_thread_name_set(&tx_thread_data, "HCI uart TX");
402 
403 	while (1) {
404 		struct net_buf *buf;
405 
406 		buf = net_buf_get(&rx_queue, K_FOREVER);
407 		err = h4_send(buf);
408 		if (err) {
409 			LOG_ERR("Failed to send");
410 		}
411 	}
412 	return 0;
413 }
414