1 /******************************************************************************
3 * Copyright (C) 2014 Google, Inc.
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
9 * http://www.apache.org/licenses/LICENSE-2.0
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
17 ******************************************************************************/
19 #define LOG_TAG "hci_layer"
22 #include <utils/Log.h>
27 #include "fixed_queue.h"
29 #include "hci_internals.h"
30 #include "hci_inject.h"
31 #include "hci_layer.h"
32 #include "low_power_manager.h"
34 #include "packet_fragmenter.h"
38 #define HCI_COMMAND_COMPLETE_EVT 0x0E
39 #define HCI_COMMAND_STATUS_EVT 0x0F
40 #define HCI_READ_BUFFER_SIZE 0x1005
41 #define HCI_LE_READ_BUFFER_SIZE 0x2002
43 #define INBOUND_PACKET_TYPE_COUNT 3
44 #define PACKET_TYPE_TO_INBOUND_INDEX(type) ((type) - 2)
45 #define PACKET_TYPE_TO_INDEX(type) ((type) - 1)
47 #define PREAMBLE_BUFFER_SIZE 4 // max preamble size, ACL
48 #define RETRIEVE_ACL_LENGTH(preamble) ((((preamble)[3]) << 8) | (preamble)[2])
50 #define MAX_WAITING_INTERNAL_COMMANDS 8
52 static const uint8_t preamble_sizes[] = {
53 HCI_COMMAND_PREAMBLE_SIZE,
54 HCI_ACL_PREAMBLE_SIZE,
55 HCI_SCO_PREAMBLE_SIZE,
56 HCI_EVENT_PREAMBLE_SIZE
59 static const uint16_t outbound_event_types[] =
61 MSG_HC_TO_STACK_HCI_ERR,
62 MSG_HC_TO_STACK_HCI_ACL,
63 MSG_HC_TO_STACK_HCI_SCO,
64 MSG_HC_TO_STACK_HCI_EVT
76 receive_state_t state;
77 uint16_t bytes_remaining;
78 uint8_t preamble[PREAMBLE_BUFFER_SIZE];
81 } packet_receive_data_t;
85 internal_command_cb callback;
86 } waiting_internal_command_t;
88 static const uint32_t EPILOG_TIMEOUT_MS = 3000;
91 static bool interface_created;
92 static hci_interface_t interface;
94 // Modules we import and callbacks we export
95 static const allocator_t *buffer_allocator;
96 static const btsnoop_interface_t *btsnoop;
97 static const hci_callbacks_t *callbacks;
98 static const hci_hal_interface_t *hal;
99 static const hci_hal_callbacks_t hal_callbacks;
100 static const hci_inject_interface_t *hci_inject;
101 static const low_power_manager_interface_t *low_power_manager;
102 static const packet_fragmenter_interface_t *packet_fragmenter;
103 static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks;
104 static const vendor_interface_t *vendor;
106 static thread_t *thread; // We own this
108 static volatile bool firmware_is_configured = false;
109 static volatile bool has_cleaned_up = false;
110 static alarm_t *epilog_alarm;
113 static int command_credits = 1;
114 static fixed_queue_t *command_queue;
115 static fixed_queue_t *packet_queue;
118 static fixed_queue_t *waiting_internal_commands;
119 static packet_receive_data_t incoming_packets[INBOUND_PACKET_TYPE_COUNT];
121 static void event_preload(void *context);
122 static void event_postload(void *context);
123 static void event_epilog(void *context);
124 static void event_command_ready(fixed_queue_t *queue, void *context);
125 static void event_packet_ready(fixed_queue_t *queue, void *context);
127 static void firmware_config_callback(bool success);
128 static void sco_config_callback(bool success);
129 static void epilog_finished_callback(bool success);
131 static void hal_says_data_ready(serial_data_type_t type);
132 static bool send_internal_command(uint16_t opcode, BT_HDR *packet, internal_command_cb callback);
133 static void start_epilog_wait_timer();
135 // Interface functions
137 static bool hci_init(
138 bdaddr_t local_bdaddr,
139 const allocator_t *upward_buffer_allocator,
140 const hci_callbacks_t *upper_callbacks) {
141 assert(local_bdaddr != NULL);
142 assert(upward_buffer_allocator != NULL);
143 assert(upper_callbacks != NULL);
145 ALOGI("%s", __func__);
147 // The host is only allowed to send at most one command initially,
148 // as per the Bluetooth spec, Volume 2, Part E, 4.4 (Command Flow Control)
149 // This value can change when you get a command complete or command status event.
151 firmware_is_configured = false;
152 has_cleaned_up = false;
154 epilog_alarm = alarm_new();
156 ALOGE("%s unable to create epilog alarm.", __func__);
160 command_queue = fixed_queue_new(SIZE_MAX);
161 if (!command_queue) {
162 ALOGE("%s unable to create pending command queue.", __func__);
166 packet_queue = fixed_queue_new(SIZE_MAX);
168 ALOGE("%s unable to create pending packet queue.", __func__);
172 thread = thread_new("hci_thread");
174 ALOGE("%s unable to create thread.", __func__);
178 waiting_internal_commands = fixed_queue_new(MAX_WAITING_INTERNAL_COMMANDS);
179 if (!waiting_internal_commands) {
180 ALOGE("%s unable to create waiting internal command queue.", __func__);
184 callbacks = upper_callbacks;
185 buffer_allocator = upward_buffer_allocator;
186 memset(incoming_packets, 0, sizeof(incoming_packets));
188 packet_fragmenter->init(&packet_fragmenter_callbacks, buffer_allocator);
190 fixed_queue_register_dequeue(command_queue, thread_get_reactor(thread), event_command_ready, NULL);
191 fixed_queue_register_dequeue(packet_queue, thread_get_reactor(thread), event_packet_ready, NULL);
193 vendor->open(local_bdaddr, buffer_allocator);
194 hal->init(&hal_callbacks, thread);
195 low_power_manager->init(thread);
197 vendor->set_callback(VENDOR_CONFIGURE_FIRMWARE, firmware_config_callback);
198 vendor->set_callback(VENDOR_CONFIGURE_SCO, sco_config_callback);
199 vendor->set_callback(VENDOR_DO_EPILOG, epilog_finished_callback);
200 vendor->set_send_internal_command_callback(send_internal_command);
202 if (!hci_inject->open(&interface, buffer_allocator)) {
203 // TODO(sharvil): gracefully propagate failures from this layer.
212 static void hci_cleanup() {
213 if (has_cleaned_up) {
214 ALOGW("%s already cleaned up for this session", __func__);
218 ALOGI("%s", __func__);
223 if (firmware_is_configured) {
224 start_epilog_wait_timer();
225 thread_post(thread, event_epilog, NULL);
233 fixed_queue_free(command_queue, buffer_allocator->free);
234 fixed_queue_free(packet_queue, buffer_allocator->free);
235 fixed_queue_free(waiting_internal_commands, osi_free);
237 packet_fragmenter->cleanup();
239 alarm_free(epilog_alarm);
242 low_power_manager->cleanup();
245 interface.set_chip_power_on(false);
250 firmware_is_configured = false;
251 has_cleaned_up = true;
254 static void set_chip_power_on(bool value) {
255 ALOGD("%s setting bluetooth chip power on to: %d", __func__, value);
257 int power_state = value ? BT_VND_PWR_ON : BT_VND_PWR_OFF;
258 vendor->send_command(VENDOR_CHIP_POWER_CONTROL, &power_state);
261 static void do_preload() {
262 ALOGD("%s posting preload work item", __func__);
263 thread_post(thread, event_preload, NULL);
266 static void do_postload() {
267 ALOGD("%s posting postload work item", __func__);
268 thread_post(thread, event_postload, NULL);
271 static void turn_on_logging(const char *path) {
272 ALOGD("%s", __func__);
277 ALOGW("%s wanted to start logging, but path was NULL", __func__);
280 static void turn_off_logging() {
281 ALOGD("%s", __func__);
285 static void transmit_downward(data_dispatcher_type_t type, void *data) {
286 if (type == MSG_STACK_TO_HC_HCI_CMD) {
287 fixed_queue_enqueue(command_queue, data);
289 fixed_queue_enqueue(packet_queue, data);
293 // Internal functions
295 // Inspects an incoming event for interesting information, like how many
296 // commands are now able to be sent. Returns true if the event should
297 // not proceed to higher layers (i.e. was intercepted for internal use).
298 static bool filter_incoming_event(BT_HDR *packet) {
299 uint8_t *stream = packet->data;
302 STREAM_TO_UINT8(event_code, stream);
303 STREAM_SKIP_UINT8(stream); // Skip the parameter total length field
305 if (event_code == HCI_COMMAND_COMPLETE_EVT) {
308 STREAM_TO_UINT8(command_credits, stream);
309 STREAM_TO_UINT16(opcode, stream);
311 // TODO make this look back in the commands rather than just the first one
312 waiting_internal_command_t *first_waiting = fixed_queue_try_peek(waiting_internal_commands);
313 if (first_waiting != NULL && opcode == first_waiting->opcode) {
314 fixed_queue_dequeue(waiting_internal_commands);
316 if (first_waiting->callback)
317 first_waiting->callback(packet);
319 buffer_allocator->free(packet);
321 osi_free(first_waiting);
325 } else if (event_code == HCI_COMMAND_STATUS_EVT) {
326 STREAM_SKIP_UINT8(stream); // Skip the status field
327 STREAM_TO_UINT8(command_credits, stream);
333 // Send an internal command. Called by the vendor library, and also
334 // internally by the HCI layer to fetch controller buffer sizes.
335 static bool send_internal_command(uint16_t opcode, BT_HDR *packet, internal_command_cb callback) {
336 waiting_internal_command_t *wait_entry = osi_calloc(sizeof(waiting_internal_command_t));
338 ALOGE("%s couldn't allocate space for wait entry.", __func__);
342 wait_entry->opcode = opcode;
343 wait_entry->callback = callback;
345 if (!fixed_queue_try_enqueue(waiting_internal_commands, wait_entry)) {
346 osi_free(wait_entry);
347 ALOGE("%s too many waiting internal commands. Rejecting 0x%04X", __func__, opcode);
351 packet->layer_specific = opcode;
352 transmit_downward(packet->event, packet);
356 static void request_acl_buffer_size_callback(void *response) {
357 BT_HDR *packet = (BT_HDR *)response;
358 uint8_t *stream = packet->data;
361 uint16_t data_size = 0;
363 stream += 3; // Skip the event header fields, and the number of hci command packets field
364 STREAM_TO_UINT16(opcode, stream);
365 STREAM_TO_UINT8(status, stream);
368 STREAM_TO_UINT16(data_size, stream);
370 if (opcode == HCI_READ_BUFFER_SIZE) {
372 packet_fragmenter->set_acl_data_size(data_size);
374 // Now request the ble buffer size, using the same buffer
375 packet->event = HCI_LE_READ_BUFFER_SIZE;
377 packet->layer_specific = 0;
378 packet->len = HCI_COMMAND_PREAMBLE_SIZE;
380 stream = packet->data;
381 UINT16_TO_STREAM(stream, HCI_LE_READ_BUFFER_SIZE);
382 UINT8_TO_STREAM(stream, 0); // no parameters
384 if (!send_internal_command(HCI_LE_READ_BUFFER_SIZE, packet, request_acl_buffer_size_callback)) {
385 buffer_allocator->free(packet);
386 ALOGI("%s couldn't send ble read buffer command, so postload finished.", __func__);
388 } else if (opcode == HCI_LE_READ_BUFFER_SIZE) {
390 packet_fragmenter->set_ble_acl_data_size(data_size);
392 buffer_allocator->free(packet);
393 ALOGI("%s postload finished.", __func__);
395 ALOGE("%s unexpected opcode %d", __func__, opcode);
399 static void request_acl_buffer_size() {
400 ALOGI("%s", __func__);
401 BT_HDR *packet = (BT_HDR *)buffer_allocator->alloc(sizeof(BT_HDR) + HCI_COMMAND_PREAMBLE_SIZE);
403 ALOGE("%s couldn't get buffer for packet.", __func__);
407 packet->event = MSG_STACK_TO_HC_HCI_CMD;
409 packet->layer_specific = 0;
410 packet->len = HCI_COMMAND_PREAMBLE_SIZE;
412 uint8_t *stream = packet->data;
413 UINT16_TO_STREAM(stream, HCI_READ_BUFFER_SIZE);
414 UINT8_TO_STREAM(stream, 0); // no parameters
416 if (!send_internal_command(HCI_READ_BUFFER_SIZE, packet, request_acl_buffer_size_callback)) {
417 buffer_allocator->free(packet);
418 ALOGE("%s couldn't send internal command, so postload aborted.", __func__);
422 static void sco_config_callback(UNUSED_ATTR bool success) {
423 request_acl_buffer_size();
426 static void firmware_config_callback(UNUSED_ATTR bool success) {
427 firmware_is_configured = true;
428 callbacks->preload_finished(true);
431 static void epilog_finished_callback(UNUSED_ATTR bool success) {
432 ALOGI("%s", __func__);
436 static void epilog_wait_timer_expired(UNUSED_ATTR void *context) {
437 ALOGI("%s", __func__);
441 static void start_epilog_wait_timer() {
442 alarm_set(epilog_alarm, EPILOG_TIMEOUT_MS, epilog_wait_timer_expired, NULL);
445 static void event_preload(UNUSED_ATTR void *context) {
446 ALOGI("%s", __func__);
448 vendor->send_async_command(VENDOR_CONFIGURE_FIRMWARE, NULL);
451 static void event_postload(UNUSED_ATTR void *context) {
452 ALOGI("%s", __func__);
453 if(vendor->send_async_command(VENDOR_CONFIGURE_SCO, NULL) == -1) {
454 // If couldn't configure sco, we won't get the sco configuration callback
455 // so go pretend to do it now
456 sco_config_callback(false);
460 static void event_epilog(UNUSED_ATTR void *context) {
461 vendor->send_async_command(VENDOR_DO_EPILOG, NULL);
464 static void event_command_ready(fixed_queue_t *queue, UNUSED_ATTR void *context) {
465 if (command_credits > 0) {
466 event_packet_ready(queue, context);
470 static void event_packet_ready(fixed_queue_t *queue, UNUSED_ATTR void *context) {
471 // The queue may be the command queue or the packet queue, we don't care
472 BT_HDR *packet = (BT_HDR *)fixed_queue_dequeue(queue);
474 low_power_manager->wake_assert();
475 packet_fragmenter->fragment_and_dispatch(packet);
476 low_power_manager->transmit_done();
479 // This function is not required to read all of a packet in one go, so
480 // be wary of reentry. But this function must return after finishing a packet.
481 static void hal_says_data_ready(serial_data_type_t type) {
482 packet_receive_data_t *incoming = &incoming_packets[PACKET_TYPE_TO_INBOUND_INDEX(type)];
485 while (hal->read_data(type, &byte, 1, false) != 0) {
486 switch (incoming->state) {
488 // Initialize and prepare to jump to the preamble reading state
489 incoming->bytes_remaining = preamble_sizes[PACKET_TYPE_TO_INDEX(type)];
490 memset(incoming->preamble, 0, PREAMBLE_BUFFER_SIZE);
492 incoming->state = PREAMBLE;
493 // INTENTIONAL FALLTHROUGH
495 incoming->preamble[incoming->index] = byte;
497 incoming->bytes_remaining--;
499 if (incoming->bytes_remaining == 0) {
500 // For event and sco preambles, the last byte we read is the length
501 incoming->bytes_remaining = (type == DATA_TYPE_ACL) ? RETRIEVE_ACL_LENGTH(incoming->preamble) : byte;
503 size_t buffer_size = BT_HDR_SIZE + incoming->index + incoming->bytes_remaining;
504 incoming->buffer = (BT_HDR *)buffer_allocator->alloc(buffer_size);
506 if (!incoming->buffer) {
507 ALOGE("%s error getting buffer for incoming packet", __func__);
508 // Can't read any more of this current packet, so jump out
509 incoming->state = incoming->bytes_remaining == 0 ? BRAND_NEW : IGNORE;
513 // Initialize the buffer
514 incoming->buffer->offset = 0;
515 incoming->buffer->layer_specific = 0;
516 incoming->buffer->event = outbound_event_types[PACKET_TYPE_TO_INDEX(type)];
517 memcpy(incoming->buffer->data, incoming->preamble, incoming->index);
519 incoming->state = incoming->bytes_remaining > 0 ? BODY : FINISHED;
524 incoming->buffer->data[incoming->index] = byte;
526 incoming->bytes_remaining--;
528 size_t bytes_read = hal->read_data(type, (incoming->buffer->data + incoming->index), incoming->bytes_remaining, false);
529 incoming->index += bytes_read;
530 incoming->bytes_remaining -= bytes_read;
532 incoming->state = incoming->bytes_remaining == 0 ? FINISHED : incoming->state;
535 incoming->bytes_remaining--;
536 incoming->state = incoming->bytes_remaining == 0 ? BRAND_NEW : incoming->state;
539 ALOGE("%s the state machine should not have been left in the finished state.", __func__);
543 if (incoming->state == FINISHED) {
544 incoming->buffer->len = incoming->index;
545 btsnoop->capture(incoming->buffer, true);
547 if (type != DATA_TYPE_EVENT || !filter_incoming_event(incoming->buffer)) {
548 packet_fragmenter->reassemble_and_dispatch(incoming->buffer);
551 // We don't control the buffer anymore
552 incoming->buffer = NULL;
553 incoming->state = BRAND_NEW;
554 hal->packet_finished(type);
556 // We return after a packet is finished for two reasons:
557 // 1. The type of the next packet could be different.
558 // 2. We don't want to hog cpu time.
564 // TODO(zachoverflow): we seem to do this a couple places, like the HCI inject module. #centralize
565 static serial_data_type_t event_to_data_type(uint16_t event) {
566 if (event == MSG_STACK_TO_HC_HCI_ACL)
567 return DATA_TYPE_ACL;
568 else if (event == MSG_STACK_TO_HC_HCI_SCO)
569 return DATA_TYPE_SCO;
570 else if (event == MSG_STACK_TO_HC_HCI_CMD)
571 return DATA_TYPE_COMMAND;
573 ALOGE("%s invalid event type, could not translate.", __func__);
578 // Callback for the fragmenter to send a fragment
579 static void transmit_fragment(BT_HDR *packet, bool send_transmit_finished) {
581 uint8_t *stream = packet->data + packet->offset;
582 uint16_t event = packet->event & MSG_EVT_MASK;
583 serial_data_type_t type = event_to_data_type(event);
585 if (event == MSG_STACK_TO_HC_HCI_CMD) {
587 STREAM_TO_UINT16(opcode, stream);
590 btsnoop->capture(packet, false);
591 hal->transmit_data(type, packet->data + packet->offset, packet->len);
593 if (event == MSG_STACK_TO_HC_HCI_CMD
594 && !fixed_queue_is_empty(waiting_internal_commands)
595 && packet->layer_specific == opcode) {
596 // This is an internal command, so nobody owns the buffer now
597 buffer_allocator->free(packet);
598 } else if (send_transmit_finished) {
599 callbacks->transmit_finished(packet, true);
603 // Callback for the fragmenter to dispatch up a completely reassembled packet
604 static void dispatch_reassembled(BT_HDR *packet) {
605 data_dispatcher_dispatch(
606 interface.upward_dispatcher,
607 packet->event & MSG_EVT_MASK,
612 static void fragmenter_transmit_finished(void *buffer, bool all_fragments_sent) {
613 callbacks->transmit_finished(buffer, all_fragments_sent);
616 static void init_layer_interface() {
617 if (!interface_created) {
618 interface.init = hci_init;
619 interface.cleanup = hci_cleanup;
621 interface.set_chip_power_on = set_chip_power_on;
622 interface.send_low_power_command = low_power_manager->post_command;
623 interface.do_preload = do_preload;
624 interface.do_postload = do_postload;
625 interface.turn_on_logging = turn_on_logging;
626 interface.turn_off_logging = turn_off_logging;
628 // It's probably ok for this to live forever. It's small and
629 // there's only one instance of the hci interface.
630 interface.upward_dispatcher = data_dispatcher_new("hci_layer");
631 if (!interface.upward_dispatcher) {
632 ALOGE("%s could not create upward dispatcher.", __func__);
636 interface.transmit_downward = transmit_downward;
637 interface_created = true;
641 static const hci_hal_callbacks_t hal_callbacks = {
645 static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks = {
647 dispatch_reassembled,
648 fragmenter_transmit_finished
651 const hci_interface_t *hci_layer_get_interface() {
652 hal = hci_hal_get_interface();
653 btsnoop = btsnoop_get_interface();
654 hci_inject = hci_inject_get_interface();
655 packet_fragmenter = packet_fragmenter_get_interface();
656 vendor = vendor_get_interface();
657 low_power_manager = low_power_manager_get_interface();
659 init_layer_interface();
663 const hci_interface_t *hci_layer_get_test_interface(
664 const hci_hal_interface_t *hal_interface,
665 const btsnoop_interface_t *btsnoop_interface,
666 const hci_inject_interface_t *hci_inject_interface,
667 const packet_fragmenter_interface_t *packet_fragmenter_interface,
668 const vendor_interface_t *vendor_interface,
669 const low_power_manager_interface_t *low_power_manager_interface) {
672 btsnoop = btsnoop_interface;
673 hci_inject = hci_inject_interface;
674 packet_fragmenter = packet_fragmenter_interface;
675 vendor = vendor_interface;
676 low_power_manager = low_power_manager_interface;
678 init_layer_interface();