1 // Copyright 2018 The Fuchsia Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 #include <ddk/binding.h>
6 #include <ddk/debug.h>
7 #include <ddk/device.h>
8 #include <ddk/driver.h>
9 #include <ddk/platform-defs.h>
10 #include <ddk/protocol/bt/hci.h>
11 #include <ddk/protocol/serial.h>
12 #include <zircon/device/bt-hci.h>
13 #include <zircon/device/serial.h>
14 #include <zircon/status.h>
15 
16 #include <assert.h>
17 #include <stdio.h>
18 #include <stdlib.h>
19 #include <string.h>
20 #include <threads.h>
21 #include <unistd.h>
22 
23 // The maximum HCI ACL frame size used for data transactions
24 #define ACL_MAX_FRAME_SIZE 1029 // (1024 + 4 bytes for the ACL header + 1 byte packet indicator)
25 
26 #define CMD_BUF_SIZE 255 + 4   // 1 byte packet indicator + 3 byte header + payload
27 #define EVENT_BUF_SIZE 255 + 3 // 1 byte packet indicator + 2 byte header + payload
28 
29 // The number of currently supported HCI channel endpoints. We currently have
30 // one channel for command/event flow and one for ACL data flow. The sniff channel is managed
31 // separately.
32 #define NUM_CHANNELS 2
33 
34 #define NUM_WAIT_ITEMS NUM_CHANNELS + 2 // add one for the changed event and one for UART socket
35 
36 // HCI UART packet indicators
37 enum {
38     HCI_NONE = 0,
39     HCI_COMMAND = 1,
40     HCI_ACL_DATA = 2,
41     HCI_SCO = 3,
42     HCI_EVENT = 4,
43 };
44 
45 typedef struct {
46     zx_device_t* zxdev;
47     zx_device_t* parent;
48     zx_handle_t uart_socket;
49     zx_handle_t cmd_channel;
50     zx_handle_t acl_channel;
51     zx_handle_t snoop_channel;
52 
53     // Signaled when a channel opens or closes
54     zx_handle_t channels_changed_evt;
55 
56     zx_wait_item_t read_wait_items[NUM_WAIT_ITEMS];
57     uint32_t read_wait_item_count;
58 
59     bool read_thread_running;
60 
61     // type of current packet being read from the UART
62     uint8_t cur_uart_packet_type;
63 
64     // for accumulating HCI events
65     uint8_t event_buffer[EVENT_BUF_SIZE];
66     size_t event_buffer_offset;
67 
68     // for accumulating ACL data packets
69     uint8_t acl_buffer[EVENT_BUF_SIZE];
70     size_t acl_buffer_offset;
71 
72     mtx_t mutex;
73 } hci_t;
74 
75 // macro for returning length of current event packet being received
76 // payload length is in byte 2 of the packet
77 // add 3 bytes for packet indicator, event code and length byte
78 #define EVENT_PACKET_LENGTH(hci) ((hci)->event_buffer_offset > 2 ? (hci)->event_buffer[2] + 3 : 0)
79 
80 // macro for returning length of current ACL data packet being received
81 // length is in bytes 3 and 4 of the packet
82 // add 5 bytes for packet indicator, control info and length fields
83 #define ACL_PACKET_LENGTH(hci) ((hci)->acl_buffer_offset > 4 ? \
84                                     ((hci)->acl_buffer[3] | ((hci)->acl_buffer[4] << 8)) + 5 : 0)
85 
channel_cleanup_locked(hci_t * hci,zx_handle_t * channel)86 static void channel_cleanup_locked(hci_t* hci, zx_handle_t* channel) {
87     if (*channel == ZX_HANDLE_INVALID)
88         return;
89 
90     zx_handle_close(*channel);
91     *channel = ZX_HANDLE_INVALID;
92     zx_object_signal(hci->channels_changed_evt, 0, ZX_EVENT_SIGNALED);
93 }
94 
snoop_channel_write_locked(hci_t * hci,uint8_t flags,uint8_t * bytes,size_t length)95 static void snoop_channel_write_locked(hci_t* hci, uint8_t flags, uint8_t* bytes, size_t length) {
96     if (hci->snoop_channel == ZX_HANDLE_INVALID)
97         return;
98 
99     // We tack on a flags byte to the beginning of the payload.
100     uint8_t snoop_buffer[length + 1];
101     snoop_buffer[0] = flags;
102     memcpy(snoop_buffer + 1, bytes, length);
103     zx_status_t status = zx_channel_write(hci->snoop_channel, 0, snoop_buffer, length + 1, NULL, 0);
104     if (status < 0) {
105         zxlogf(ERROR, "bt-transport-uart: failed to write to snoop channel: %s\n",
106                zx_status_get_string(status));
107         channel_cleanup_locked(hci, &hci->snoop_channel);
108     }
109 }
110 
hci_build_read_wait_items_locked(hci_t * hci)111 static void hci_build_read_wait_items_locked(hci_t* hci) {
112     zx_wait_item_t* items = hci->read_wait_items;
113     memset(items, 0, sizeof(hci->read_wait_items));
114     uint32_t count = 0;
115 
116     if (hci->cmd_channel != ZX_HANDLE_INVALID) {
117         items[count].handle = hci->cmd_channel;
118         items[count].waitfor = ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED;
119         count++;
120     }
121 
122     if (hci->acl_channel != ZX_HANDLE_INVALID) {
123         items[count].handle = hci->acl_channel;
124         items[count].waitfor = ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED;
125         count++;
126     }
127 
128     items[count].handle = hci->uart_socket;
129     items[count].waitfor = ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED;
130     count++;
131 
132     items[count].handle = hci->channels_changed_evt;
133     items[count].waitfor = ZX_EVENT_SIGNALED;
134     count++;
135 
136     hci->read_wait_item_count = count;
137 
138     zx_object_signal(hci->channels_changed_evt, ZX_EVENT_SIGNALED, 0);
139 }
140 
hci_build_read_wait_items(hci_t * hci)141 static void hci_build_read_wait_items(hci_t* hci) {
142     mtx_lock(&hci->mutex);
143     hci_build_read_wait_items_locked(hci);
144     mtx_unlock(&hci->mutex);
145 }
146 
147 // Returns false if there's an error while sending the packet to the hardware or
148 // if the channel peer closed its endpoint.
hci_handle_cmd_read_events(hci_t * hci,zx_wait_item_t * item)149 static void hci_handle_cmd_read_events(hci_t* hci, zx_wait_item_t* item) {
150     if (item->pending & (ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED)) {
151         uint8_t buf[CMD_BUF_SIZE];
152         uint32_t length = sizeof(buf) - 1;
153         zx_status_t status =
154             zx_channel_read(item->handle, 0, buf + 1, NULL, length, 0, &length, NULL);
155         if (status < 0) {
156             if (status != ZX_ERR_PEER_CLOSED) {
157                 zxlogf(ERROR, "hci_read_thread: failed to read from command channel %s\n",
158                        zx_status_get_string(status));
159             }
160             goto fail;
161         }
162 
163         buf[0] = HCI_COMMAND;
164         length++;
165         status = zx_socket_write(hci->uart_socket, 0, buf, length, NULL);
166         if (status < 0) {
167             zxlogf(ERROR, "hci_read_thread: zx_socket_write failed: %s\n",
168                    zx_status_get_string(status));
169             goto fail;
170         }
171 
172         mtx_lock(&hci->mutex);
173         snoop_channel_write_locked(hci, bt_hci_snoop_flags(BT_HCI_SNOOP_TYPE_CMD, false), buf + 1, length - 1);
174         mtx_unlock(&hci->mutex);
175     }
176 
177     return;
178 
179 fail:
180     mtx_lock(&hci->mutex);
181     channel_cleanup_locked(hci, &hci->cmd_channel);
182     mtx_unlock(&hci->mutex);
183 }
184 
hci_handle_acl_read_events(hci_t * hci,zx_wait_item_t * item)185 static void hci_handle_acl_read_events(hci_t* hci, zx_wait_item_t* item) {
186     if (item->pending & (ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED)) {
187         uint8_t buf[ACL_MAX_FRAME_SIZE];
188         uint32_t length = sizeof(buf) - 1;
189         zx_status_t status =
190             zx_channel_read(item->handle, 0, buf + 1, NULL, length, 0, &length, NULL);
191         if (status < 0) {
192             zxlogf(ERROR, "hci_read_thread: failed to read from ACL channel %s\n",
193                    zx_status_get_string(status));
194             goto fail;
195         }
196 
197         buf[0] = HCI_ACL_DATA;
198         length++;
199         status = zx_socket_write(hci->uart_socket, 0, buf, length, NULL);
200         if (status < 0) {
201             zxlogf(ERROR, "hci_read_thread: zx_socket_write failed: %s\n",
202                    zx_status_get_string(status));
203             goto fail;
204         }
205         snoop_channel_write_locked(
206             hci, bt_hci_snoop_flags(BT_HCI_SNOOP_TYPE_ACL, false), buf + 1, length - 1);
207     }
208 
209     return;
210 
211 fail:
212     mtx_lock(&hci->mutex);
213     channel_cleanup_locked(hci, &hci->acl_channel);
214     mtx_unlock(&hci->mutex);
215 }
216 
hci_handle_uart_read_events(hci_t * hci,zx_wait_item_t * item)217 static void hci_handle_uart_read_events(hci_t* hci, zx_wait_item_t* item) {
218     if (item->pending & (ZX_CHANNEL_READABLE | ZX_CHANNEL_PEER_CLOSED)) {
219         uint8_t buf[ACL_MAX_FRAME_SIZE];
220         size_t length = sizeof(buf);
221         zx_status_t status = zx_socket_read(item->handle, 0, buf, length, &length);
222         if (status < 0) {
223             zxlogf(ERROR, "hci_read_thread: failed to read from ACL channel %s\n",
224                    zx_status_get_string(status));
225             goto fail;
226         }
227 
228         const uint8_t* src = buf;
229         const uint8_t* end = src + length;
230         uint8_t packet_type = hci->cur_uart_packet_type;
231 
232         while (src < end) {
233             if (packet_type == HCI_NONE) {
234                 // start of new packet. read packet type
235                 packet_type = *src++;
236                 if (packet_type != HCI_EVENT && packet_type != HCI_ACL_DATA) {
237                     zxlogf(INFO, "unsupported HCI packet type %u. We may be out of sync\n",
238                            packet_type);
239                     return;
240                 }
241             }
242 
243             if (packet_type == HCI_EVENT) {
244                 size_t packet_length = EVENT_PACKET_LENGTH(hci);
245 
246                 while (!packet_length && src < end) {
247                     // read until we have enough to compute packet length
248                     hci->event_buffer[hci->event_buffer_offset++] = *src++;
249                     packet_length = EVENT_PACKET_LENGTH(hci);
250                 }
251                 if (!packet_length) {
252                     break;
253                 }
254 
255                 size_t remaining = end - src;
256                 size_t copy = packet_length - hci->event_buffer_offset;
257                 if (copy > remaining) copy = remaining;
258                 memcpy(hci->event_buffer + hci->event_buffer_offset, src, copy);
259                 src += copy;
260                 hci->event_buffer_offset += copy;
261 
262                 if (hci->event_buffer_offset == packet_length) {
263                     // send accumulated event packet, minus the packet indicator
264                     zx_status_t status = zx_channel_write(hci->cmd_channel, 0,
265                                                           &hci->event_buffer[1],
266                                                           packet_length - 1, NULL, 0);
267                     if (status < 0) {
268                         zxlogf(ERROR, "bt-transport-uart: failed to write event packet: %s\n",
269                                zx_status_get_string(status));
270                     }
271                     snoop_channel_write_locked(hci, bt_hci_snoop_flags(BT_HCI_SNOOP_TYPE_EVT, true),
272                                                &hci->event_buffer[1], packet_length - 1);
273 
274                     // reset buffer
275                     packet_type = HCI_NONE;
276                     hci->event_buffer_offset = 1;
277                 }
278             } else { // HCI_ACL_DATA
279                 size_t packet_length = EVENT_PACKET_LENGTH(hci);
280 
281                 while (!packet_length && src < end) {
282                     // read until we have enough to compute packet length
283                     hci->acl_buffer[hci->acl_buffer_offset++] = *src++;
284                     packet_length = ACL_PACKET_LENGTH(hci);
285                 }
286                 if (!packet_length) {
287                     break;
288                 }
289 
290                 size_t remaining = end - src;
291                 size_t copy = packet_length - hci->acl_buffer_offset;
292                 if (copy > remaining) copy = remaining;
293                 memcpy(hci->acl_buffer + hci->acl_buffer_offset, src, copy);
294                 src += copy;
295                 hci->acl_buffer_offset += copy;
296 
297                 if (hci->acl_buffer_offset == packet_length) {
298                     // send accumulated ACL data packet, minus the packet indicator
299                     zx_status_t status = zx_channel_write(hci->acl_channel, 0,
300                                                           &hci->acl_buffer[1],
301                                                           packet_length - 1, NULL, 0);
302                     if (status < 0) {
303                         zxlogf(ERROR, "bt-transport-uart: failed to write ACL packet: %s\n",
304                                zx_status_get_string(status));
305                     }
306 
307                     // If the snoop channel is open then try to write the packet
308                     // even if acl_channel was closed.
309                     snoop_channel_write_locked(hci,
310                                                bt_hci_snoop_flags(BT_HCI_SNOOP_TYPE_ACL, true),
311                                                &hci->acl_buffer[1], packet_length - 1);
312 
313                     // reset buffer
314                     packet_type = HCI_NONE;
315                     hci->acl_buffer_offset = 1;
316                 }
317             }
318         }
319 
320         hci->cur_uart_packet_type = packet_type;
321     }
322 
323     return;
324 
325 fail:
326     mtx_lock(&hci->mutex);
327     channel_cleanup_locked(hci, &hci->acl_channel);
328     mtx_unlock(&hci->mutex);
329 }
330 
hci_has_read_channels_locked(hci_t * hci)331 static bool hci_has_read_channels_locked(hci_t* hci) {
332     // One for the signal event and one for uart socket, any additional are read channels.
333     return hci->read_wait_item_count > 2;
334 }
335 
hci_read_thread(void * arg)336 static int hci_read_thread(void* arg) {
337     hci_t* hci = (hci_t*)arg;
338 
339     mtx_lock(&hci->mutex);
340 
341     if (!hci_has_read_channels_locked(hci)) {
342         zxlogf(ERROR, "bt-transport-uart: no channels are open - exiting\n");
343         hci->read_thread_running = false;
344         mtx_unlock(&hci->mutex);
345         return 0;
346     }
347 
348     mtx_unlock(&hci->mutex);
349 
350     while (1) {
351         zx_status_t status = zx_object_wait_many(hci->read_wait_items, hci->read_wait_item_count,
352                                                  ZX_TIME_INFINITE);
353         if (status < 0) {
354             zxlogf(ERROR, "bt-transport-uart: zx_object_wait_many failed (%s) - exiting\n",
355                    zx_status_get_string(status));
356             mtx_lock(&hci->mutex);
357             channel_cleanup_locked(hci, &hci->cmd_channel);
358             channel_cleanup_locked(hci, &hci->acl_channel);
359             mtx_unlock(&hci->mutex);
360             break;
361         }
362 
363         for (unsigned i = 0; i < hci->read_wait_item_count; ++i) {
364             mtx_lock(&hci->mutex);
365             zx_wait_item_t item = hci->read_wait_items[i];
366             mtx_unlock(&hci->mutex);
367 
368             if (item.handle == hci->cmd_channel) {
369                 hci_handle_cmd_read_events(hci, &item);
370             } else if (item.handle == hci->acl_channel) {
371                 hci_handle_acl_read_events(hci, &item);
372             } else if (item.handle == hci->uart_socket) {
373                 hci_handle_uart_read_events(hci, &item);
374             }
375         }
376 
377         // The channels might have been changed by the *_read_events, recheck the event.
378         status = zx_object_wait_one(hci->channels_changed_evt, ZX_EVENT_SIGNALED, 0u, NULL);
379         if (status == ZX_OK) {
380             hci_build_read_wait_items(hci);
381             if (!hci_has_read_channels_locked(hci)) {
382                 zxlogf(TRACE, "bt-transport-uart: all channels closed - exiting\n");
383                 break;
384             }
385         }
386     }
387 
388     mtx_lock(&hci->mutex);
389     hci->read_thread_running = false;
390     mtx_unlock(&hci->mutex);
391     return 0;
392 }
393 
hci_open_channel(hci_t * hci,zx_handle_t * in_channel,zx_handle_t * out_channel)394 static zx_status_t hci_open_channel(hci_t* hci, zx_handle_t* in_channel, zx_handle_t* out_channel) {
395     zx_status_t result = ZX_OK;
396     mtx_lock(&hci->mutex);
397 
398     if (*in_channel != ZX_HANDLE_INVALID) {
399         zxlogf(ERROR, "bt-transport-uart: already bound, failing\n");
400         result = ZX_ERR_ALREADY_BOUND;
401         goto done;
402     }
403 
404     zx_status_t status = zx_channel_create(0, in_channel, out_channel);
405     if (status < 0) {
406         zxlogf(ERROR, "bt-transport-uart: Failed to create channel: %s\n",
407                zx_status_get_string(status));
408         result = ZX_ERR_INTERNAL;
409         goto done;
410     }
411 
412     // Kick off the hci_read_thread if it's not already running.
413     if (!hci->read_thread_running) {
414         hci_build_read_wait_items_locked(hci);
415         thrd_t read_thread;
416         thrd_create_with_name(&read_thread, hci_read_thread, hci, "bt_usb_read_thread");
417         hci->read_thread_running = true;
418         thrd_detach(read_thread);
419     } else {
420         // Poke the changed event to get the new channel.
421         zx_object_signal(hci->channels_changed_evt, 0, ZX_EVENT_SIGNALED);
422     }
423 
424 done:
425     mtx_unlock(&hci->mutex);
426     return result;
427 }
428 
hci_unbind(void * ctx)429 static void hci_unbind(void* ctx) {
430     hci_t* hci = ctx;
431 
432     // Close the transport channels so that the host stack is notified of device removal.
433     mtx_lock(&hci->mutex);
434 
435     channel_cleanup_locked(hci, &hci->cmd_channel);
436     channel_cleanup_locked(hci, &hci->acl_channel);
437     channel_cleanup_locked(hci, &hci->snoop_channel);
438 
439     mtx_unlock(&hci->mutex);
440 
441     device_remove(hci->zxdev);
442 }
443 
hci_release(void * ctx)444 static void hci_release(void* ctx) {
445     hci_t* hci = ctx;
446     zx_handle_close(hci->uart_socket);
447     free(hci);
448 }
449 
hci_open_command_channel(void * ctx,zx_handle_t * out_channel)450 static zx_status_t hci_open_command_channel(void* ctx, zx_handle_t* out_channel) {
451     hci_t* hci = ctx;
452     return hci_open_channel(hci, &hci->cmd_channel, out_channel);
453 }
454 
hci_open_acl_data_channel(void * ctx,zx_handle_t * out_channel)455 static zx_status_t hci_open_acl_data_channel(void* ctx, zx_handle_t* out_channel) {
456     hci_t* hci = ctx;
457     return hci_open_channel(hci, &hci->acl_channel, out_channel);
458 }
459 
hci_open_snoop_channel(void * ctx,zx_handle_t * out_channel)460 static zx_status_t hci_open_snoop_channel(void* ctx, zx_handle_t* out_channel) {
461     hci_t* hci = ctx;
462     return hci_open_channel(hci, &hci->snoop_channel, out_channel);
463 }
464 
465 static bt_hci_protocol_ops_t hci_protocol_ops = {
466     .open_command_channel = hci_open_command_channel,
467     .open_acl_data_channel = hci_open_acl_data_channel,
468     .open_snoop_channel = hci_open_snoop_channel,
469 };
470 
hci_get_protocol(void * ctx,uint32_t proto_id,void * protocol)471 static zx_status_t hci_get_protocol(void* ctx, uint32_t proto_id, void* protocol) {
472     hci_t* hci = ctx;
473     if (proto_id != ZX_PROTOCOL_BT_HCI) {
474         // Pass this on for drivers to load firmware / initialize
475         return device_get_protocol(hci->parent, proto_id, protocol);
476     }
477 
478     bt_hci_protocol_t* hci_proto = protocol;
479 
480     hci_proto->ops = &hci_protocol_ops;
481     hci_proto->ctx = ctx;
482     return ZX_OK;
483 };
484 
485 static zx_protocol_device_t hci_device_proto = {
486     .version = DEVICE_OPS_VERSION,
487     .get_protocol = hci_get_protocol,
488     .unbind = hci_unbind,
489     .release = hci_release,
490 };
491 
hci_bind(void * ctx,zx_device_t * parent)492 static zx_status_t hci_bind(void* ctx, zx_device_t* parent) {
493     serial_protocol_t serial;
494 
495     zx_status_t status = device_get_protocol(parent, ZX_PROTOCOL_SERIAL, &serial);
496     if (status != ZX_OK) {
497         zxlogf(ERROR, "bt-transport-uart: get protocol ZX_PROTOCOL_SERIAL failed\n");
498         return status;
499     }
500 
501     hci_t* hci = calloc(1, sizeof(hci_t));
502     if (!hci) {
503         zxlogf(ERROR, "bt-transport-uart: Not enough memory for hci_t\n");
504         return ZX_ERR_NO_MEMORY;
505     }
506 
507     status = serial_open_socket(&serial, &hci->uart_socket);
508      if (status != ZX_OK) {
509         zxlogf(ERROR, "bt-transport-uart: serial_open_socket failed: %s\n",
510                zx_status_get_string(status));
511         goto fail;
512     }
513 
514     zx_event_create(0, &hci->channels_changed_evt);
515     mtx_init(&hci->mutex, mtx_plain);
516     hci->parent = parent;
517     hci->cur_uart_packet_type = HCI_NONE;
518 
519     // pre-populate event packet indicators
520     hci->event_buffer[0] = HCI_EVENT;
521     hci->event_buffer_offset = 1;
522     hci->acl_buffer[0] = HCI_ACL_DATA;
523     hci->acl_buffer_offset = 1;
524 
525     serial_port_info_t info;
526     status = serial_get_info(&serial, &info);
527     if (status != ZX_OK) {
528         zxlogf(ERROR, "hci_bind: serial_get_info failed\n");
529         goto fail;
530     }
531     if (info.serial_class != SERIAL_CLASS_BLUETOOTH_HCI) {
532         zxlogf(ERROR, "hci_bind: info.device_class != SERIAL_CLASS_BLUETOOTH_HCI\n");
533         status = ZX_ERR_INTERNAL;
534         goto fail;
535     }
536 
537     // Copy the PID and VID from the platform device info so it can be filtered on
538     // for HCI drivers
539     zx_device_prop_t props[] = {
540       { BIND_PROTOCOL, 0, ZX_PROTOCOL_BT_TRANSPORT },
541       { BIND_SERIAL_VID, 0, info.serial_vid },
542       { BIND_SERIAL_PID, 0, info.serial_pid },
543     };
544 
545     device_add_args_t args = {
546         .version = DEVICE_ADD_ARGS_VERSION,
547         .name = "bt-transport-uart",
548         .ctx = hci,
549         .ops = &hci_device_proto,
550         .proto_id = ZX_PROTOCOL_BT_TRANSPORT,
551         .props = props,
552         .prop_count = countof(props),
553     };
554 
555     status = device_add(parent, &args, &hci->zxdev);
556     if (status == ZX_OK) {
557         return ZX_OK;
558     }
559 
560 fail:
561     zxlogf(ERROR, "hci_bind: bind failed: %s\n", zx_status_get_string(status));
562     hci_release(hci);
563     return status;
564 }
565 
566 static zx_driver_ops_t bt_hci_driver_ops = {
567     .version = DRIVER_OPS_VERSION,
568     .bind = hci_bind,
569 };
570 
571 // clang-format off
572 ZIRCON_DRIVER_BEGIN(bt_transport_uart, bt_hci_driver_ops, "zircon", "0.1", 2)
573     BI_ABORT_IF(NE, BIND_PROTOCOL, ZX_PROTOCOL_SERIAL),
574     BI_MATCH_IF(EQ, BIND_SERIAL_CLASS, SERIAL_CLASS_BLUETOOTH_HCI),
575 ZIRCON_DRIVER_END(bt_transport_uart)
576