OSDN Git Service

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