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