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