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 #include <frameworks/base/core/proto/android/bluetooth/hci/enums.pb.h>
29 
30 #include <signal.h>
31 #include <string.h>
32 #include <sys/types.h>
33 #include <unistd.h>
34 
35 #include <chrono>
36 #include <mutex>
37 
38 #include "btcore/include/module.h"
39 #include "btif/include/btif_bqr.h"
40 #include "btsnoop.h"
41 #include "buffer_allocator.h"
42 #include "common/message_loop_thread.h"
43 #include "common/metrics.h"
44 #include "common/once_timer.h"
45 #include "hci_inject.h"
46 #include "hci_internals.h"
47 #include "hcidefs.h"
48 #include "hcimsgs.h"
49 #include "main/shim/shim.h"
50 #include "osi/include/alarm.h"
51 #include "osi/include/list.h"
52 #include "osi/include/log.h"
53 #include "osi/include/properties.h"
54 #include "osi/include/reactor.h"
55 #include "packet_fragmenter.h"
56 
57 #define BT_HCI_TIMEOUT_TAG_NUM 1010000
58 
59 using bluetooth::common::MessageLoopThread;
60 using bluetooth::common::OnceTimer;
61 
62 extern void hci_initialize();
63 extern void hci_transmit(BT_HDR* packet);
64 extern void hci_close();
65 extern int hci_open_firmware_log_file();
66 extern void hci_close_firmware_log_file(int fd);
67 extern void hci_log_firmware_debug_packet(int fd, BT_HDR* packet);
68 
69 static int hci_firmware_log_fd = INVALID_FD;
70 
71 typedef struct {
72   uint16_t opcode;
73   future_t* complete_future;
74   command_complete_cb complete_callback;
75   command_status_cb status_callback;
76   void* context;
77   BT_HDR* command;
78   std::chrono::time_point<std::chrono::steady_clock> timestamp;
79 } waiting_command_t;
80 
81 // Using a define here, because it can be stringified for the property lookup
82 // Default timeout should be less than BLE_START_TIMEOUT and
83 // having less than 3 sec would hold the wakelock for init
84 #define DEFAULT_STARTUP_TIMEOUT_MS 2900
85 #define STRING_VALUE_OF(x) #x
86 
87 // Abort if there is no response to an HCI command.
88 static const uint32_t COMMAND_PENDING_TIMEOUT_MS = 2000;
89 static const uint32_t COMMAND_PENDING_MUTEX_ACQUIRE_TIMEOUT_MS = 500;
90 static const uint32_t COMMAND_TIMEOUT_RESTART_MS = 5000;
91 static const uint32_t ROOT_INFLAMMED_RESTART_MS = 5000;
92 static const int HCI_UNKNOWN_COMMAND_TIMED_OUT = 0x00ffffff;
93 static const int HCI_STARTUP_TIMED_OUT = 0x00eeeeee;
94 
95 // Our interface
96 static bool interface_created;
97 static hci_t interface;
98 
99 // Modules we import and callbacks we export
100 static const allocator_t* buffer_allocator;
101 static const btsnoop_t* btsnoop;
102 static const packet_fragmenter_t* packet_fragmenter;
103 
104 static future_t* startup_future;
105 static MessageLoopThread hci_thread("bt_hci_thread");
106 
107 static alarm_t* startup_timer;
108 
109 // Outbound-related
110 static int command_credits = 1;
111 static std::mutex command_credits_mutex;
112 static std::queue<base::Closure> command_queue;
113 
114 // Inbound-related
115 static alarm_t* command_response_timer;
116 static list_t* commands_pending_response;
117 static std::recursive_timed_mutex commands_pending_response_mutex;
118 static OnceTimer abort_timer;
119 
120 // Root inflammation error codes
121 static uint8_t root_inflamed_error_code = 0;
122 static uint8_t root_inflamed_vendor_error_code = 0;
123 
124 // The hand-off point for data going to a higher layer, set by the higher layer
125 static base::Callback<void(const base::Location&, BT_HDR*)> send_data_upwards;
126 
127 static bool filter_incoming_event(BT_HDR* packet);
128 static waiting_command_t* get_waiting_command(command_opcode_t opcode);
129 static int get_num_waiting_commands();
130 
131 static void hci_root_inflamed_abort();
132 static void hci_timeout_abort(void);
133 static void event_finish_startup(void* context);
134 static void startup_timer_expired(void* context);
135 
136 static void enqueue_command(waiting_command_t* wait_entry);
137 static void event_command_ready(waiting_command_t* wait_entry);
138 static void enqueue_packet(void* packet);
139 static void event_packet_ready(void* packet);
140 static void command_timed_out(void* context);
141 
142 static void update_command_response_timer(void);
143 
144 static void transmit_fragment(BT_HDR* packet, bool send_transmit_finished);
145 static void dispatch_reassembled(BT_HDR* packet);
146 static void fragmenter_transmit_finished(BT_HDR* packet,
147                                          bool all_fragments_sent);
148 static bool filter_bqr_event(int16_t bqr_parameter_length,
149                              uint8_t* p_bqr_event);
150 
151 static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks = {
152     transmit_fragment, dispatch_reassembled, fragmenter_transmit_finished};
153 
initialization_complete()154 void initialization_complete() {
155   hci_thread.DoInThread(FROM_HERE, base::Bind(&event_finish_startup, nullptr));
156 }
157 
hci_event_received(const base::Location & from_here,BT_HDR * packet)158 void hci_event_received(const base::Location& from_here, BT_HDR* packet) {
159   btsnoop->capture(packet, true);
160 
161   if (!filter_incoming_event(packet)) {
162     send_data_upwards.Run(from_here, packet);
163   }
164 }
165 
acl_event_received(BT_HDR * packet)166 void acl_event_received(BT_HDR* packet) {
167   btsnoop->capture(packet, true);
168   packet_fragmenter->reassemble_and_dispatch(packet);
169 }
170 
sco_data_received(BT_HDR * packet)171 void sco_data_received(BT_HDR* packet) {
172   btsnoop->capture(packet, true);
173   packet_fragmenter->reassemble_and_dispatch(packet);
174 }
175 
iso_data_received(BT_HDR * packet)176 void iso_data_received(BT_HDR* packet) {
177   btsnoop->capture(packet, true);
178   packet_fragmenter->reassemble_and_dispatch(packet);
179 }
180 
hal_service_died()181 void hal_service_died() {
182   if (abort_timer.IsScheduled()) {
183     if (root_inflamed_vendor_error_code != 0 || root_inflamed_error_code != 0) {
184       hci_root_inflamed_abort();
185     } else {
186       hci_timeout_abort();
187     }
188     return;
189   }
190   abort();
191 }
192 
193 // Module lifecycle functions
194 
195 static future_t* hci_module_shut_down();
196 
hci_module_start_up(void)197 static future_t* hci_module_start_up(void) {
198   LOG_INFO("%s", __func__);
199 
200   // The host is only allowed to send at most one command initially,
201   // as per the Bluetooth spec, Volume 2, Part E, 4.4 (Command Flow Control)
202   // This value can change when you get a command complete or command status
203   // event.
204   command_credits = 1;
205 
206   // For now, always use the default timeout on non-Android builds.
207   uint64_t startup_timeout_ms = DEFAULT_STARTUP_TIMEOUT_MS;
208 
209   // Grab the override startup timeout ms, if present.
210   char timeout_prop[PROPERTY_VALUE_MAX];
211   if (!osi_property_get("bluetooth.enable_timeout_ms", timeout_prop,
212                         STRING_VALUE_OF(DEFAULT_STARTUP_TIMEOUT_MS)) ||
213       (startup_timeout_ms = atoi(timeout_prop)) < 100)
214     startup_timeout_ms = DEFAULT_STARTUP_TIMEOUT_MS;
215 
216   startup_timer = alarm_new("hci.startup_timer");
217   if (!startup_timer) {
218     LOG_ERROR("%s unable to create startup timer.", __func__);
219     goto error;
220   }
221 
222   command_response_timer = alarm_new("hci.command_response_timer");
223   if (!command_response_timer) {
224     LOG_ERROR("%s unable to create command response timer.", __func__);
225     goto error;
226   }
227 
228   hci_thread.StartUp();
229   if (!hci_thread.IsRunning()) {
230     LOG_ERROR("%s unable to start thread.", __func__);
231     goto error;
232   }
233   if (!hci_thread.EnableRealTimeScheduling()) {
234     LOG_ERROR("%s unable to make thread RT.", __func__);
235     goto error;
236   }
237 
238   commands_pending_response = list_new(NULL);
239   if (!commands_pending_response) {
240     LOG_ERROR("%s unable to create list for commands pending response.",
241               __func__);
242     goto error;
243   }
244 
245   // Make sure we run in a bounded amount of time
246   future_t* local_startup_future;
247   local_startup_future = future_new();
248   startup_future = local_startup_future;
249   alarm_set(startup_timer, startup_timeout_ms, startup_timer_expired, NULL);
250 
251   packet_fragmenter->init(&packet_fragmenter_callbacks);
252 
253   hci_thread.DoInThread(FROM_HERE, base::Bind(&hci_initialize));
254 
255   LOG_DEBUG("%s starting async portion", __func__);
256   return local_startup_future;
257 
258 error:
259   hci_module_shut_down();  // returns NULL so no need to wait for it
260   return future_new_immediate(FUTURE_FAIL);
261 }
262 
hci_module_shut_down()263 static future_t* hci_module_shut_down() {
264   LOG_INFO("%s", __func__);
265 
266   // Free the timers
267   {
268     std::lock_guard<std::recursive_timed_mutex> lock(
269         commands_pending_response_mutex);
270     alarm_free(command_response_timer);
271     command_response_timer = NULL;
272     alarm_free(startup_timer);
273     startup_timer = NULL;
274   }
275 
276   hci_thread.ShutDown();
277 
278   // Close HCI to prevent callbacks.
279   hci_close();
280 
281   {
282     std::lock_guard<std::recursive_timed_mutex> lock(
283         commands_pending_response_mutex);
284     list_free(commands_pending_response);
285     commands_pending_response = NULL;
286   }
287 
288   packet_fragmenter->cleanup();
289 
290   if (hci_firmware_log_fd != INVALID_FD) {
291     hci_close_firmware_log_file(hci_firmware_log_fd);
292     hci_firmware_log_fd = INVALID_FD;
293   }
294 
295   return NULL;
296 }
297 
298 EXPORT_SYMBOL extern const module_t hci_module = {
299     .name = HCI_MODULE,
300     .init = NULL,
301     .start_up = hci_module_start_up,
302     .shut_down = hci_module_shut_down,
303     .clean_up = NULL,
304     .dependencies = {BTSNOOP_MODULE, NULL}};
305 
306 // Interface functions
307 
set_data_cb(base::Callback<void (const base::Location &,BT_HDR *)> send_data_cb)308 static void set_data_cb(
309     base::Callback<void(const base::Location&, BT_HDR*)> send_data_cb) {
310   send_data_upwards = std::move(send_data_cb);
311 }
312 
transmit_command(BT_HDR * command,command_complete_cb complete_callback,command_status_cb status_callback,void * context)313 static void transmit_command(BT_HDR* command,
314                              command_complete_cb complete_callback,
315                              command_status_cb status_callback, void* context) {
316   waiting_command_t* wait_entry = reinterpret_cast<waiting_command_t*>(
317       osi_calloc(sizeof(waiting_command_t)));
318 
319   uint8_t* stream = command->data + command->offset;
320   STREAM_TO_UINT16(wait_entry->opcode, stream);
321   wait_entry->complete_callback = complete_callback;
322   wait_entry->status_callback = status_callback;
323   wait_entry->command = command;
324   wait_entry->context = context;
325 
326   // Store the command message type in the event field
327   // in case the upper layer didn't already
328   command->event = MSG_STACK_TO_HC_HCI_CMD;
329 
330   enqueue_command(wait_entry);
331 }
332 
transmit_command_futured(BT_HDR * command)333 static future_t* transmit_command_futured(BT_HDR* command) {
334   waiting_command_t* wait_entry = reinterpret_cast<waiting_command_t*>(
335       osi_calloc(sizeof(waiting_command_t)));
336   future_t* future = future_new();
337 
338   uint8_t* stream = command->data + command->offset;
339   STREAM_TO_UINT16(wait_entry->opcode, stream);
340   wait_entry->complete_future = future;
341   wait_entry->command = command;
342 
343   // Store the command message type in the event field
344   // in case the upper layer didn't already
345   command->event = MSG_STACK_TO_HC_HCI_CMD;
346 
347   enqueue_command(wait_entry);
348   return future;
349 }
350 
transmit_downward(uint16_t type,void * data)351 static void transmit_downward(uint16_t type, void* data) {
352   if (type == MSG_STACK_TO_HC_HCI_CMD) {
353     // TODO(zachoverflow): eliminate this call
354     transmit_command((BT_HDR*)data, NULL, NULL, NULL);
355     LOG_WARN("%s legacy transmit of command. Use transmit_command instead.",
356              __func__);
357   } else {
358     enqueue_packet(data);
359   }
360 }
361 
362 // Start up functions
363 
event_finish_startup(UNUSED_ATTR void * context)364 static void event_finish_startup(UNUSED_ATTR void* context) {
365   LOG_INFO("%s", __func__);
366   std::lock_guard<std::recursive_timed_mutex> lock(
367       commands_pending_response_mutex);
368   alarm_cancel(startup_timer);
369   if (!startup_future) {
370     return;
371   }
372   future_ready(startup_future, FUTURE_SUCCESS);
373   startup_future = NULL;
374 }
375 
startup_timer_expired(UNUSED_ATTR void * context)376 static void startup_timer_expired(UNUSED_ATTR void* context) {
377   LOG_ERROR("%s", __func__);
378 
379   LOG_EVENT_INT(BT_HCI_TIMEOUT_TAG_NUM, HCI_STARTUP_TIMED_OUT);
380 
381   hci_close();
382   if (abort_timer.IsScheduled()) {
383     LOG_ERROR("%s: waiting for abort_timer", __func__);
384     return;
385   }
386 
387   abort();
388 }
389 
390 // Command/packet transmitting functions
enqueue_command(waiting_command_t * wait_entry)391 static void enqueue_command(waiting_command_t* wait_entry) {
392   base::Closure callback = base::Bind(&event_command_ready, wait_entry);
393 
394   std::lock_guard<std::mutex> command_credits_lock(command_credits_mutex);
395   if (command_credits > 0) {
396     if (!hci_thread.DoInThread(FROM_HERE, std::move(callback))) {
397       // HCI Layer was shut down or not running
398       buffer_allocator->free(wait_entry->command);
399       osi_free(wait_entry);
400       return;
401     }
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_timed_mutex> lock(
412         commands_pending_response_mutex);
413     wait_entry->timestamp = std::chrono::steady_clock::now();
414     list_append(commands_pending_response, wait_entry);
415   }
416   // Send it off
417   packet_fragmenter->fragment_and_dispatch(wait_entry->command);
418 
419   update_command_response_timer();
420 }
421 
enqueue_packet(void * packet)422 static void enqueue_packet(void* packet) {
423   if (!hci_thread.DoInThread(FROM_HERE,
424                              base::Bind(&event_packet_ready, packet))) {
425     // HCI Layer was shut down or not running
426     buffer_allocator->free(packet);
427     return;
428   }
429 }
430 
event_packet_ready(void * pkt)431 static void event_packet_ready(void* pkt) {
432   // The queue may be the command queue or the packet queue, we don't care
433   BT_HDR* packet = (BT_HDR*)pkt;
434   packet_fragmenter->fragment_and_dispatch(packet);
435 }
436 
437 // Callback for the fragmenter to send a fragment
transmit_fragment(BT_HDR * packet,bool send_transmit_finished)438 static void transmit_fragment(BT_HDR* packet, bool send_transmit_finished) {
439   btsnoop->capture(packet, false);
440 
441   // HCI command packets are freed on a different thread when the matching
442   // event is received. Check packet->event before sending to avoid a race.
443   bool free_after_transmit =
444       (packet->event & MSG_EVT_MASK) != MSG_STACK_TO_HC_HCI_CMD &&
445       send_transmit_finished;
446 
447   hci_transmit(packet);
448 
449   if (free_after_transmit) {
450     buffer_allocator->free(packet);
451   }
452 }
453 
fragmenter_transmit_finished(BT_HDR * packet,bool all_fragments_sent)454 static void fragmenter_transmit_finished(BT_HDR* packet,
455                                          bool all_fragments_sent) {
456   if (all_fragments_sent) {
457     buffer_allocator->free(packet);
458   } else {
459     // This is kind of a weird case, since we're dispatching a partially sent
460     // packet up to a higher layer.
461     // TODO(zachoverflow): rework upper layer so this isn't necessary.
462 
463     send_data_upwards.Run(FROM_HERE, packet);
464   }
465 }
466 
467 // Abort.  The chip has had time to write any debugging information.
hci_timeout_abort(void)468 static void hci_timeout_abort(void) {
469   LOG_ERROR("%s restarting the Bluetooth process.", __func__);
470   hci_close_firmware_log_file(hci_firmware_log_fd);
471 
472   // We shouldn't try to recover the stack from this command timeout.
473   // If it's caused by a software bug, fix it. If it's a hardware bug, fix it.
474   abort();
475 }
476 
hci_root_inflamed_abort()477 static void hci_root_inflamed_abort() {
478   LOG(FATAL) << __func__
479              << ": error_code = " << std::to_string(root_inflamed_error_code)
480              << ", vendor_error_code = "
481              << std::to_string(root_inflamed_vendor_error_code);
482 }
483 
command_timed_out_log_info(void * original_wait_entry)484 static void command_timed_out_log_info(void* original_wait_entry) {
485   LOG_ERROR("%s: %d commands pending response", __func__,
486             get_num_waiting_commands());
487 
488   for (const list_node_t* node = list_begin(commands_pending_response);
489        node != list_end(commands_pending_response); node = list_next(node)) {
490     waiting_command_t* wait_entry =
491         reinterpret_cast<waiting_command_t*>(list_node(node));
492 
493     int wait_time_ms =
494         std::chrono::duration_cast<std::chrono::milliseconds>(
495             std::chrono::steady_clock::now() - wait_entry->timestamp)
496             .count();
497     LOG_ERROR("%s: Waited %d ms for a response to opcode: 0x%x %s", __func__,
498               wait_time_ms, wait_entry->opcode,
499               (wait_entry == original_wait_entry) ? "*matches timer*" : "");
500 
501     // Dump the length field and the first byte of the payload, if present.
502     uint8_t* command = wait_entry->command->data + wait_entry->command->offset;
503     if (wait_entry->command->len > 3) {
504       LOG_ERROR("%s: Size %d Hex %02x %02x %02x %02x", __func__,
505                 wait_entry->command->len, command[0], command[1], command[2],
506                 command[3]);
507     } else {
508       LOG_ERROR("%s: Size %d Hex %02x %02x %02x", __func__,
509                 wait_entry->command->len, command[0], command[1], command[2]);
510     }
511 
512     LOG_EVENT_INT(BT_HCI_TIMEOUT_TAG_NUM, wait_entry->opcode);
513     bluetooth::common::LogHciTimeoutEvent(wait_entry->opcode);
514   }
515 }
516 
517 // Print debugging information and quit. Don't dereference original_wait_entry.
command_timed_out(void * original_wait_entry)518 static void command_timed_out(void* original_wait_entry) {
519   LOG_ERROR("%s", __func__);
520   std::unique_lock<std::recursive_timed_mutex> lock(
521       commands_pending_response_mutex, std::defer_lock);
522   if (!lock.try_lock_for(std::chrono::milliseconds(
523           COMMAND_PENDING_MUTEX_ACQUIRE_TIMEOUT_MS))) {
524     LOG_ERROR("%s: Cannot obtain the mutex", __func__);
525     LOG_EVENT_INT(BT_HCI_TIMEOUT_TAG_NUM, HCI_UNKNOWN_COMMAND_TIMED_OUT);
526     bluetooth::common::LogHciTimeoutEvent(android::bluetooth::hci::CMD_UNKNOWN);
527   } else {
528     command_timed_out_log_info(original_wait_entry);
529     lock.unlock();
530   }
531 
532   // Don't request a firmware dump for multiple hci timeouts
533   if (hci_firmware_log_fd != INVALID_FD) {
534     return;
535   }
536 
537   LOG_ERROR("%s: requesting a firmware dump.", __func__);
538 
539   /* Allocate a buffer to hold the HCI command. */
540   BT_HDR* bt_hdr =
541       static_cast<BT_HDR*>(osi_malloc(sizeof(BT_HDR) + HCIC_PREAMBLE_SIZE));
542 
543   bt_hdr->len = HCIC_PREAMBLE_SIZE;
544   bt_hdr->event = MSG_STACK_TO_HC_HCI_CMD;
545   bt_hdr->offset = 0;
546 
547   uint8_t* hci_packet = reinterpret_cast<uint8_t*>(bt_hdr + 1);
548 
549   UINT16_TO_STREAM(hci_packet, HCI_CONTROLLER_DEBUG_INFO);
550   UINT8_TO_STREAM(hci_packet, 0);  // No parameters
551 
552   hci_firmware_log_fd = hci_open_firmware_log_file();
553 
554   transmit_fragment(bt_hdr, true);
555 
556   osi_free(bt_hdr);
557   LOG_ERROR("%s: Setting a timer to restart.", __func__);
558 
559   // alarm_default_callbacks thread post to hci_thread.
560   if (!abort_timer.Schedule(
561           hci_thread.GetWeakPtr(), FROM_HERE, base::Bind(hci_timeout_abort),
562           base::TimeDelta::FromMilliseconds(COMMAND_TIMEOUT_RESTART_MS))) {
563     LOG_ERROR("%s unable to create an abort timer.", __func__);
564     abort();
565   }
566 }
567 
568 // Event/packet receiving functions
process_command_credits(int credits)569 void process_command_credits(int credits) {
570   std::lock_guard<std::mutex> command_credits_lock(command_credits_mutex);
571 
572   if (!hci_thread.IsRunning()) {
573     // HCI Layer was shut down or not running
574     return;
575   }
576 
577   // Subtract commands in flight.
578   command_credits = credits - get_num_waiting_commands();
579 
580   while (command_credits > 0 && !command_queue.empty()) {
581     if (!hci_thread.DoInThread(FROM_HERE, std::move(command_queue.front()))) {
582       LOG(ERROR) << __func__ << ": failed to enqueue command";
583     }
584     command_queue.pop();
585     command_credits--;
586   }
587 }
588 
hci_is_root_inflammation_event_received()589 bool hci_is_root_inflammation_event_received() {
590   return abort_timer.IsScheduled();
591 }
592 
handle_root_inflammation_event()593 void handle_root_inflammation_event() {
594   LOG(ERROR) << __func__
595              << ": Root inflammation event! setting timer to restart.";
596   // TODO(ugoyu) Report to bluetooth metrics here
597   {
598     // Try to stop hci command and startup timers
599     std::unique_lock<std::recursive_timed_mutex> lock(
600         commands_pending_response_mutex, std::defer_lock);
601     if (lock.try_lock_for(std::chrono::milliseconds(
602             COMMAND_PENDING_MUTEX_ACQUIRE_TIMEOUT_MS))) {
603       if (alarm_is_scheduled(startup_timer)) {
604         alarm_cancel(startup_timer);
605       }
606       if (alarm_is_scheduled(command_response_timer)) {
607         alarm_cancel(command_response_timer);
608       }
609       // Cleanup the hci/startup timers so they will not be scheduled again and
610       // expire before the abort_timer.
611       alarm_free(command_response_timer);
612       command_response_timer = NULL;
613       alarm_free(startup_timer);
614       startup_timer = NULL;
615     } else {
616       LOG(ERROR) << __func__ << ": Failed to obtain mutex";
617       hci_root_inflamed_abort();
618     }
619   }
620 
621   // HwBinder thread post to hci_thread
622   if (!hci_thread.IsRunning() ||
623       !abort_timer.Schedule(
624           hci_thread.GetWeakPtr(), FROM_HERE,
625           base::Bind(hci_root_inflamed_abort),
626           base::TimeDelta::FromMilliseconds(ROOT_INFLAMMED_RESTART_MS))) {
627     LOG(ERROR) << "Failed to schedule abort_timer or hci has already closed!";
628     hci_root_inflamed_abort();
629   }
630 }
631 
632 // Returns true if the event was intercepted and should not proceed to
633 // higher layers. Also inspects an incoming event for interesting
634 // information, like how many commands are now able to be sent.
filter_incoming_event(BT_HDR * packet)635 static bool filter_incoming_event(BT_HDR* packet) {
636   waiting_command_t* wait_entry = NULL;
637   uint8_t* stream = packet->data;
638   uint8_t event_code;
639   int credits = 0;
640   command_opcode_t opcode;
641 
642   STREAM_TO_UINT8(event_code, stream);
643   STREAM_SKIP_UINT8(stream);  // Skip the parameter total length field
644 
645   if (event_code == HCI_COMMAND_COMPLETE_EVT) {
646     STREAM_TO_UINT8(credits, stream);
647     STREAM_TO_UINT16(opcode, stream);
648 
649     wait_entry = get_waiting_command(opcode);
650 
651     process_command_credits(credits);
652 
653     if (!wait_entry) {
654       if (opcode != HCI_COMMAND_NONE) {
655         LOG_WARN(
656             "%s command complete event with no matching command (opcode: "
657             "0x%04x).",
658             __func__, opcode);
659       }
660     } else {
661       update_command_response_timer();
662       if (wait_entry->complete_callback) {
663         wait_entry->complete_callback(packet, wait_entry->context);
664       } else if (wait_entry->complete_future) {
665         future_ready(wait_entry->complete_future, packet);
666       }
667     }
668 
669     goto intercepted;
670   } else if (event_code == HCI_COMMAND_STATUS_EVT) {
671     uint8_t status;
672     STREAM_TO_UINT8(status, stream);
673     STREAM_TO_UINT8(credits, stream);
674     STREAM_TO_UINT16(opcode, stream);
675 
676     // If a command generates a command status event, it won't be getting a
677     // command complete event
678     wait_entry = get_waiting_command(opcode);
679 
680     process_command_credits(credits);
681 
682     if (!wait_entry) {
683       LOG_WARN(
684           "%s command status event with no matching command. opcode: 0x%04x",
685           __func__, opcode);
686     } else {
687       update_command_response_timer();
688       if (wait_entry->status_callback)
689         wait_entry->status_callback(status, wait_entry->command,
690                                     wait_entry->context);
691     }
692 
693     goto intercepted;
694   } else if (event_code == HCI_VENDOR_SPECIFIC_EVT) {
695     uint8_t sub_event_code;
696     STREAM_TO_UINT8(sub_event_code, stream);
697 
698     if (sub_event_code == HCI_VSE_SUBCODE_DEBUG_INFO_SUB_EVT) {
699       if (hci_firmware_log_fd == INVALID_FD)
700         hci_firmware_log_fd = hci_open_firmware_log_file();
701 
702       if (hci_firmware_log_fd != INVALID_FD)
703         hci_log_firmware_debug_packet(hci_firmware_log_fd, packet);
704 
705       buffer_allocator->free(packet);
706       return true;
707     } else if (sub_event_code == HCI_VSE_SUBCODE_BQR_SUB_EVT) {
708       // Excluding the HCI Event packet header and 1 octet sub-event code
709       int16_t bqr_parameter_length = packet->len - HCIE_PREAMBLE_SIZE - 1;
710       // The stream currently points to the BQR sub-event parameters
711       if (filter_bqr_event(bqr_parameter_length, stream)) {
712         buffer_allocator->free(packet);
713         return true;
714       }
715     }
716   }
717 
718   return false;
719 
720 intercepted:
721   if (wait_entry) {
722     // If it has a callback, it's responsible for freeing the packet
723     if (event_code == HCI_COMMAND_STATUS_EVT ||
724         (!wait_entry->complete_callback && !wait_entry->complete_future))
725       buffer_allocator->free(packet);
726 
727     // If it has a callback, it's responsible for freeing the command
728     if (event_code == HCI_COMMAND_COMPLETE_EVT || !wait_entry->status_callback)
729       buffer_allocator->free(wait_entry->command);
730 
731     osi_free(wait_entry);
732   } else {
733     buffer_allocator->free(packet);
734   }
735 
736   return true;
737 }
738 
739 // Callback for the fragmenter to dispatch up a completely reassembled packet
dispatch_reassembled(BT_HDR * packet)740 static void dispatch_reassembled(BT_HDR* packet) {
741   // Events should already have been dispatched before this point
742   CHECK((packet->event & MSG_EVT_MASK) != MSG_HC_TO_STACK_HCI_EVT);
743   CHECK(!send_data_upwards.is_null());
744 
745   send_data_upwards.Run(FROM_HERE, packet);
746 }
747 
748 // Misc internal functions
749 
get_waiting_command(command_opcode_t opcode)750 static waiting_command_t* get_waiting_command(command_opcode_t opcode) {
751   std::lock_guard<std::recursive_timed_mutex> lock(
752       commands_pending_response_mutex);
753 
754   for (const list_node_t* node = list_begin(commands_pending_response);
755        node != list_end(commands_pending_response); node = list_next(node)) {
756     waiting_command_t* wait_entry =
757         reinterpret_cast<waiting_command_t*>(list_node(node));
758 
759     if (!wait_entry || wait_entry->opcode != opcode) continue;
760 
761     list_remove(commands_pending_response, wait_entry);
762 
763     return wait_entry;
764   }
765 
766   return NULL;
767 }
768 
get_num_waiting_commands()769 static int get_num_waiting_commands() {
770   std::lock_guard<std::recursive_timed_mutex> lock(
771       commands_pending_response_mutex);
772   return list_length(commands_pending_response);
773 }
774 
update_command_response_timer(void)775 static void update_command_response_timer(void) {
776   std::lock_guard<std::recursive_timed_mutex> lock(
777       commands_pending_response_mutex);
778 
779   if (command_response_timer == NULL) return;
780   if (list_is_empty(commands_pending_response)) {
781     alarm_cancel(command_response_timer);
782   } else {
783     alarm_set(command_response_timer, COMMAND_PENDING_TIMEOUT_MS,
784               command_timed_out, list_front(commands_pending_response));
785   }
786 }
787 
788 // Returns true if the BQR event is handled and should not proceed to
789 // higher layers.
filter_bqr_event(int16_t bqr_parameter_length,uint8_t * p_bqr_event)790 static bool filter_bqr_event(int16_t bqr_parameter_length,
791                              uint8_t* p_bqr_event) {
792   if (bqr_parameter_length <= 0) {
793     LOG(ERROR) << __func__ << ": Invalid parameter length : "
794                << std::to_string(bqr_parameter_length);
795     return true;
796   }
797 
798   bool intercepted = false;
799   uint8_t quality_report_id = p_bqr_event[0];
800   switch (quality_report_id) {
801     case bluetooth::bqr::QUALITY_REPORT_ID_ROOT_INFLAMMATION:
802       if (bqr_parameter_length >=
803           bluetooth::bqr::kRootInflammationParamTotalLen) {
804         STREAM_TO_UINT8(quality_report_id, p_bqr_event);
805         STREAM_TO_UINT8(root_inflamed_error_code, p_bqr_event);
806         STREAM_TO_UINT8(root_inflamed_vendor_error_code, p_bqr_event);
807         handle_root_inflammation_event();
808       }
809       intercepted = true;
810       break;
811 
812     case bluetooth::bqr::QUALITY_REPORT_ID_LMP_LL_MESSAGE_TRACE:
813       if (bqr_parameter_length >= bluetooth::bqr::kLogDumpParamTotalLen) {
814         bluetooth::bqr::DumpLmpLlMessage(bqr_parameter_length, p_bqr_event);
815       }
816       intercepted = true;
817       break;
818 
819     case bluetooth::bqr::QUALITY_REPORT_ID_BT_SCHEDULING_TRACE:
820       if (bqr_parameter_length >= bluetooth::bqr::kLogDumpParamTotalLen) {
821         bluetooth::bqr::DumpBtScheduling(bqr_parameter_length, p_bqr_event);
822       }
823       intercepted = true;
824       break;
825 
826     case bluetooth::bqr::QUALITY_REPORT_ID_CONTROLLER_DBG_INFO:
827       // TODO: Integrate with the HCI_VSE_SUBCODE_DEBUG_INFO_SUB_EVT
828       intercepted = true;
829       break;
830 
831     case bluetooth::bqr::QUALITY_REPORT_ID_MONITOR_MODE:
832     case bluetooth::bqr::QUALITY_REPORT_ID_APPROACH_LSTO:
833     case bluetooth::bqr::QUALITY_REPORT_ID_A2DP_AUDIO_CHOPPY:
834     case bluetooth::bqr::QUALITY_REPORT_ID_SCO_VOICE_CHOPPY:
835     default:
836       break;
837   }
838 
839   return intercepted;
840 }
841 
init_layer_interface()842 static void init_layer_interface() {
843   if (!interface_created) {
844     // It's probably ok for this to live forever. It's small and
845     // there's only one instance of the hci interface.
846 
847     interface.set_data_cb = set_data_cb;
848     interface.transmit_command = transmit_command;
849     interface.transmit_command_futured = transmit_command_futured;
850     interface.transmit_downward = transmit_downward;
851     interface_created = true;
852   }
853 }
854 
hci_layer_cleanup_interface()855 void hci_layer_cleanup_interface() {
856   if (interface_created) {
857     send_data_upwards.Reset();
858 
859     interface.set_data_cb = NULL;
860     interface.transmit_command = NULL;
861     interface.transmit_command_futured = NULL;
862     interface.transmit_downward = NULL;
863     interface_created = false;
864   }
865 }
866 
867 namespace bluetooth {
868 namespace shim {
869 const hci_t* hci_layer_get_interface();
870 }  // namespace shim
871 }  // namespace bluetooth
872 
hci_layer_get_interface()873 const hci_t* hci_layer_get_interface() {
874   if (bluetooth::shim::is_gd_shim_enabled()) {
875     return bluetooth::shim::hci_layer_get_interface();
876   } else {
877     return bluetooth::legacy::hci_layer_get_interface();
878   }
879 }
880 
hci_layer_get_interface()881 const hci_t* bluetooth::legacy::hci_layer_get_interface() {
882   buffer_allocator = buffer_allocator_get_interface();
883   btsnoop = btsnoop_get_interface();
884   packet_fragmenter = packet_fragmenter_get_interface();
885 
886   init_layer_interface();
887 
888   return &interface;
889 }
890 
hci_layer_get_test_interface(const allocator_t * buffer_allocator_interface,const btsnoop_t * btsnoop_interface,const packet_fragmenter_t * packet_fragmenter_interface)891 const hci_t* hci_layer_get_test_interface(
892     const allocator_t* buffer_allocator_interface,
893     const btsnoop_t* btsnoop_interface,
894     const packet_fragmenter_t* packet_fragmenter_interface) {
895   buffer_allocator = buffer_allocator_interface;
896   btsnoop = btsnoop_interface;
897   packet_fragmenter = packet_fragmenter_interface;
898 
899   init_layer_interface();
900   return &interface;
901 }
902