• 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 #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(LOG_TAG, "%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(LOG_TAG, "%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(LOG_TAG, "%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(LOG_TAG, "%s unable to start thread.", __func__);
231     goto error;
232   }
233   if (!hci_thread.EnableRealTimeScheduling()) {
234     LOG_ERROR(LOG_TAG, "%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(LOG_TAG,
241               "%s unable to create list for commands pending response.",
242               __func__);
243     goto error;
244   }
245 
246   // Make sure we run in a bounded amount of time
247   future_t* local_startup_future;
248   local_startup_future = future_new();
249   startup_future = local_startup_future;
250   alarm_set(startup_timer, startup_timeout_ms, startup_timer_expired, NULL);
251 
252   packet_fragmenter->init(&packet_fragmenter_callbacks);
253 
254   hci_thread.DoInThread(FROM_HERE, base::Bind(&hci_initialize));
255 
256   LOG_DEBUG(LOG_TAG, "%s starting async portion", __func__);
257   return local_startup_future;
258 
259 error:
260   hci_module_shut_down();  // returns NULL so no need to wait for it
261   return future_new_immediate(FUTURE_FAIL);
262 }
263 
hci_module_shut_down()264 static future_t* hci_module_shut_down() {
265   LOG_INFO(LOG_TAG, "%s", __func__);
266 
267   // Free the timers
268   {
269     std::lock_guard<std::recursive_timed_mutex> lock(
270         commands_pending_response_mutex);
271     alarm_free(command_response_timer);
272     command_response_timer = NULL;
273     alarm_free(startup_timer);
274     startup_timer = NULL;
275   }
276 
277   hci_thread.ShutDown();
278 
279   // Close HCI to prevent callbacks.
280   hci_close();
281 
282   {
283     std::lock_guard<std::recursive_timed_mutex> lock(
284         commands_pending_response_mutex);
285     list_free(commands_pending_response);
286     commands_pending_response = NULL;
287   }
288 
289   packet_fragmenter->cleanup();
290 
291   if (hci_firmware_log_fd != INVALID_FD) {
292     hci_close_firmware_log_file(hci_firmware_log_fd);
293     hci_firmware_log_fd = INVALID_FD;
294   }
295 
296   return NULL;
297 }
298 
299 EXPORT_SYMBOL extern const module_t hci_module = {
300     .name = HCI_MODULE,
301     .init = NULL,
302     .start_up = hci_module_start_up,
303     .shut_down = hci_module_shut_down,
304     .clean_up = NULL,
305     .dependencies = {BTSNOOP_MODULE, NULL}};
306 
307 // Interface functions
308 
set_data_cb(base::Callback<void (const base::Location &,BT_HDR *)> send_data_cb)309 static void set_data_cb(
310     base::Callback<void(const base::Location&, BT_HDR*)> send_data_cb) {
311   send_data_upwards = std::move(send_data_cb);
312 }
313 
transmit_command(BT_HDR * command,command_complete_cb complete_callback,command_status_cb status_callback,void * context)314 static void transmit_command(BT_HDR* command,
315                              command_complete_cb complete_callback,
316                              command_status_cb status_callback, void* context) {
317   waiting_command_t* wait_entry = reinterpret_cast<waiting_command_t*>(
318       osi_calloc(sizeof(waiting_command_t)));
319 
320   uint8_t* stream = command->data + command->offset;
321   STREAM_TO_UINT16(wait_entry->opcode, stream);
322   wait_entry->complete_callback = complete_callback;
323   wait_entry->status_callback = status_callback;
324   wait_entry->command = command;
325   wait_entry->context = context;
326 
327   // Store the command message type in the event field
328   // in case the upper layer didn't already
329   command->event = MSG_STACK_TO_HC_HCI_CMD;
330 
331   enqueue_command(wait_entry);
332 }
333 
transmit_command_futured(BT_HDR * command)334 static future_t* transmit_command_futured(BT_HDR* command) {
335   waiting_command_t* wait_entry = reinterpret_cast<waiting_command_t*>(
336       osi_calloc(sizeof(waiting_command_t)));
337   future_t* future = future_new();
338 
339   uint8_t* stream = command->data + command->offset;
340   STREAM_TO_UINT16(wait_entry->opcode, stream);
341   wait_entry->complete_future = future;
342   wait_entry->command = command;
343 
344   // Store the command message type in the event field
345   // in case the upper layer didn't already
346   command->event = MSG_STACK_TO_HC_HCI_CMD;
347 
348   enqueue_command(wait_entry);
349   return future;
350 }
351 
transmit_downward(uint16_t type,void * data)352 static void transmit_downward(uint16_t type, void* data) {
353   if (type == MSG_STACK_TO_HC_HCI_CMD) {
354     // TODO(zachoverflow): eliminate this call
355     transmit_command((BT_HDR*)data, NULL, NULL, NULL);
356     LOG_WARN(LOG_TAG,
357              "%s legacy transmit of command. Use transmit_command instead.",
358              __func__);
359   } else {
360     enqueue_packet(data);
361   }
362 }
363 
364 // Start up functions
365 
event_finish_startup(UNUSED_ATTR void * context)366 static void event_finish_startup(UNUSED_ATTR void* context) {
367   LOG_INFO(LOG_TAG, "%s", __func__);
368   std::lock_guard<std::recursive_timed_mutex> lock(
369       commands_pending_response_mutex);
370   alarm_cancel(startup_timer);
371   if (!startup_future) {
372     return;
373   }
374   future_ready(startup_future, FUTURE_SUCCESS);
375   startup_future = NULL;
376 }
377 
startup_timer_expired(UNUSED_ATTR void * context)378 static void startup_timer_expired(UNUSED_ATTR void* context) {
379   LOG_ERROR(LOG_TAG, "%s", __func__);
380 
381   LOG_EVENT_INT(BT_HCI_TIMEOUT_TAG_NUM, HCI_STARTUP_TIMED_OUT);
382 
383   hci_close();
384   if (abort_timer.IsScheduled()) {
385     LOG_ERROR(LOG_TAG, "%s: waiting for abort_timer", __func__);
386     return;
387   }
388 
389   abort();
390 }
391 
392 // Command/packet transmitting functions
enqueue_command(waiting_command_t * wait_entry)393 static void enqueue_command(waiting_command_t* wait_entry) {
394   base::Closure callback = base::Bind(&event_command_ready, wait_entry);
395 
396   std::lock_guard<std::mutex> command_credits_lock(command_credits_mutex);
397   if (command_credits > 0) {
398     if (!hci_thread.DoInThread(FROM_HERE, std::move(callback))) {
399       // HCI Layer was shut down or not running
400       buffer_allocator->free(wait_entry->command);
401       osi_free(wait_entry);
402       return;
403     }
404     command_credits--;
405   } else {
406     command_queue.push(std::move(callback));
407   }
408 }
409 
event_command_ready(waiting_command_t * wait_entry)410 static void event_command_ready(waiting_command_t* wait_entry) {
411   {
412     /// Move it to the list of commands awaiting response
413     std::lock_guard<std::recursive_timed_mutex> lock(
414         commands_pending_response_mutex);
415     wait_entry->timestamp = std::chrono::steady_clock::now();
416     list_append(commands_pending_response, wait_entry);
417   }
418   // Send it off
419   packet_fragmenter->fragment_and_dispatch(wait_entry->command);
420 
421   update_command_response_timer();
422 }
423 
enqueue_packet(void * packet)424 static void enqueue_packet(void* packet) {
425   if (!hci_thread.DoInThread(FROM_HERE,
426                              base::Bind(&event_packet_ready, packet))) {
427     // HCI Layer was shut down or not running
428     buffer_allocator->free(packet);
429     return;
430   }
431 }
432 
event_packet_ready(void * pkt)433 static void event_packet_ready(void* pkt) {
434   // The queue may be the command queue or the packet queue, we don't care
435   BT_HDR* packet = (BT_HDR*)pkt;
436   packet_fragmenter->fragment_and_dispatch(packet);
437 }
438 
439 // Callback for the fragmenter to send a fragment
transmit_fragment(BT_HDR * packet,bool send_transmit_finished)440 static void transmit_fragment(BT_HDR* packet, bool send_transmit_finished) {
441   btsnoop->capture(packet, false);
442 
443   // HCI command packets are freed on a different thread when the matching
444   // event is received. Check packet->event before sending to avoid a race.
445   bool free_after_transmit =
446       (packet->event & MSG_EVT_MASK) != MSG_STACK_TO_HC_HCI_CMD &&
447       send_transmit_finished;
448 
449   hci_transmit(packet);
450 
451   if (free_after_transmit) {
452     buffer_allocator->free(packet);
453   }
454 }
455 
fragmenter_transmit_finished(BT_HDR * packet,bool all_fragments_sent)456 static void fragmenter_transmit_finished(BT_HDR* packet,
457                                          bool all_fragments_sent) {
458   if (all_fragments_sent) {
459     buffer_allocator->free(packet);
460   } else {
461     // This is kind of a weird case, since we're dispatching a partially sent
462     // packet up to a higher layer.
463     // TODO(zachoverflow): rework upper layer so this isn't necessary.
464 
465     send_data_upwards.Run(FROM_HERE, packet);
466   }
467 }
468 
469 // Abort.  The chip has had time to write any debugging information.
hci_timeout_abort(void)470 static void hci_timeout_abort(void) {
471   LOG_ERROR(LOG_TAG, "%s restarting the Bluetooth process.", __func__);
472   hci_close_firmware_log_file(hci_firmware_log_fd);
473 
474   // We shouldn't try to recover the stack from this command timeout.
475   // If it's caused by a software bug, fix it. If it's a hardware bug, fix it.
476   abort();
477 }
478 
hci_root_inflamed_abort()479 static void hci_root_inflamed_abort() {
480   LOG(FATAL) << __func__
481              << ": error_code = " << std::to_string(root_inflamed_error_code)
482              << ", vendor_error_code = "
483              << std::to_string(root_inflamed_vendor_error_code);
484 }
485 
command_timed_out_log_info(void * original_wait_entry)486 static void command_timed_out_log_info(void* original_wait_entry) {
487   LOG_ERROR(LOG_TAG, "%s: %d commands pending response", __func__,
488             get_num_waiting_commands());
489 
490   for (const list_node_t* node = list_begin(commands_pending_response);
491        node != list_end(commands_pending_response); node = list_next(node)) {
492     waiting_command_t* wait_entry =
493         reinterpret_cast<waiting_command_t*>(list_node(node));
494 
495     int wait_time_ms =
496         std::chrono::duration_cast<std::chrono::milliseconds>(
497             std::chrono::steady_clock::now() - wait_entry->timestamp)
498             .count();
499     LOG_ERROR(LOG_TAG, "%s: Waited %d ms for a response to opcode: 0x%x %s",
500               __func__, wait_time_ms, wait_entry->opcode,
501               (wait_entry == original_wait_entry) ? "*matches timer*" : "");
502 
503     // Dump the length field and the first byte of the payload, if present.
504     uint8_t* command = wait_entry->command->data + wait_entry->command->offset;
505     if (wait_entry->command->len > 3) {
506       LOG_ERROR(LOG_TAG, "%s: Size %d Hex %02x %02x %02x %02x", __func__,
507                 wait_entry->command->len, command[0], command[1], command[2],
508                 command[3]);
509     } else {
510       LOG_ERROR(LOG_TAG, "%s: Size %d Hex %02x %02x %02x", __func__,
511                 wait_entry->command->len, command[0], command[1], command[2]);
512     }
513 
514     LOG_EVENT_INT(BT_HCI_TIMEOUT_TAG_NUM, wait_entry->opcode);
515     bluetooth::common::LogHciTimeoutEvent(wait_entry->opcode);
516   }
517 }
518 
519 // Print debugging information and quit. Don't dereference original_wait_entry.
command_timed_out(void * original_wait_entry)520 static void command_timed_out(void* original_wait_entry) {
521   LOG_ERROR(LOG_TAG, "%s", __func__);
522   std::unique_lock<std::recursive_timed_mutex> lock(
523       commands_pending_response_mutex, std::defer_lock);
524   if (!lock.try_lock_for(std::chrono::milliseconds(
525           COMMAND_PENDING_MUTEX_ACQUIRE_TIMEOUT_MS))) {
526     LOG_ERROR(LOG_TAG, "%s: Cannot obtain the mutex", __func__);
527     LOG_EVENT_INT(BT_HCI_TIMEOUT_TAG_NUM, HCI_UNKNOWN_COMMAND_TIMED_OUT);
528     bluetooth::common::LogHciTimeoutEvent(android::bluetooth::hci::CMD_UNKNOWN);
529   } else {
530     command_timed_out_log_info(original_wait_entry);
531     lock.unlock();
532   }
533 
534   // Don't request a firmware dump for multiple hci timeouts
535   if (hci_firmware_log_fd != INVALID_FD) {
536     return;
537   }
538 
539   LOG_ERROR(LOG_TAG, "%s: requesting a firmware dump.", __func__);
540 
541   /* Allocate a buffer to hold the HCI command. */
542   BT_HDR* bt_hdr =
543       static_cast<BT_HDR*>(osi_malloc(sizeof(BT_HDR) + HCIC_PREAMBLE_SIZE));
544 
545   bt_hdr->len = HCIC_PREAMBLE_SIZE;
546   bt_hdr->event = MSG_STACK_TO_HC_HCI_CMD;
547   bt_hdr->offset = 0;
548 
549   uint8_t* hci_packet = reinterpret_cast<uint8_t*>(bt_hdr + 1);
550 
551   UINT16_TO_STREAM(hci_packet, HCI_CONTROLLER_DEBUG_INFO);
552   UINT8_TO_STREAM(hci_packet, 0);  // No parameters
553 
554   hci_firmware_log_fd = hci_open_firmware_log_file();
555 
556   transmit_fragment(bt_hdr, true);
557 
558   osi_free(bt_hdr);
559   LOG_ERROR(LOG_TAG, "%s: Setting a timer to restart.", __func__);
560 
561   // alarm_default_callbacks thread post to hci_thread.
562   if (!abort_timer.Schedule(
563           hci_thread.GetWeakPtr(), FROM_HERE, base::Bind(hci_timeout_abort),
564           base::TimeDelta::FromMilliseconds(COMMAND_TIMEOUT_RESTART_MS))) {
565     LOG_ERROR(LOG_TAG, "%s unable to create an abort timer.", __func__);
566     abort();
567   }
568 }
569 
570 // Event/packet receiving functions
process_command_credits(int credits)571 void process_command_credits(int credits) {
572   std::lock_guard<std::mutex> command_credits_lock(command_credits_mutex);
573 
574   if (!hci_thread.IsRunning()) {
575     // HCI Layer was shut down or not running
576     return;
577   }
578 
579   // Subtract commands in flight.
580   command_credits = credits - get_num_waiting_commands();
581 
582   while (command_credits > 0 && !command_queue.empty()) {
583     if (!hci_thread.DoInThread(FROM_HERE, std::move(command_queue.front()))) {
584       LOG(ERROR) << __func__ << ": failed to enqueue command";
585     }
586     command_queue.pop();
587     command_credits--;
588   }
589 }
590 
hci_is_root_inflammation_event_received()591 bool hci_is_root_inflammation_event_received() {
592   return abort_timer.IsScheduled();
593 }
594 
handle_root_inflammation_event()595 void handle_root_inflammation_event() {
596   LOG(ERROR) << __func__
597              << ": Root inflammation event! setting timer to restart.";
598   // TODO(ugoyu) Report to bluetooth metrics here
599   {
600     // Try to stop hci command and startup timers
601     std::unique_lock<std::recursive_timed_mutex> lock(
602         commands_pending_response_mutex, std::defer_lock);
603     if (lock.try_lock_for(std::chrono::milliseconds(
604             COMMAND_PENDING_MUTEX_ACQUIRE_TIMEOUT_MS))) {
605       if (alarm_is_scheduled(startup_timer)) {
606         alarm_cancel(startup_timer);
607       }
608       if (alarm_is_scheduled(command_response_timer)) {
609         alarm_cancel(command_response_timer);
610       }
611       // Cleanup the hci/startup timers so they will not be scheduled again and
612       // expire before the abort_timer.
613       alarm_free(command_response_timer);
614       command_response_timer = NULL;
615       alarm_free(startup_timer);
616       startup_timer = NULL;
617     } else {
618       LOG(ERROR) << __func__ << ": Failed to obtain mutex";
619       hci_root_inflamed_abort();
620     }
621   }
622 
623   // HwBinder thread post to hci_thread
624   if (!hci_thread.IsRunning() ||
625       !abort_timer.Schedule(
626           hci_thread.GetWeakPtr(), FROM_HERE,
627           base::Bind(hci_root_inflamed_abort),
628           base::TimeDelta::FromMilliseconds(ROOT_INFLAMMED_RESTART_MS))) {
629     LOG(ERROR) << "Failed to schedule abort_timer or hci has already closed!";
630     hci_root_inflamed_abort();
631   }
632 }
633 
634 // Returns true if the event was intercepted and should not proceed to
635 // higher layers. Also inspects an incoming event for interesting
636 // information, like how many commands are now able to be sent.
filter_incoming_event(BT_HDR * packet)637 static bool filter_incoming_event(BT_HDR* packet) {
638   waiting_command_t* wait_entry = NULL;
639   uint8_t* stream = packet->data;
640   uint8_t event_code;
641   uint8_t length;
642   int credits = 0;
643   command_opcode_t opcode;
644 
645   STREAM_TO_UINT8(event_code, stream);
646   STREAM_TO_UINT8(length, stream);
647 
648   if (event_code == HCI_COMMAND_COMPLETE_EVT) {
649     STREAM_TO_UINT8(credits, stream);
650     STREAM_TO_UINT16(opcode, stream);
651 
652     wait_entry = get_waiting_command(opcode);
653 
654     process_command_credits(credits);
655 
656     if (!wait_entry) {
657       if (opcode != HCI_COMMAND_NONE) {
658         LOG_WARN(LOG_TAG,
659                  "%s command complete event with no matching command (opcode: "
660                  "0x%04x).",
661                  __func__, opcode);
662       }
663     } else {
664       update_command_response_timer();
665       if (wait_entry->complete_callback) {
666         wait_entry->complete_callback(packet, wait_entry->context);
667       } else if (wait_entry->complete_future) {
668         future_ready(wait_entry->complete_future, packet);
669       }
670     }
671 
672     goto intercepted;
673   } else if (event_code == HCI_COMMAND_STATUS_EVT) {
674     if (length < (sizeof(uint8_t) + sizeof(uint8_t) + sizeof(uint16_t))) {
675       goto intercepted;
676     }
677     uint8_t status;
678     STREAM_TO_UINT8(status, stream);
679     STREAM_TO_UINT8(credits, stream);
680     STREAM_TO_UINT16(opcode, stream);
681 
682     // If a command generates a command status event, it won't be getting a
683     // command complete event
684     wait_entry = get_waiting_command(opcode);
685 
686     process_command_credits(credits);
687 
688     if (!wait_entry) {
689       LOG_WARN(
690           LOG_TAG,
691           "%s command status event with no matching command. opcode: 0x%04x",
692           __func__, opcode);
693     } else {
694       update_command_response_timer();
695       if (wait_entry->status_callback)
696         wait_entry->status_callback(status, wait_entry->command,
697                                     wait_entry->context);
698     }
699 
700     goto intercepted;
701   } else if (event_code == HCI_VENDOR_SPECIFIC_EVT) {
702     uint8_t sub_event_code;
703     STREAM_TO_UINT8(sub_event_code, stream);
704 
705     if (sub_event_code == HCI_VSE_SUBCODE_DEBUG_INFO_SUB_EVT) {
706       if (hci_firmware_log_fd == INVALID_FD)
707         hci_firmware_log_fd = hci_open_firmware_log_file();
708 
709       if (hci_firmware_log_fd != INVALID_FD)
710         hci_log_firmware_debug_packet(hci_firmware_log_fd, packet);
711 
712       buffer_allocator->free(packet);
713       return true;
714     } else if (sub_event_code == HCI_VSE_SUBCODE_BQR_SUB_EVT) {
715       // Excluding the HCI Event packet header and 1 octet sub-event code
716       int16_t bqr_parameter_length = packet->len - HCIE_PREAMBLE_SIZE - 1;
717       // The stream currently points to the BQR sub-event parameters
718       if (filter_bqr_event(bqr_parameter_length, stream)) {
719         buffer_allocator->free(packet);
720         return true;
721       }
722     }
723   }
724 
725   return false;
726 
727 intercepted:
728   if (wait_entry) {
729     // If it has a callback, it's responsible for freeing the packet
730     if (event_code == HCI_COMMAND_STATUS_EVT ||
731         (!wait_entry->complete_callback && !wait_entry->complete_future))
732       buffer_allocator->free(packet);
733 
734     // If it has a callback, it's responsible for freeing the command
735     if (event_code == HCI_COMMAND_COMPLETE_EVT || !wait_entry->status_callback)
736       buffer_allocator->free(wait_entry->command);
737 
738     osi_free(wait_entry);
739   } else {
740     buffer_allocator->free(packet);
741   }
742 
743   return true;
744 }
745 
746 // Callback for the fragmenter to dispatch up a completely reassembled packet
dispatch_reassembled(BT_HDR * packet)747 static void dispatch_reassembled(BT_HDR* packet) {
748   // Events should already have been dispatched before this point
749   CHECK((packet->event & MSG_EVT_MASK) != MSG_HC_TO_STACK_HCI_EVT);
750   CHECK(!send_data_upwards.is_null());
751 
752   send_data_upwards.Run(FROM_HERE, packet);
753 }
754 
755 // Misc internal functions
756 
get_waiting_command(command_opcode_t opcode)757 static waiting_command_t* get_waiting_command(command_opcode_t opcode) {
758   std::lock_guard<std::recursive_timed_mutex> lock(
759       commands_pending_response_mutex);
760 
761   for (const list_node_t* node = list_begin(commands_pending_response);
762        node != list_end(commands_pending_response); node = list_next(node)) {
763     waiting_command_t* wait_entry =
764         reinterpret_cast<waiting_command_t*>(list_node(node));
765 
766     if (!wait_entry || wait_entry->opcode != opcode) continue;
767 
768     list_remove(commands_pending_response, wait_entry);
769 
770     return wait_entry;
771   }
772 
773   return NULL;
774 }
775 
get_num_waiting_commands()776 static int get_num_waiting_commands() {
777   std::lock_guard<std::recursive_timed_mutex> lock(
778       commands_pending_response_mutex);
779   return list_length(commands_pending_response);
780 }
781 
update_command_response_timer(void)782 static void update_command_response_timer(void) {
783   std::lock_guard<std::recursive_timed_mutex> lock(
784       commands_pending_response_mutex);
785 
786   if (command_response_timer == NULL) return;
787   if (list_is_empty(commands_pending_response)) {
788     alarm_cancel(command_response_timer);
789   } else {
790     alarm_set(command_response_timer, COMMAND_PENDING_TIMEOUT_MS,
791               command_timed_out, list_front(commands_pending_response));
792   }
793 }
794 
795 // Returns true if the BQR event is handled and should not proceed to
796 // higher layers.
filter_bqr_event(int16_t bqr_parameter_length,uint8_t * p_bqr_event)797 static bool filter_bqr_event(int16_t bqr_parameter_length,
798                              uint8_t* p_bqr_event) {
799   if (bqr_parameter_length <= 0) {
800     LOG(ERROR) << __func__ << ": Invalid parameter length : "
801                << std::to_string(bqr_parameter_length);
802     return true;
803   }
804 
805   bool intercepted = false;
806   uint8_t quality_report_id = p_bqr_event[0];
807   switch (quality_report_id) {
808     case bluetooth::bqr::QUALITY_REPORT_ID_ROOT_INFLAMMATION:
809       if (bqr_parameter_length >=
810           bluetooth::bqr::kRootInflammationParamTotalLen) {
811         STREAM_TO_UINT8(quality_report_id, p_bqr_event);
812         STREAM_TO_UINT8(root_inflamed_error_code, p_bqr_event);
813         STREAM_TO_UINT8(root_inflamed_vendor_error_code, p_bqr_event);
814         handle_root_inflammation_event();
815       }
816       intercepted = true;
817       break;
818 
819     case bluetooth::bqr::QUALITY_REPORT_ID_LMP_LL_MESSAGE_TRACE:
820       if (bqr_parameter_length >= bluetooth::bqr::kLogDumpParamTotalLen) {
821         bluetooth::bqr::DumpLmpLlMessage(bqr_parameter_length, p_bqr_event);
822       }
823       intercepted = true;
824       break;
825 
826     case bluetooth::bqr::QUALITY_REPORT_ID_BT_SCHEDULING_TRACE:
827       if (bqr_parameter_length >= bluetooth::bqr::kLogDumpParamTotalLen) {
828         bluetooth::bqr::DumpBtScheduling(bqr_parameter_length, p_bqr_event);
829       }
830       intercepted = true;
831       break;
832 
833     case bluetooth::bqr::QUALITY_REPORT_ID_CONTROLLER_DBG_INFO:
834       // TODO: Integrate with the HCI_VSE_SUBCODE_DEBUG_INFO_SUB_EVT
835       intercepted = true;
836       break;
837 
838     case bluetooth::bqr::QUALITY_REPORT_ID_MONITOR_MODE:
839     case bluetooth::bqr::QUALITY_REPORT_ID_APPROACH_LSTO:
840     case bluetooth::bqr::QUALITY_REPORT_ID_A2DP_AUDIO_CHOPPY:
841     case bluetooth::bqr::QUALITY_REPORT_ID_SCO_VOICE_CHOPPY:
842     default:
843       break;
844   }
845 
846   return intercepted;
847 }
848 
init_layer_interface()849 static void init_layer_interface() {
850   if (!interface_created) {
851     // It's probably ok for this to live forever. It's small and
852     // there's only one instance of the hci interface.
853 
854     interface.set_data_cb = set_data_cb;
855     interface.transmit_command = transmit_command;
856     interface.transmit_command_futured = transmit_command_futured;
857     interface.transmit_downward = transmit_downward;
858     interface_created = true;
859   }
860 }
861 
hci_layer_cleanup_interface()862 void hci_layer_cleanup_interface() {
863   if (interface_created) {
864     send_data_upwards.Reset();
865 
866     interface.set_data_cb = NULL;
867     interface.transmit_command = NULL;
868     interface.transmit_command_futured = NULL;
869     interface.transmit_downward = NULL;
870     interface_created = false;
871   }
872 }
873 
874 namespace bluetooth {
875 namespace shim {
876 const hci_t* hci_layer_get_interface();
877 }  // namespace shim
878 }  // namespace bluetooth
879 
hci_layer_get_interface()880 const hci_t* hci_layer_get_interface() {
881   if (bluetooth::shim::is_gd_shim_enabled()) {
882     return bluetooth::shim::hci_layer_get_interface();
883   } else {
884     return bluetooth::legacy::hci_layer_get_interface();
885   }
886 }
887 
hci_layer_get_interface()888 const hci_t* bluetooth::legacy::hci_layer_get_interface() {
889   buffer_allocator = buffer_allocator_get_interface();
890   btsnoop = btsnoop_get_interface();
891   packet_fragmenter = packet_fragmenter_get_interface();
892 
893   init_layer_interface();
894 
895   return &interface;
896 }
897 
hci_layer_get_test_interface(const allocator_t * buffer_allocator_interface,const btsnoop_t * btsnoop_interface,const packet_fragmenter_t * packet_fragmenter_interface)898 const hci_t* hci_layer_get_test_interface(
899     const allocator_t* buffer_allocator_interface,
900     const btsnoop_t* btsnoop_interface,
901     const packet_fragmenter_t* packet_fragmenter_interface) {
902   buffer_allocator = buffer_allocator_interface;
903   btsnoop = btsnoop_interface;
904   packet_fragmenter = packet_fragmenter_interface;
905 
906   init_layer_interface();
907   return &interface;
908 }
909