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 				k_fifo_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 = k_fifo_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 	while (uart_irq_update(hci_uart_dev) && uart_irq_is_pending(hci_uart_dev)) {
236 		if (!(uart_irq_rx_ready(hci_uart_dev) ||
237 		      uart_irq_tx_ready(hci_uart_dev))) {
238 			LOG_DBG("spurious interrupt");
239 		}
240 
241 		if (uart_irq_tx_ready(hci_uart_dev)) {
242 			tx_isr();
243 		}
244 
245 		if (uart_irq_rx_ready(hci_uart_dev)) {
246 			rx_isr();
247 		}
248 	}
249 }
250 
tx_thread(void * p1,void * p2,void * p3)251 static void tx_thread(void *p1, void *p2, void *p3)
252 {
253 	while (1) {
254 		struct net_buf *buf;
255 		int err;
256 
257 		/* Wait until a buffer is available */
258 		buf = k_fifo_get(&tx_queue, K_FOREVER);
259 		/* Pass buffer to the stack */
260 		err = bt_send(buf);
261 		if (err) {
262 			LOG_ERR("Unable to send (err %d)", err);
263 			net_buf_unref(buf);
264 		}
265 
266 		/* Give other threads a chance to run if tx_queue keeps getting
267 		 * new data all the time.
268 		 */
269 		k_yield();
270 	}
271 }
272 
h4_send(struct net_buf * buf)273 static int h4_send(struct net_buf *buf)
274 {
275 	LOG_DBG("buf %p type %u len %u", buf, bt_buf_get_type(buf),
276 		    buf->len);
277 
278 	k_fifo_put(&uart_tx_queue, buf);
279 	uart_irq_tx_enable(hci_uart_dev);
280 
281 	return 0;
282 }
283 
284 #if defined(CONFIG_BT_CTLR_ASSERT_HANDLER)
bt_ctlr_assert_handle(char * file,uint32_t line)285 void bt_ctlr_assert_handle(char *file, uint32_t line)
286 {
287 	uint32_t len = 0U, pos = 0U;
288 
289 	/* Disable interrupts, this is unrecoverable */
290 	(void)irq_lock();
291 
292 	uart_irq_rx_disable(hci_uart_dev);
293 	uart_irq_tx_disable(hci_uart_dev);
294 
295 	if (file) {
296 		while (file[len] != '\0') {
297 			if (file[len] == '/') {
298 				pos = len + 1;
299 			}
300 			len++;
301 		}
302 		file += pos;
303 		len -= pos;
304 	}
305 
306 	uart_poll_out(hci_uart_dev, H4_EVT);
307 	/* Vendor-Specific debug event */
308 	uart_poll_out(hci_uart_dev, 0xff);
309 	/* 0xAA + strlen + \0 + 32-bit line number */
310 	uart_poll_out(hci_uart_dev, 1 + len + 1 + 4);
311 	uart_poll_out(hci_uart_dev, 0xAA);
312 
313 	if (len) {
314 		while (*file != '\0') {
315 			uart_poll_out(hci_uart_dev, *file);
316 			file++;
317 		}
318 		uart_poll_out(hci_uart_dev, 0x00);
319 	}
320 
321 	uart_poll_out(hci_uart_dev, line >> 0 & 0xff);
322 	uart_poll_out(hci_uart_dev, line >> 8 & 0xff);
323 	uart_poll_out(hci_uart_dev, line >> 16 & 0xff);
324 	uart_poll_out(hci_uart_dev, line >> 24 & 0xff);
325 
326 	while (1) {
327 	}
328 }
329 #endif /* CONFIG_BT_CTLR_ASSERT_HANDLER */
330 
hci_uart_init(void)331 static int hci_uart_init(void)
332 {
333 	LOG_DBG("");
334 
335 	if (IS_ENABLED(CONFIG_USB_CDC_ACM)) {
336 		if (usb_enable(NULL)) {
337 			LOG_ERR("Failed to enable USB");
338 			return -EINVAL;
339 		}
340 	}
341 
342 	if (!device_is_ready(hci_uart_dev)) {
343 		LOG_ERR("HCI UART %s is not ready", hci_uart_dev->name);
344 		return -EINVAL;
345 	}
346 
347 	uart_irq_rx_disable(hci_uart_dev);
348 	uart_irq_tx_disable(hci_uart_dev);
349 
350 	uart_irq_callback_set(hci_uart_dev, bt_uart_isr);
351 
352 	uart_irq_rx_enable(hci_uart_dev);
353 
354 	return 0;
355 }
356 
357 SYS_INIT(hci_uart_init, APPLICATION, CONFIG_KERNEL_INIT_PRIORITY_DEVICE);
358 
main(void)359 int main(void)
360 {
361 	/* incoming events and data from the controller */
362 	static K_FIFO_DEFINE(rx_queue);
363 	int err;
364 
365 	LOG_DBG("Start");
366 	__ASSERT(hci_uart_dev, "UART device is NULL");
367 
368 	/* Enable the raw interface, this will in turn open the HCI driver */
369 	bt_enable_raw(&rx_queue);
370 
371 	if (IS_ENABLED(CONFIG_BT_WAIT_NOP)) {
372 		/* Issue a Command Complete with NOP */
373 		int i;
374 
375 		const struct {
376 			const uint8_t h4;
377 			const struct bt_hci_evt_hdr hdr;
378 			const struct bt_hci_evt_cmd_complete cc;
379 		} __packed cc_evt = {
380 			.h4 = H4_EVT,
381 			.hdr = {
382 				.evt = BT_HCI_EVT_CMD_COMPLETE,
383 				.len = sizeof(struct bt_hci_evt_cmd_complete),
384 			},
385 			.cc = {
386 				.ncmd = 1,
387 				.opcode = sys_cpu_to_le16(BT_OP_NOP),
388 			},
389 		};
390 
391 		for (i = 0; i < sizeof(cc_evt); i++) {
392 			uart_poll_out(hci_uart_dev,
393 				      *(((const uint8_t *)&cc_evt)+i));
394 		}
395 	}
396 
397 	/* Spawn the TX thread and start feeding commands and data to the
398 	 * controller
399 	 */
400 	k_thread_create(&tx_thread_data, tx_thread_stack,
401 			K_THREAD_STACK_SIZEOF(tx_thread_stack), tx_thread,
402 			NULL, NULL, NULL, K_PRIO_COOP(7), 0, K_NO_WAIT);
403 	k_thread_name_set(&tx_thread_data, "HCI uart TX");
404 
405 	while (1) {
406 		struct net_buf *buf;
407 
408 		buf = k_fifo_get(&rx_queue, K_FOREVER);
409 		err = h4_send(buf);
410 		if (err) {
411 			LOG_ERR("Failed to send");
412 		}
413 	}
414 	return 0;
415 }
416