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