Home | History | Annotate | Download | only in src
      1 /******************************************************************************
      2  *
      3  *  Copyright (C) 2014 Google, Inc.
      4  *
      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:
      8  *
      9  *  http://www.apache.org/licenses/LICENSE-2.0
     10  *
     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.
     16  *
     17  ******************************************************************************/
     18 
     19 #define LOG_TAG "bt_hci"
     20 
     21 #include "hci_layer.h"
     22 
     23 #include <base/bind.h>
     24 #include <base/logging.h>
     25 #include <base/run_loop.h>
     26 #include <base/sequenced_task_runner.h>
     27 #include <base/threading/thread.h>
     28 
     29 #include <signal.h>
     30 #include <string.h>
     31 #include <sys/types.h>
     32 #include <unistd.h>
     33 
     34 #include <chrono>
     35 #include <mutex>
     36 
     37 #include "btcore/include/module.h"
     38 #include "btsnoop.h"
     39 #include "buffer_allocator.h"
     40 #include "hci_inject.h"
     41 #include "hci_internals.h"
     42 #include "hcidefs.h"
     43 #include "hcimsgs.h"
     44 #include "osi/include/alarm.h"
     45 #include "osi/include/list.h"
     46 #include "osi/include/log.h"
     47 #include "osi/include/properties.h"
     48 #include "osi/include/reactor.h"
     49 #include "packet_fragmenter.h"
     50 
     51 #define BT_HCI_TIMEOUT_TAG_NUM 1010000
     52 
     53 extern void hci_initialize();
     54 extern void hci_transmit(BT_HDR* packet);
     55 extern void hci_close();
     56 extern int hci_open_firmware_log_file();
     57 extern void hci_close_firmware_log_file(int fd);
     58 extern void hci_log_firmware_debug_packet(int fd, BT_HDR* packet);
     59 
     60 static int hci_firmware_log_fd = INVALID_FD;
     61 
     62 typedef struct {
     63   uint16_t opcode;
     64   future_t* complete_future;
     65   command_complete_cb complete_callback;
     66   command_status_cb status_callback;
     67   void* context;
     68   BT_HDR* command;
     69   std::chrono::time_point<std::chrono::steady_clock> timestamp;
     70 } waiting_command_t;
     71 
     72 // Using a define here, because it can be stringified for the property lookup
     73 #define DEFAULT_STARTUP_TIMEOUT_MS 8000
     74 #define STRING_VALUE_OF(x) #x
     75 
     76 // RT priority for HCI thread
     77 static const int BT_HCI_RT_PRIORITY = 1;
     78 
     79 // Abort if there is no response to an HCI command.
     80 static const uint32_t COMMAND_PENDING_TIMEOUT_MS = 2000;
     81 static const uint32_t COMMAND_TIMEOUT_RESTART_US = 5000000;
     82 
     83 // Our interface
     84 static bool interface_created;
     85 static hci_t interface;
     86 
     87 // Modules we import and callbacks we export
     88 static const allocator_t* buffer_allocator;
     89 static const btsnoop_t* btsnoop;
     90 static const packet_fragmenter_t* packet_fragmenter;
     91 
     92 static future_t* startup_future;
     93 static thread_t* thread;  // We own this
     94 static std::mutex message_loop_mutex;
     95 static base::MessageLoop* message_loop_ = nullptr;
     96 static base::RunLoop* run_loop_ = nullptr;
     97 
     98 static alarm_t* startup_timer;
     99 
    100 // Outbound-related
    101 static int command_credits = 1;
    102 static std::mutex command_credits_mutex;
    103 static std::queue<base::Closure> command_queue;
    104 
    105 // Inbound-related
    106 static alarm_t* command_response_timer;
    107 static list_t* commands_pending_response;
    108 static std::recursive_mutex commands_pending_response_mutex;
    109 
    110 // The hand-off point for data going to a higher layer, set by the higher layer
    111 static base::Callback<void(const tracked_objects::Location&, BT_HDR*)>
    112     send_data_upwards;
    113 
    114 static bool filter_incoming_event(BT_HDR* packet);
    115 static waiting_command_t* get_waiting_command(command_opcode_t opcode);
    116 static int get_num_waiting_commands();
    117 
    118 static void event_finish_startup(void* context);
    119 static void startup_timer_expired(void* context);
    120 
    121 static void enqueue_command(waiting_command_t* wait_entry);
    122 static void event_command_ready(waiting_command_t* wait_entry);
    123 static void enqueue_packet(void* packet);
    124 static void event_packet_ready(void* packet);
    125 static void command_timed_out(void* context);
    126 
    127 static void update_command_response_timer(void);
    128 
    129 static void transmit_fragment(BT_HDR* packet, bool send_transmit_finished);
    130 static void dispatch_reassembled(BT_HDR* packet);
    131 static void fragmenter_transmit_finished(BT_HDR* packet,
    132                                          bool all_fragments_sent);
    133 
    134 static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks = {
    135     transmit_fragment, dispatch_reassembled, fragmenter_transmit_finished};
    136 
    137 void initialization_complete() {
    138   std::lock_guard<std::mutex> lock(message_loop_mutex);
    139   message_loop_->task_runner()->PostTask(
    140       FROM_HERE, base::Bind(&event_finish_startup, nullptr));
    141 }
    142 
    143 void hci_event_received(const tracked_objects::Location& from_here,
    144                         BT_HDR* packet) {
    145   btsnoop->capture(packet, true);
    146 
    147   if (!filter_incoming_event(packet)) {
    148     send_data_upwards.Run(from_here, packet);
    149   }
    150 }
    151 
    152 void acl_event_received(BT_HDR* packet) {
    153   btsnoop->capture(packet, true);
    154   packet_fragmenter->reassemble_and_dispatch(packet);
    155 }
    156 
    157 void sco_data_received(BT_HDR* packet) {
    158   btsnoop->capture(packet, true);
    159   packet_fragmenter->reassemble_and_dispatch(packet);
    160 }
    161 
    162 // Module lifecycle functions
    163 
    164 static future_t* hci_module_shut_down();
    165 
    166 void message_loop_run(UNUSED_ATTR void* context) {
    167   {
    168     std::lock_guard<std::mutex> lock(message_loop_mutex);
    169     message_loop_ = new base::MessageLoop();
    170     run_loop_ = new base::RunLoop();
    171   }
    172 
    173   message_loop_->task_runner()->PostTask(FROM_HERE,
    174                                          base::Bind(&hci_initialize));
    175   run_loop_->Run();
    176 
    177   {
    178     std::lock_guard<std::mutex> lock(message_loop_mutex);
    179     delete message_loop_;
    180     message_loop_ = nullptr;
    181     delete run_loop_;
    182     run_loop_ = nullptr;
    183   }
    184 }
    185 
    186 static future_t* hci_module_start_up(void) {
    187   LOG_INFO(LOG_TAG, "%s", __func__);
    188 
    189   // The host is only allowed to send at most one command initially,
    190   // as per the Bluetooth spec, Volume 2, Part E, 4.4 (Command Flow Control)
    191   // This value can change when you get a command complete or command status
    192   // event.
    193   command_credits = 1;
    194 
    195   // For now, always use the default timeout on non-Android builds.
    196   period_ms_t startup_timeout_ms = DEFAULT_STARTUP_TIMEOUT_MS;
    197 
    198   // Grab the override startup timeout ms, if present.
    199   char timeout_prop[PROPERTY_VALUE_MAX];
    200   if (!osi_property_get("bluetooth.enable_timeout_ms", timeout_prop,
    201                         STRING_VALUE_OF(DEFAULT_STARTUP_TIMEOUT_MS)) ||
    202       (startup_timeout_ms = atoi(timeout_prop)) < 100)
    203     startup_timeout_ms = DEFAULT_STARTUP_TIMEOUT_MS;
    204 
    205   startup_timer = alarm_new("hci.startup_timer");
    206   if (!startup_timer) {
    207     LOG_ERROR(LOG_TAG, "%s unable to create startup timer.", __func__);
    208     goto error;
    209   }
    210 
    211   command_response_timer = alarm_new("hci.command_response_timer");
    212   if (!command_response_timer) {
    213     LOG_ERROR(LOG_TAG, "%s unable to create command response timer.", __func__);
    214     goto error;
    215   }
    216 
    217   thread = thread_new("hci_thread");
    218   if (!thread) {
    219     LOG_ERROR(LOG_TAG, "%s unable to create thread.", __func__);
    220     goto error;
    221   }
    222   if (!thread_set_rt_priority(thread, BT_HCI_RT_PRIORITY)) {
    223     LOG_ERROR(LOG_TAG, "%s unable to make thread RT.", __func__);
    224   }
    225 
    226   commands_pending_response = list_new(NULL);
    227   if (!commands_pending_response) {
    228     LOG_ERROR(LOG_TAG,
    229               "%s unable to create list for commands pending response.",
    230               __func__);
    231     goto error;
    232   }
    233 
    234   // Make sure we run in a bounded amount of time
    235   future_t* local_startup_future;
    236   local_startup_future = future_new();
    237   startup_future = local_startup_future;
    238   alarm_set(startup_timer, startup_timeout_ms, startup_timer_expired, NULL);
    239 
    240   packet_fragmenter->init(&packet_fragmenter_callbacks);
    241 
    242   thread_post(thread, message_loop_run, NULL);
    243 
    244   LOG_DEBUG(LOG_TAG, "%s starting async portion", __func__);
    245   return local_startup_future;
    246 
    247 error:
    248   hci_module_shut_down();  // returns NULL so no need to wait for it
    249   return future_new_immediate(FUTURE_FAIL);
    250 }
    251 
    252 static future_t* hci_module_shut_down() {
    253   LOG_INFO(LOG_TAG, "%s", __func__);
    254 
    255   // Free the timers
    256   {
    257     std::lock_guard<std::recursive_mutex> lock(commands_pending_response_mutex);
    258     alarm_free(command_response_timer);
    259     command_response_timer = NULL;
    260     alarm_free(startup_timer);
    261     startup_timer = NULL;
    262   }
    263 
    264   {
    265     std::lock_guard<std::mutex> lock(message_loop_mutex);
    266     message_loop_->task_runner()->PostTask(FROM_HERE, run_loop_->QuitClosure());
    267   }
    268 
    269   // Stop the thread to prevent Send() calls.
    270   if (thread) {
    271     thread_stop(thread);
    272     thread_join(thread);
    273   }
    274 
    275   // Close HCI to prevent callbacks.
    276   hci_close();
    277 
    278   {
    279     std::lock_guard<std::recursive_mutex> lock(commands_pending_response_mutex);
    280     list_free(commands_pending_response);
    281     commands_pending_response = NULL;
    282   }
    283 
    284   packet_fragmenter->cleanup();
    285 
    286   thread_free(thread);
    287   thread = NULL;
    288 
    289   return NULL;
    290 }
    291 
    292 EXPORT_SYMBOL extern const module_t hci_module = {
    293     .name = HCI_MODULE,
    294     .init = NULL,
    295     .start_up = hci_module_start_up,
    296     .shut_down = hci_module_shut_down,
    297     .clean_up = NULL,
    298     .dependencies = {BTSNOOP_MODULE, NULL}};
    299 
    300 // Interface functions
    301 
    302 static void set_data_cb(
    303     base::Callback<void(const tracked_objects::Location&, BT_HDR*)>
    304         send_data_cb) {
    305   send_data_upwards = std::move(send_data_cb);
    306 }
    307 
    308 static void transmit_command(BT_HDR* command,
    309                              command_complete_cb complete_callback,
    310                              command_status_cb status_callback, void* context) {
    311   waiting_command_t* wait_entry = reinterpret_cast<waiting_command_t*>(
    312       osi_calloc(sizeof(waiting_command_t)));
    313 
    314   uint8_t* stream = command->data + command->offset;
    315   STREAM_TO_UINT16(wait_entry->opcode, stream);
    316   wait_entry->complete_callback = complete_callback;
    317   wait_entry->status_callback = status_callback;
    318   wait_entry->command = command;
    319   wait_entry->context = context;
    320 
    321   // Store the command message type in the event field
    322   // in case the upper layer didn't already
    323   command->event = MSG_STACK_TO_HC_HCI_CMD;
    324 
    325   enqueue_command(wait_entry);
    326 }
    327 
    328 static future_t* transmit_command_futured(BT_HDR* command) {
    329   waiting_command_t* wait_entry = reinterpret_cast<waiting_command_t*>(
    330       osi_calloc(sizeof(waiting_command_t)));
    331   future_t* future = future_new();
    332 
    333   uint8_t* stream = command->data + command->offset;
    334   STREAM_TO_UINT16(wait_entry->opcode, stream);
    335   wait_entry->complete_future = future;
    336   wait_entry->command = command;
    337 
    338   // Store the command message type in the event field
    339   // in case the upper layer didn't already
    340   command->event = MSG_STACK_TO_HC_HCI_CMD;
    341 
    342   enqueue_command(wait_entry);
    343   return future;
    344 }
    345 
    346 static void transmit_downward(uint16_t type, void* data) {
    347   if (type == MSG_STACK_TO_HC_HCI_CMD) {
    348     // TODO(zachoverflow): eliminate this call
    349     transmit_command((BT_HDR*)data, NULL, NULL, NULL);
    350     LOG_WARN(LOG_TAG,
    351              "%s legacy transmit of command. Use transmit_command instead.",
    352              __func__);
    353   } else {
    354     enqueue_packet(data);
    355   }
    356 }
    357 
    358 // Start up functions
    359 
    360 static void event_finish_startup(UNUSED_ATTR void* context) {
    361   LOG_INFO(LOG_TAG, "%s", __func__);
    362   std::lock_guard<std::recursive_mutex> lock(commands_pending_response_mutex);
    363   alarm_cancel(startup_timer);
    364   future_ready(startup_future, FUTURE_SUCCESS);
    365   startup_future = NULL;
    366 }
    367 
    368 static void startup_timer_expired(UNUSED_ATTR void* context) {
    369   LOG_ERROR(LOG_TAG, "%s", __func__);
    370 
    371   std::lock_guard<std::recursive_mutex> lock(commands_pending_response_mutex);
    372   future_ready(startup_future, FUTURE_FAIL);
    373   startup_future = NULL;
    374 }
    375 
    376 // Command/packet transmitting functions
    377 static void enqueue_command(waiting_command_t* wait_entry) {
    378   base::Closure callback = base::Bind(&event_command_ready, wait_entry);
    379 
    380   std::lock_guard<std::mutex> command_credits_lock(command_credits_mutex);
    381   if (command_credits > 0) {
    382     std::lock_guard<std::mutex> message_loop_lock(message_loop_mutex);
    383     if (message_loop_ == nullptr) {
    384       // HCI Layer was shut down
    385       buffer_allocator->free(wait_entry->command);
    386       osi_free(wait_entry);
    387       return;
    388     }
    389     message_loop_->task_runner()->PostTask(FROM_HERE, std::move(callback));
    390     command_credits--;
    391   } else {
    392     command_queue.push(std::move(callback));
    393   }
    394 }
    395 
    396 static void event_command_ready(waiting_command_t* wait_entry) {
    397   /// Move it to the list of commands awaiting response
    398   std::lock_guard<std::recursive_mutex> lock(commands_pending_response_mutex);
    399   wait_entry->timestamp = std::chrono::steady_clock::now();
    400   list_append(commands_pending_response, wait_entry);
    401 
    402   // Send it off
    403   packet_fragmenter->fragment_and_dispatch(wait_entry->command);
    404 
    405   update_command_response_timer();
    406 }
    407 
    408 static void enqueue_packet(void* packet) {
    409   std::lock_guard<std::mutex> lock(message_loop_mutex);
    410   if (message_loop_ == nullptr) {
    411     // HCI Layer was shut down
    412     buffer_allocator->free(packet);
    413     return;
    414   }
    415   message_loop_->task_runner()->PostTask(
    416       FROM_HERE, base::Bind(&event_packet_ready, packet));
    417 }
    418 
    419 static void event_packet_ready(void* pkt) {
    420   // The queue may be the command queue or the packet queue, we don't care
    421   BT_HDR* packet = (BT_HDR*)pkt;
    422   packet_fragmenter->fragment_and_dispatch(packet);
    423 }
    424 
    425 // Callback for the fragmenter to send a fragment
    426 static void transmit_fragment(BT_HDR* packet, bool send_transmit_finished) {
    427   btsnoop->capture(packet, false);
    428 
    429   hci_transmit(packet);
    430 
    431   uint16_t event = packet->event & MSG_EVT_MASK;
    432   if (event != MSG_STACK_TO_HC_HCI_CMD && send_transmit_finished)
    433     buffer_allocator->free(packet);
    434 }
    435 
    436 static void fragmenter_transmit_finished(BT_HDR* packet,
    437                                          bool all_fragments_sent) {
    438   if (all_fragments_sent) {
    439     buffer_allocator->free(packet);
    440   } else {
    441     // This is kind of a weird case, since we're dispatching a partially sent
    442     // packet up to a higher layer.
    443     // TODO(zachoverflow): rework upper layer so this isn't necessary.
    444 
    445     send_data_upwards.Run(FROM_HERE, packet);
    446   }
    447 }
    448 
    449 // Print debugging information and quit. Don't dereference original_wait_entry.
    450 static void command_timed_out(void* original_wait_entry) {
    451   std::unique_lock<std::recursive_mutex> lock(commands_pending_response_mutex);
    452 
    453   LOG_ERROR(LOG_TAG, "%s: %d commands pending response", __func__,
    454             get_num_waiting_commands());
    455 
    456   for (const list_node_t* node = list_begin(commands_pending_response);
    457        node != list_end(commands_pending_response); node = list_next(node)) {
    458     waiting_command_t* wait_entry =
    459         reinterpret_cast<waiting_command_t*>(list_node(node));
    460 
    461     int wait_time_ms =
    462         std::chrono::duration_cast<std::chrono::milliseconds>(
    463             std::chrono::steady_clock::now() - wait_entry->timestamp)
    464             .count();
    465     LOG_ERROR(LOG_TAG, "%s: Waited %d ms for a response to opcode: 0x%x %s",
    466               __func__, wait_time_ms, wait_entry->opcode,
    467               (wait_entry == original_wait_entry) ? "*matches timer*" : "");
    468 
    469     // Dump the length field and the first byte of the payload, if present.
    470     uint8_t* command = wait_entry->command->data + wait_entry->command->offset;
    471     if (wait_entry->command->len > 3) {
    472       LOG_ERROR(LOG_TAG, "%s: Size %d Hex %02x %02x %02x %02x", __func__,
    473                 wait_entry->command->len, command[0], command[1], command[2],
    474                 command[3]);
    475     } else {
    476       LOG_ERROR(LOG_TAG, "%s: Size %d Hex %02x %02x %02x", __func__,
    477                 wait_entry->command->len, command[0], command[1], command[2]);
    478     }
    479 
    480     LOG_EVENT_INT(BT_HCI_TIMEOUT_TAG_NUM, wait_entry->opcode);
    481   }
    482   lock.unlock();
    483 
    484   LOG_ERROR(LOG_TAG, "%s: requesting a firmware dump.", __func__);
    485 
    486   /* Allocate a buffer to hold the HCI command. */
    487   BT_HDR* bt_hdr =
    488       static_cast<BT_HDR*>(osi_malloc(sizeof(BT_HDR) + HCIC_PREAMBLE_SIZE));
    489 
    490   bt_hdr->len = HCIC_PREAMBLE_SIZE;
    491   bt_hdr->event = MSG_STACK_TO_HC_HCI_CMD;
    492   bt_hdr->offset = 0;
    493 
    494   uint8_t* hci_packet = reinterpret_cast<uint8_t*>(bt_hdr + 1);
    495 
    496   UINT16_TO_STREAM(hci_packet,
    497                    HCI_GRP_VENDOR_SPECIFIC | HCI_CONTROLLER_DEBUG_INFO_OCF);
    498   UINT8_TO_STREAM(hci_packet, 0);  // No parameters
    499 
    500   hci_firmware_log_fd = hci_open_firmware_log_file();
    501 
    502   transmit_fragment(bt_hdr, true);
    503 
    504   osi_free(bt_hdr);
    505 
    506   LOG_ERROR(LOG_TAG, "%s restarting the Bluetooth process.", __func__);
    507   usleep(COMMAND_TIMEOUT_RESTART_US);
    508   hci_close_firmware_log_file(hci_firmware_log_fd);
    509 
    510   // We shouldn't try to recover the stack from this command timeout.
    511   // If it's caused by a software bug, fix it. If it's a hardware bug, fix it.
    512   abort();
    513 }
    514 
    515 // Event/packet receiving functions
    516 void process_command_credits(int credits) {
    517   std::lock_guard<std::mutex> command_credits_lock(command_credits_mutex);
    518   std::lock_guard<std::mutex> message_loop_lock(message_loop_mutex);
    519 
    520   if (message_loop_ == nullptr) {
    521     // HCI Layer was shut down
    522     return;
    523   }
    524 
    525   // Subtract commands in flight.
    526   command_credits = credits - get_num_waiting_commands();
    527 
    528   while (command_credits > 0 && command_queue.size() > 0) {
    529     message_loop_->task_runner()->PostTask(FROM_HERE,
    530                                            std::move(command_queue.front()));
    531     command_queue.pop();
    532     command_credits--;
    533   }
    534 }
    535 
    536 // Returns true if the event was intercepted and should not proceed to
    537 // higher layers. Also inspects an incoming event for interesting
    538 // information, like how many commands are now able to be sent.
    539 static bool filter_incoming_event(BT_HDR* packet) {
    540   waiting_command_t* wait_entry = NULL;
    541   uint8_t* stream = packet->data;
    542   uint8_t event_code;
    543   int credits = 0;
    544   command_opcode_t opcode;
    545 
    546   STREAM_TO_UINT8(event_code, stream);
    547   STREAM_SKIP_UINT8(stream);  // Skip the parameter total length field
    548 
    549   if (event_code == HCI_COMMAND_COMPLETE_EVT) {
    550     STREAM_TO_UINT8(credits, stream);
    551     STREAM_TO_UINT16(opcode, stream);
    552 
    553     wait_entry = get_waiting_command(opcode);
    554 
    555     process_command_credits(credits);
    556 
    557     if (!wait_entry) {
    558       if (opcode != HCI_COMMAND_NONE) {
    559         LOG_WARN(LOG_TAG,
    560                  "%s command complete event with no matching command (opcode: "
    561                  "0x%04x).",
    562                  __func__, opcode);
    563       }
    564     } else {
    565       update_command_response_timer();
    566       if (wait_entry->complete_callback) {
    567         wait_entry->complete_callback(packet, wait_entry->context);
    568       } else if (wait_entry->complete_future) {
    569         future_ready(wait_entry->complete_future, packet);
    570       }
    571     }
    572 
    573     goto intercepted;
    574   } else if (event_code == HCI_COMMAND_STATUS_EVT) {
    575     uint8_t status;
    576     STREAM_TO_UINT8(status, stream);
    577     STREAM_TO_UINT8(credits, stream);
    578     STREAM_TO_UINT16(opcode, stream);
    579 
    580     // If a command generates a command status event, it won't be getting a
    581     // command complete event
    582     wait_entry = get_waiting_command(opcode);
    583 
    584     process_command_credits(credits);
    585 
    586     if (!wait_entry) {
    587       LOG_WARN(
    588           LOG_TAG,
    589           "%s command status event with no matching command. opcode: 0x%04x",
    590           __func__, opcode);
    591     } else {
    592       update_command_response_timer();
    593       if (wait_entry->status_callback)
    594         wait_entry->status_callback(status, wait_entry->command,
    595                                     wait_entry->context);
    596     }
    597 
    598     goto intercepted;
    599   } else if (event_code == HCI_VSE_SUBCODE_DEBUG_INFO_SUB_EVT) {
    600     if (hci_firmware_log_fd == INVALID_FD)
    601       hci_firmware_log_fd = hci_open_firmware_log_file();
    602 
    603     if (hci_firmware_log_fd != INVALID_FD)
    604       hci_log_firmware_debug_packet(hci_firmware_log_fd, packet);
    605 
    606     buffer_allocator->free(packet);
    607     return true;
    608   }
    609 
    610   return false;
    611 
    612 intercepted:
    613   if (wait_entry) {
    614     // If it has a callback, it's responsible for freeing the packet
    615     if (event_code == HCI_COMMAND_STATUS_EVT ||
    616         (!wait_entry->complete_callback && !wait_entry->complete_future))
    617       buffer_allocator->free(packet);
    618 
    619     // If it has a callback, it's responsible for freeing the command
    620     if (event_code == HCI_COMMAND_COMPLETE_EVT || !wait_entry->status_callback)
    621       buffer_allocator->free(wait_entry->command);
    622 
    623     osi_free(wait_entry);
    624   } else {
    625     buffer_allocator->free(packet);
    626   }
    627 
    628   return true;
    629 }
    630 
    631 // Callback for the fragmenter to dispatch up a completely reassembled packet
    632 static void dispatch_reassembled(BT_HDR* packet) {
    633   // Events should already have been dispatched before this point
    634   CHECK((packet->event & MSG_EVT_MASK) != MSG_HC_TO_STACK_HCI_EVT);
    635   CHECK(!send_data_upwards.is_null());
    636 
    637   send_data_upwards.Run(FROM_HERE, packet);
    638 }
    639 
    640 // Misc internal functions
    641 
    642 static waiting_command_t* get_waiting_command(command_opcode_t opcode) {
    643   std::lock_guard<std::recursive_mutex> lock(commands_pending_response_mutex);
    644 
    645   for (const list_node_t* node = list_begin(commands_pending_response);
    646        node != list_end(commands_pending_response); node = list_next(node)) {
    647     waiting_command_t* wait_entry =
    648         reinterpret_cast<waiting_command_t*>(list_node(node));
    649 
    650     if (!wait_entry || wait_entry->opcode != opcode) continue;
    651 
    652     list_remove(commands_pending_response, wait_entry);
    653 
    654     return wait_entry;
    655   }
    656 
    657   return NULL;
    658 }
    659 
    660 static int get_num_waiting_commands() {
    661   std::lock_guard<std::recursive_mutex> lock(commands_pending_response_mutex);
    662   return list_length(commands_pending_response);
    663 }
    664 
    665 static void update_command_response_timer(void) {
    666   std::lock_guard<std::recursive_mutex> lock(commands_pending_response_mutex);
    667 
    668   if (command_response_timer == NULL) return;
    669   if (list_is_empty(commands_pending_response)) {
    670     alarm_cancel(command_response_timer);
    671   } else {
    672     alarm_set(command_response_timer, COMMAND_PENDING_TIMEOUT_MS,
    673               command_timed_out, list_front(commands_pending_response));
    674   }
    675 }
    676 
    677 static void init_layer_interface() {
    678   if (!interface_created) {
    679     // It's probably ok for this to live forever. It's small and
    680     // there's only one instance of the hci interface.
    681 
    682     interface.set_data_cb = set_data_cb;
    683     interface.transmit_command = transmit_command;
    684     interface.transmit_command_futured = transmit_command_futured;
    685     interface.transmit_downward = transmit_downward;
    686     interface_created = true;
    687   }
    688 }
    689 
    690 void hci_layer_cleanup_interface() {
    691   if (interface_created) {
    692     send_data_upwards.Reset();
    693 
    694     interface.set_data_cb = NULL;
    695     interface.transmit_command = NULL;
    696     interface.transmit_command_futured = NULL;
    697     interface.transmit_downward = NULL;
    698     interface_created = false;
    699   }
    700 }
    701 
    702 const hci_t* hci_layer_get_interface() {
    703   buffer_allocator = buffer_allocator_get_interface();
    704   btsnoop = btsnoop_get_interface();
    705   packet_fragmenter = packet_fragmenter_get_interface();
    706 
    707   init_layer_interface();
    708 
    709   return &interface;
    710 }
    711 
    712 const hci_t* hci_layer_get_test_interface(
    713     const allocator_t* buffer_allocator_interface,
    714     const btsnoop_t* btsnoop_interface,
    715     const packet_fragmenter_t* packet_fragmenter_interface) {
    716   buffer_allocator = buffer_allocator_interface;
    717   btsnoop = btsnoop_interface;
    718   packet_fragmenter = packet_fragmenter_interface;
    719 
    720   init_layer_interface();
    721   return &interface;
    722 }
    723