1 /******************************************************************************
2 *
3 * Copyright (C) 2014 Google, Inc.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at:
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 ******************************************************************************/
18
19 #define LOG_TAG "bt_hci"
20
21 #include <assert.h>
22 #include <cutils/properties.h>
23 #include <string.h>
24 #include <signal.h>
25 #include <string.h>
26 #include <sys/types.h>
27
28 #include "buffer_allocator.h"
29 #include "btsnoop.h"
30 #include "osi/include/fixed_queue.h"
31 #include "osi/include/future.h"
32 #include "hcidefs.h"
33 #include "hcimsgs.h"
34 #include "hci_hal.h"
35 #include "hci_internals.h"
36 #include "hci_inject.h"
37 #include "hci_layer.h"
38 #include "osi/include/list.h"
39 #include "low_power_manager.h"
40 #include "btcore/include/module.h"
41 #include "osi/include/non_repeating_timer.h"
42 #include "osi/include/osi.h"
43 #include "osi/include/log.h"
44 #include "packet_fragmenter.h"
45 #include "osi/include/reactor.h"
46 #include "vendor.h"
47
48 // TODO(zachoverflow): remove this hack extern
49 #include <hardware/bluetooth.h>
50 bt_bdaddr_t btif_local_bd_addr;
51
52 #define INBOUND_PACKET_TYPE_COUNT 3
53 #define PACKET_TYPE_TO_INBOUND_INDEX(type) ((type) - 2)
54 #define PACKET_TYPE_TO_INDEX(type) ((type) - 1)
55
56 #define PREAMBLE_BUFFER_SIZE 4 // max preamble size, ACL
57 #define RETRIEVE_ACL_LENGTH(preamble) ((((preamble)[3]) << 8) | (preamble)[2])
58
59 static const uint8_t preamble_sizes[] = {
60 HCI_COMMAND_PREAMBLE_SIZE,
61 HCI_ACL_PREAMBLE_SIZE,
62 HCI_SCO_PREAMBLE_SIZE,
63 HCI_EVENT_PREAMBLE_SIZE
64 };
65
66 static const uint16_t outbound_event_types[] =
67 {
68 MSG_HC_TO_STACK_HCI_ERR,
69 MSG_HC_TO_STACK_HCI_ACL,
70 MSG_HC_TO_STACK_HCI_SCO,
71 MSG_HC_TO_STACK_HCI_EVT
72 };
73
74 typedef enum {
75 BRAND_NEW,
76 PREAMBLE,
77 BODY,
78 IGNORE,
79 FINISHED
80 } receive_state_t;
81
82 typedef struct {
83 receive_state_t state;
84 uint16_t bytes_remaining;
85 uint8_t preamble[PREAMBLE_BUFFER_SIZE];
86 uint16_t index;
87 BT_HDR *buffer;
88 } packet_receive_data_t;
89
90 typedef struct {
91 uint16_t opcode;
92 future_t *complete_future;
93 command_complete_cb complete_callback;
94 command_status_cb status_callback;
95 void *context;
96 BT_HDR *command;
97 } waiting_command_t;
98
99 // Using a define here, because it can be stringified for the property lookup
100 #define DEFAULT_STARTUP_TIMEOUT_MS 8000
101 #define STRING_VALUE_OF(x) #x
102
103 static const uint32_t EPILOG_TIMEOUT_MS = 3000;
104 static const uint32_t COMMAND_PENDING_TIMEOUT = 8000;
105
106 // Our interface
107 static bool interface_created;
108 static hci_t interface;
109
110 // Modules we import and callbacks we export
111 static const allocator_t *buffer_allocator;
112 static const btsnoop_t *btsnoop;
113 static const hci_hal_t *hal;
114 static const hci_hal_callbacks_t hal_callbacks;
115 static const hci_inject_t *hci_inject;
116 static const low_power_manager_t *low_power_manager;
117 static const packet_fragmenter_t *packet_fragmenter;
118 static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks;
119 static const vendor_t *vendor;
120
121 static future_t *startup_future;
122 static thread_t *thread; // We own this
123
124 static volatile bool firmware_is_configured = false;
125 static non_repeating_timer_t *epilog_timer;
126 static non_repeating_timer_t *startup_timer;
127
128 // Outbound-related
129 static int command_credits = 1;
130 static fixed_queue_t *command_queue;
131 static fixed_queue_t *packet_queue;
132
133 // Inbound-related
134 static non_repeating_timer_t *command_response_timer;
135 static list_t *commands_pending_response;
136 static pthread_mutex_t commands_pending_response_lock;
137 static packet_receive_data_t incoming_packets[INBOUND_PACKET_TYPE_COUNT];
138
139 // The hand-off point for data going to a higher layer, set by the higher layer
140 static fixed_queue_t *upwards_data_queue;
141
142 static future_t *shut_down();
143
144 static void event_finish_startup(void *context);
145 static void firmware_config_callback(bool success);
146 static void startup_timer_expired(void *context);
147
148 static void event_postload(void *context);
149 static void sco_config_callback(bool success);
150
151 static void event_epilog(void *context);
152 static void epilog_finished_callback(bool success);
153 static void epilog_timer_expired(void *context);
154
155 static void event_command_ready(fixed_queue_t *queue, void *context);
156 static void event_packet_ready(fixed_queue_t *queue, void *context);
157 static void command_timed_out(void *context);
158
159 static void hal_says_data_ready(serial_data_type_t type);
160 static bool filter_incoming_event(BT_HDR *packet);
161
162 static serial_data_type_t event_to_data_type(uint16_t event);
163 static waiting_command_t *get_waiting_command(command_opcode_t opcode);
164
165 // Module lifecycle functions
166
start_up(void)167 static future_t *start_up(void) {
168 LOG_INFO("%s", __func__);
169
170 // The host is only allowed to send at most one command initially,
171 // as per the Bluetooth spec, Volume 2, Part E, 4.4 (Command Flow Control)
172 // This value can change when you get a command complete or command status event.
173 command_credits = 1;
174 firmware_is_configured = false;
175
176 pthread_mutex_init(&commands_pending_response_lock, NULL);
177
178 // Grab the override startup timeout ms, if present.
179 period_ms_t startup_timeout_ms;
180 char timeout_prop[PROPERTY_VALUE_MAX];
181 if (!property_get("bluetooth.enable_timeout_ms", timeout_prop, STRING_VALUE_OF(DEFAULT_STARTUP_TIMEOUT_MS))
182 || (startup_timeout_ms = atoi(timeout_prop)) < 100)
183 startup_timeout_ms = DEFAULT_STARTUP_TIMEOUT_MS;
184
185 startup_timer = non_repeating_timer_new(startup_timeout_ms, startup_timer_expired, NULL);
186 if (!startup_timer) {
187 LOG_ERROR("%s unable to create startup timer.", __func__);
188 goto error;
189 }
190
191 // Make sure we run in a bounded amount of time
192 non_repeating_timer_restart(startup_timer);
193
194 epilog_timer = non_repeating_timer_new(EPILOG_TIMEOUT_MS, epilog_timer_expired, NULL);
195 if (!epilog_timer) {
196 LOG_ERROR("%s unable to create epilog timer.", __func__);
197 goto error;
198 }
199
200 command_response_timer = non_repeating_timer_new(COMMAND_PENDING_TIMEOUT, command_timed_out, NULL);
201 if (!command_response_timer) {
202 LOG_ERROR("%s unable to create command response timer.", __func__);
203 goto error;
204 }
205
206 command_queue = fixed_queue_new(SIZE_MAX);
207 if (!command_queue) {
208 LOG_ERROR("%s unable to create pending command queue.", __func__);
209 goto error;
210 }
211
212 packet_queue = fixed_queue_new(SIZE_MAX);
213 if (!packet_queue) {
214 LOG_ERROR("%s unable to create pending packet queue.", __func__);
215 goto error;
216 }
217
218 thread = thread_new("hci_thread");
219 if (!thread) {
220 LOG_ERROR("%s unable to create thread.", __func__);
221 goto error;
222 }
223
224 commands_pending_response = list_new(NULL);
225 if (!commands_pending_response) {
226 LOG_ERROR("%s unable to create list for commands pending response.", __func__);
227 goto error;
228 }
229
230 memset(incoming_packets, 0, sizeof(incoming_packets));
231
232 packet_fragmenter->init(&packet_fragmenter_callbacks);
233
234 fixed_queue_register_dequeue(command_queue, thread_get_reactor(thread), event_command_ready, NULL);
235 fixed_queue_register_dequeue(packet_queue, thread_get_reactor(thread), event_packet_ready, NULL);
236
237 vendor->open(btif_local_bd_addr.address, &interface);
238 hal->init(&hal_callbacks, thread);
239 low_power_manager->init(thread);
240
241 vendor->set_callback(VENDOR_CONFIGURE_FIRMWARE, firmware_config_callback);
242 vendor->set_callback(VENDOR_CONFIGURE_SCO, sco_config_callback);
243 vendor->set_callback(VENDOR_DO_EPILOG, epilog_finished_callback);
244
245 if (!hci_inject->open(&interface)) {
246 // TODO(sharvil): gracefully propagate failures from this layer.
247 }
248
249 int power_state = BT_VND_PWR_OFF;
250 #if (defined (BT_CLEAN_TURN_ON_DISABLED) && BT_CLEAN_TURN_ON_DISABLED == TRUE)
251 LOG_WARN("%s not turning off the chip before turning on.", __func__);
252 // So apparently this hack was needed in the past because a Wingray kernel driver
253 // didn't handle power off commands in a powered off state correctly.
254
255 // The comment in the old code said the workaround should be removed when the
256 // problem was fixed. Sadly, I have no idea if said bug was fixed or if said
257 // kernel is still in use, so we must leave this here for posterity. #sadpanda
258 #else
259 // cycle power on the chip to ensure it has been reset
260 vendor->send_command(VENDOR_CHIP_POWER_CONTROL, &power_state);
261 #endif
262 power_state = BT_VND_PWR_ON;
263 vendor->send_command(VENDOR_CHIP_POWER_CONTROL, &power_state);
264
265 startup_future = future_new();
266 LOG_DEBUG("%s starting async portion", __func__);
267 thread_post(thread, event_finish_startup, NULL);
268 return startup_future;
269 error:;
270 shut_down(); // returns NULL so no need to wait for it
271 return future_new_immediate(FUTURE_FAIL);
272 }
273
shut_down()274 static future_t *shut_down() {
275 LOG_INFO("%s", __func__);
276
277 hci_inject->close();
278
279 if (thread) {
280 if (firmware_is_configured) {
281 non_repeating_timer_restart(epilog_timer);
282 thread_post(thread, event_epilog, NULL);
283 } else {
284 thread_stop(thread);
285 }
286
287 thread_join(thread);
288 }
289
290 fixed_queue_free(command_queue, osi_free);
291 fixed_queue_free(packet_queue, buffer_allocator->free);
292 list_free(commands_pending_response);
293
294 pthread_mutex_destroy(&commands_pending_response_lock);
295
296 packet_fragmenter->cleanup();
297
298 non_repeating_timer_free(epilog_timer);
299 non_repeating_timer_free(command_response_timer);
300 non_repeating_timer_free(startup_timer);
301
302 epilog_timer = NULL;
303 command_response_timer = NULL;
304
305 low_power_manager->cleanup();
306 hal->close();
307
308 // Turn off the chip
309 int power_state = BT_VND_PWR_OFF;
310 vendor->send_command(VENDOR_CHIP_POWER_CONTROL, &power_state);
311 vendor->close();
312
313 thread_free(thread);
314 thread = NULL;
315 firmware_is_configured = false;
316
317 return NULL;
318 }
319
320 const module_t hci_module = {
321 .name = HCI_MODULE,
322 .init = NULL,
323 .start_up = start_up,
324 .shut_down = shut_down,
325 .clean_up = NULL,
326 .dependencies = {
327 BTSNOOP_MODULE,
328 NULL
329 }
330 };
331
332 // Interface functions
333
do_postload()334 static void do_postload() {
335 LOG_DEBUG("%s posting postload work item", __func__);
336 thread_post(thread, event_postload, NULL);
337 }
338
set_data_queue(fixed_queue_t * queue)339 static void set_data_queue(fixed_queue_t *queue) {
340 upwards_data_queue = queue;
341 }
342
transmit_command(BT_HDR * command,command_complete_cb complete_callback,command_status_cb status_callback,void * context)343 static void transmit_command(
344 BT_HDR *command,
345 command_complete_cb complete_callback,
346 command_status_cb status_callback,
347 void *context) {
348 waiting_command_t *wait_entry = osi_calloc(sizeof(waiting_command_t));
349 if (!wait_entry) {
350 LOG_ERROR("%s couldn't allocate space for wait entry.", __func__);
351 return;
352 }
353
354 uint8_t *stream = command->data + command->offset;
355 STREAM_TO_UINT16(wait_entry->opcode, stream);
356 wait_entry->complete_callback = complete_callback;
357 wait_entry->status_callback = status_callback;
358 wait_entry->command = command;
359 wait_entry->context = context;
360
361 // Store the command message type in the event field
362 // in case the upper layer didn't already
363 command->event = MSG_STACK_TO_HC_HCI_CMD;
364
365 fixed_queue_enqueue(command_queue, wait_entry);
366 }
367
transmit_command_futured(BT_HDR * command)368 static future_t *transmit_command_futured(BT_HDR *command) {
369 waiting_command_t *wait_entry = osi_calloc(sizeof(waiting_command_t));
370 assert(wait_entry != NULL);
371
372 future_t *future = future_new();
373
374 uint8_t *stream = command->data + command->offset;
375 STREAM_TO_UINT16(wait_entry->opcode, stream);
376 wait_entry->complete_future = future;
377 wait_entry->command = command;
378
379 // Store the command message type in the event field
380 // in case the upper layer didn't already
381 command->event = MSG_STACK_TO_HC_HCI_CMD;
382
383 fixed_queue_enqueue(command_queue, wait_entry);
384 return future;
385 }
386
transmit_downward(data_dispatcher_type_t type,void * data)387 static void transmit_downward(data_dispatcher_type_t type, void *data) {
388 if (type == MSG_STACK_TO_HC_HCI_CMD) {
389 // TODO(zachoverflow): eliminate this call
390 transmit_command((BT_HDR *)data, NULL, NULL, NULL);
391 LOG_WARN("%s legacy transmit of command. Use transmit_command instead.", __func__);
392 } else {
393 fixed_queue_enqueue(packet_queue, data);
394 }
395 }
396
397 // Start up functions
398
event_finish_startup(UNUSED_ATTR void * context)399 static void event_finish_startup(UNUSED_ATTR void *context) {
400 LOG_INFO("%s", __func__);
401 hal->open();
402 vendor->send_async_command(VENDOR_CONFIGURE_FIRMWARE, NULL);
403 }
404
firmware_config_callback(UNUSED_ATTR bool success)405 static void firmware_config_callback(UNUSED_ATTR bool success) {
406 LOG_INFO("%s", __func__);
407 firmware_is_configured = true;
408 non_repeating_timer_cancel(startup_timer);
409
410 future_ready(startup_future, FUTURE_SUCCESS);
411 startup_future = NULL;
412 }
413
startup_timer_expired(UNUSED_ATTR void * context)414 static void startup_timer_expired(UNUSED_ATTR void *context) {
415 LOG_ERROR("%s", __func__);
416 future_ready(startup_future, FUTURE_FAIL);
417 startup_future = NULL;
418 }
419
420 // Postload functions
421
event_postload(UNUSED_ATTR void * context)422 static void event_postload(UNUSED_ATTR void *context) {
423 LOG_INFO("%s", __func__);
424 if(vendor->send_async_command(VENDOR_CONFIGURE_SCO, NULL) == -1) {
425 // If couldn't configure sco, we won't get the sco configuration callback
426 // so go pretend to do it now
427 sco_config_callback(false);
428
429 }
430 }
431
sco_config_callback(UNUSED_ATTR bool success)432 static void sco_config_callback(UNUSED_ATTR bool success) {
433 LOG_INFO("%s postload finished.", __func__);
434 }
435
436 // Epilog functions
437
event_epilog(UNUSED_ATTR void * context)438 static void event_epilog(UNUSED_ATTR void *context) {
439 vendor->send_async_command(VENDOR_DO_EPILOG, NULL);
440 }
441
epilog_finished_callback(UNUSED_ATTR bool success)442 static void epilog_finished_callback(UNUSED_ATTR bool success) {
443 LOG_INFO("%s", __func__);
444 thread_stop(thread);
445 }
446
epilog_timer_expired(UNUSED_ATTR void * context)447 static void epilog_timer_expired(UNUSED_ATTR void *context) {
448 LOG_INFO("%s", __func__);
449 thread_stop(thread);
450 }
451
452 // Command/packet transmitting functions
453
event_command_ready(fixed_queue_t * queue,UNUSED_ATTR void * context)454 static void event_command_ready(fixed_queue_t *queue, UNUSED_ATTR void *context) {
455 if (command_credits > 0) {
456 waiting_command_t *wait_entry = fixed_queue_dequeue(queue);
457 command_credits--;
458
459 // Move it to the list of commands awaiting response
460 pthread_mutex_lock(&commands_pending_response_lock);
461 list_append(commands_pending_response, wait_entry);
462 pthread_mutex_unlock(&commands_pending_response_lock);
463
464 // Send it off
465 low_power_manager->wake_assert();
466 packet_fragmenter->fragment_and_dispatch(wait_entry->command);
467 low_power_manager->transmit_done();
468
469 non_repeating_timer_restart_if(command_response_timer, !list_is_empty(commands_pending_response));
470 }
471 }
472
event_packet_ready(fixed_queue_t * queue,UNUSED_ATTR void * context)473 static void event_packet_ready(fixed_queue_t *queue, UNUSED_ATTR void *context) {
474 // The queue may be the command queue or the packet queue, we don't care
475 BT_HDR *packet = (BT_HDR *)fixed_queue_dequeue(queue);
476
477 low_power_manager->wake_assert();
478 packet_fragmenter->fragment_and_dispatch(packet);
479 low_power_manager->transmit_done();
480 }
481
482 // Callback for the fragmenter to send a fragment
transmit_fragment(BT_HDR * packet,bool send_transmit_finished)483 static void transmit_fragment(BT_HDR *packet, bool send_transmit_finished) {
484 uint16_t event = packet->event & MSG_EVT_MASK;
485 serial_data_type_t type = event_to_data_type(event);
486
487 btsnoop->capture(packet, false);
488 hal->transmit_data(type, packet->data + packet->offset, packet->len);
489
490 if (event != MSG_STACK_TO_HC_HCI_CMD && send_transmit_finished)
491 buffer_allocator->free(packet);
492 }
493
fragmenter_transmit_finished(BT_HDR * packet,bool all_fragments_sent)494 static void fragmenter_transmit_finished(BT_HDR *packet, bool all_fragments_sent) {
495 if (all_fragments_sent) {
496 buffer_allocator->free(packet);
497 } else {
498 // This is kind of a weird case, since we're dispatching a partially sent packet
499 // up to a higher layer.
500 // TODO(zachoverflow): rework upper layer so this isn't necessary.
501 data_dispatcher_dispatch(interface.event_dispatcher, packet->event & MSG_EVT_MASK, packet);
502 }
503 }
504
command_timed_out(UNUSED_ATTR void * context)505 static void command_timed_out(UNUSED_ATTR void *context) {
506 pthread_mutex_lock(&commands_pending_response_lock);
507
508 if (list_is_empty(commands_pending_response)) {
509 LOG_ERROR("%s with no commands pending response", __func__);
510 } else {
511 waiting_command_t *wait_entry = list_front(commands_pending_response);
512 pthread_mutex_unlock(&commands_pending_response_lock);
513
514 // We shouldn't try to recover the stack from this command timeout.
515 // If it's caused by a software bug, fix it. If it's a hardware bug, fix it.
516 LOG_ERROR("%s hci layer timeout waiting for response to a command. opcode: 0x%x", __func__, wait_entry->opcode);
517 }
518
519 LOG_ERROR("%s restarting the bluetooth process.", __func__);
520 usleep(10000);
521 kill(getpid(), SIGKILL);
522 }
523
524 // Event/packet receiving functions
525
526 // This function is not required to read all of a packet in one go, so
527 // be wary of reentry. But this function must return after finishing a packet.
hal_says_data_ready(serial_data_type_t type)528 static void hal_says_data_ready(serial_data_type_t type) {
529 packet_receive_data_t *incoming = &incoming_packets[PACKET_TYPE_TO_INBOUND_INDEX(type)];
530
531 uint8_t byte;
532 while (hal->read_data(type, &byte, 1, false) != 0) {
533 switch (incoming->state) {
534 case BRAND_NEW:
535 // Initialize and prepare to jump to the preamble reading state
536 incoming->bytes_remaining = preamble_sizes[PACKET_TYPE_TO_INDEX(type)];
537 memset(incoming->preamble, 0, PREAMBLE_BUFFER_SIZE);
538 incoming->index = 0;
539 incoming->state = PREAMBLE;
540 // INTENTIONAL FALLTHROUGH
541 case PREAMBLE:
542 incoming->preamble[incoming->index] = byte;
543 incoming->index++;
544 incoming->bytes_remaining--;
545
546 if (incoming->bytes_remaining == 0) {
547 // For event and sco preambles, the last byte we read is the length
548 incoming->bytes_remaining = (type == DATA_TYPE_ACL) ? RETRIEVE_ACL_LENGTH(incoming->preamble) : byte;
549
550 size_t buffer_size = BT_HDR_SIZE + incoming->index + incoming->bytes_remaining;
551 incoming->buffer = (BT_HDR *)buffer_allocator->alloc(buffer_size);
552
553 if (!incoming->buffer) {
554 LOG_ERROR("%s error getting buffer for incoming packet of type %d and size %zd", __func__, type, buffer_size);
555 // Can't read any more of this current packet, so jump out
556 incoming->state = incoming->bytes_remaining == 0 ? BRAND_NEW : IGNORE;
557 break;
558 }
559
560 // Initialize the buffer
561 incoming->buffer->offset = 0;
562 incoming->buffer->layer_specific = 0;
563 incoming->buffer->event = outbound_event_types[PACKET_TYPE_TO_INDEX(type)];
564 memcpy(incoming->buffer->data, incoming->preamble, incoming->index);
565
566 incoming->state = incoming->bytes_remaining > 0 ? BODY : FINISHED;
567 }
568
569 break;
570 case BODY:
571 incoming->buffer->data[incoming->index] = byte;
572 incoming->index++;
573 incoming->bytes_remaining--;
574
575 size_t bytes_read = hal->read_data(type, (incoming->buffer->data + incoming->index), incoming->bytes_remaining, false);
576 incoming->index += bytes_read;
577 incoming->bytes_remaining -= bytes_read;
578
579 incoming->state = incoming->bytes_remaining == 0 ? FINISHED : incoming->state;
580 break;
581 case IGNORE:
582 incoming->bytes_remaining--;
583 if (incoming->bytes_remaining == 0) {
584 incoming->state = BRAND_NEW;
585 // Don't forget to let the hal know we finished the packet we were ignoring.
586 // Otherwise we'll get out of sync with hals that embed extra information
587 // in the uart stream (like H4). #badnewsbears
588 hal->packet_finished(type);
589 return;
590 }
591
592 break;
593 case FINISHED:
594 LOG_ERROR("%s the state machine should not have been left in the finished state.", __func__);
595 break;
596 }
597
598 if (incoming->state == FINISHED) {
599 incoming->buffer->len = incoming->index;
600 btsnoop->capture(incoming->buffer, true);
601
602 if (type != DATA_TYPE_EVENT) {
603 packet_fragmenter->reassemble_and_dispatch(incoming->buffer);
604 } else if (!filter_incoming_event(incoming->buffer)) {
605 // Dispatch the event by event code
606 uint8_t *stream = incoming->buffer->data;
607 uint8_t event_code;
608 STREAM_TO_UINT8(event_code, stream);
609
610 data_dispatcher_dispatch(
611 interface.event_dispatcher,
612 event_code,
613 incoming->buffer
614 );
615 }
616
617 // We don't control the buffer anymore
618 incoming->buffer = NULL;
619 incoming->state = BRAND_NEW;
620 hal->packet_finished(type);
621
622 // We return after a packet is finished for two reasons:
623 // 1. The type of the next packet could be different.
624 // 2. We don't want to hog cpu time.
625 return;
626 }
627 }
628 }
629
630 // Returns true if the event was intercepted and should not proceed to
631 // higher layers. Also inspects an incoming event for interesting
632 // information, like how many commands are now able to be sent.
filter_incoming_event(BT_HDR * packet)633 static bool filter_incoming_event(BT_HDR *packet) {
634 waiting_command_t *wait_entry = NULL;
635 uint8_t *stream = packet->data;
636 uint8_t event_code;
637 command_opcode_t opcode;
638
639 STREAM_TO_UINT8(event_code, stream);
640 STREAM_SKIP_UINT8(stream); // Skip the parameter total length field
641
642 if (event_code == HCI_COMMAND_COMPLETE_EVT) {
643 STREAM_TO_UINT8(command_credits, stream);
644 STREAM_TO_UINT16(opcode, stream);
645
646 wait_entry = get_waiting_command(opcode);
647 if (!wait_entry)
648 LOG_WARN("%s command complete event with no matching command. opcode: 0x%x.", __func__, opcode);
649 else if (wait_entry->complete_callback)
650 wait_entry->complete_callback(packet, wait_entry->context);
651 else if (wait_entry->complete_future)
652 future_ready(wait_entry->complete_future, packet);
653
654 goto intercepted;
655 } else if (event_code == HCI_COMMAND_STATUS_EVT) {
656 uint8_t status;
657 STREAM_TO_UINT8(status, stream);
658 STREAM_TO_UINT8(command_credits, stream);
659 STREAM_TO_UINT16(opcode, stream);
660
661 // If a command generates a command status event, it won't be getting a command complete event
662
663 wait_entry = get_waiting_command(opcode);
664 if (!wait_entry)
665 LOG_WARN("%s command status event with no matching command. opcode: 0x%x", __func__, opcode);
666 else if (wait_entry->status_callback)
667 wait_entry->status_callback(status, wait_entry->command, wait_entry->context);
668
669 goto intercepted;
670 }
671
672 return false;
673 intercepted:;
674 non_repeating_timer_restart_if(command_response_timer, !list_is_empty(commands_pending_response));
675
676 if (wait_entry) {
677 // If it has a callback, it's responsible for freeing the packet
678 if (event_code == HCI_COMMAND_STATUS_EVT || (!wait_entry->complete_callback && !wait_entry->complete_future))
679 buffer_allocator->free(packet);
680
681 // If it has a callback, it's responsible for freeing the command
682 if (event_code == HCI_COMMAND_COMPLETE_EVT || !wait_entry->status_callback)
683 buffer_allocator->free(wait_entry->command);
684
685 osi_free(wait_entry);
686 } else {
687 buffer_allocator->free(packet);
688 }
689
690 return true;
691 }
692
693 // Callback for the fragmenter to dispatch up a completely reassembled packet
dispatch_reassembled(BT_HDR * packet)694 static void dispatch_reassembled(BT_HDR *packet) {
695 // Events should already have been dispatched before this point
696 assert((packet->event & MSG_EVT_MASK) != MSG_HC_TO_STACK_HCI_EVT);
697 assert(upwards_data_queue != NULL);
698
699 if (upwards_data_queue) {
700 fixed_queue_enqueue(upwards_data_queue, packet);
701 } else {
702 LOG_ERROR("%s had no queue to place upwards data packet in. Dropping it on the floor.", __func__);
703 buffer_allocator->free(packet);
704 }
705 }
706
707 // Misc internal functions
708
709 // TODO(zachoverflow): we seem to do this a couple places, like the HCI inject module. #centralize
event_to_data_type(uint16_t event)710 static serial_data_type_t event_to_data_type(uint16_t event) {
711 if (event == MSG_STACK_TO_HC_HCI_ACL)
712 return DATA_TYPE_ACL;
713 else if (event == MSG_STACK_TO_HC_HCI_SCO)
714 return DATA_TYPE_SCO;
715 else if (event == MSG_STACK_TO_HC_HCI_CMD)
716 return DATA_TYPE_COMMAND;
717 else
718 LOG_ERROR("%s invalid event type, could not translate 0x%x", __func__, event);
719
720 return 0;
721 }
722
get_waiting_command(command_opcode_t opcode)723 static waiting_command_t *get_waiting_command(command_opcode_t opcode) {
724 pthread_mutex_lock(&commands_pending_response_lock);
725
726 for (const list_node_t *node = list_begin(commands_pending_response);
727 node != list_end(commands_pending_response);
728 node = list_next(node)) {
729 waiting_command_t *wait_entry = list_node(node);
730
731 if (!wait_entry || wait_entry->opcode != opcode)
732 continue;
733
734 list_remove(commands_pending_response, wait_entry);
735
736 pthread_mutex_unlock(&commands_pending_response_lock);
737 return wait_entry;
738 }
739
740 pthread_mutex_unlock(&commands_pending_response_lock);
741 return NULL;
742 }
743
init_layer_interface()744 static void init_layer_interface() {
745 if (!interface_created) {
746 interface.send_low_power_command = low_power_manager->post_command;
747 interface.do_postload = do_postload;
748
749 // It's probably ok for this to live forever. It's small and
750 // there's only one instance of the hci interface.
751 interface.event_dispatcher = data_dispatcher_new("hci_layer");
752 if (!interface.event_dispatcher) {
753 LOG_ERROR("%s could not create upward dispatcher.", __func__);
754 return;
755 }
756
757 interface.set_data_queue = set_data_queue;
758 interface.transmit_command = transmit_command;
759 interface.transmit_command_futured = transmit_command_futured;
760 interface.transmit_downward = transmit_downward;
761 interface_created = true;
762 }
763 }
764
765 static const hci_hal_callbacks_t hal_callbacks = {
766 hal_says_data_ready
767 };
768
769 static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks = {
770 transmit_fragment,
771 dispatch_reassembled,
772 fragmenter_transmit_finished
773 };
774
hci_layer_get_interface()775 const hci_t *hci_layer_get_interface() {
776 buffer_allocator = buffer_allocator_get_interface();
777 hal = hci_hal_get_interface();
778 btsnoop = btsnoop_get_interface();
779 hci_inject = hci_inject_get_interface();
780 packet_fragmenter = packet_fragmenter_get_interface();
781 vendor = vendor_get_interface();
782 low_power_manager = low_power_manager_get_interface();
783
784 init_layer_interface();
785 return &interface;
786 }
787
hci_layer_get_test_interface(const allocator_t * buffer_allocator_interface,const hci_hal_t * hal_interface,const btsnoop_t * btsnoop_interface,const hci_inject_t * hci_inject_interface,const packet_fragmenter_t * packet_fragmenter_interface,const vendor_t * vendor_interface,const low_power_manager_t * low_power_manager_interface)788 const hci_t *hci_layer_get_test_interface(
789 const allocator_t *buffer_allocator_interface,
790 const hci_hal_t *hal_interface,
791 const btsnoop_t *btsnoop_interface,
792 const hci_inject_t *hci_inject_interface,
793 const packet_fragmenter_t *packet_fragmenter_interface,
794 const vendor_t *vendor_interface,
795 const low_power_manager_t *low_power_manager_interface) {
796
797 buffer_allocator = buffer_allocator_interface;
798 hal = hal_interface;
799 btsnoop = btsnoop_interface;
800 hci_inject = hci_inject_interface;
801 packet_fragmenter = packet_fragmenter_interface;
802 vendor = vendor_interface;
803 low_power_manager = low_power_manager_interface;
804
805 init_layer_interface();
806 return &interface;
807 }
808