1 /******************************************************************************
3 * Copyright (C) 2014 Google, Inc.
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:
9 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 ******************************************************************************/
24 #include "bt_vendor_lib.h"
25 #include "hci_internals.h"
27 #include "hci_layer.h"
28 #include "allocator.h"
29 #include "packet_fragmenter.h"
30 #include "buffer_allocator.h"
37 future_t *complete_future;
38 command_complete_cb complete_callback;
39 command_status_cb status_callback;
47 osi_alarm_t *command_response_timer;
48 list_t *commands_pending_response;
49 pthread_mutex_t commands_pending_response_lock;
50 } command_waiting_response_t;
54 fixed_queue_t *command_queue;
55 fixed_queue_t *packet_queue;
57 // The hand-off point for data going to a higher layer, set by the higher layer
58 fixed_queue_t *upwards_data_queue;
60 command_waiting_response_t cmd_waiting_q;
63 non_repeating_timer_t *command_response_timer;
64 list_t *commands_pending_response;
65 pthread_mutex_t commands_pending_response_lock;
69 // Using a define here, because it can be stringified for the property lookup
70 static const uint32_t COMMAND_PENDING_TIMEOUT = 8000;
73 static bool interface_created;
74 static hci_t interface;
75 static hci_host_env_t hci_host_env;
77 static xTaskHandle xHciHostTaskHandle;
78 static xQueueHandle xHciHostQueue;
80 static bool hci_host_startup_flag;
82 // Modules we import and callbacks we export
83 static const allocator_t *buffer_allocator;
84 static const hci_hal_t *hal;
85 static const hci_hal_callbacks_t hal_callbacks;
86 static const packet_fragmenter_t *packet_fragmenter;
87 static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks;
89 static int hci_layer_init_env(void);
90 static void hci_layer_deinit_env(void);
91 static void hci_host_thread_handler(void *arg);
92 static void event_command_ready(fixed_queue_t *queue);
93 static void event_packet_ready(fixed_queue_t *queue);
94 static void restart_comamnd_waiting_response_timer(
95 command_waiting_response_t *cmd_wait_q,
96 bool tigger_by_sending_command);
97 static void command_timed_out(void *context);
98 static void hal_says_packet_ready(BT_HDR *packet);
99 static bool filter_incoming_event(BT_HDR *packet);
100 static serial_data_type_t event_to_data_type(uint16_t event);
101 static waiting_command_t *get_waiting_command(command_opcode_t opcode);
102 static void dispatch_reassembled(BT_HDR *packet);
104 // Module lifecycle functions
105 int hci_start_up(void)
107 if (hci_layer_init_env()) {
111 xHciHostQueue = xQueueCreate(HCI_HOST_QUEUE_NUM, sizeof(BtTaskEvt_t));
112 xTaskCreate(hci_host_thread_handler, HCI_HOST_TASK_NAME, HCI_HOST_TASK_STACK_SIZE, NULL, HCI_HOST_TASK_PRIO, &xHciHostTaskHandle);
114 packet_fragmenter->init(&packet_fragmenter_callbacks);
115 hal->open(&hal_callbacks);
117 hci_host_startup_flag = true;
124 void hci_shut_down(void)
126 hci_host_startup_flag = false;
127 hci_layer_deinit_env();
129 packet_fragmenter->cleanup();
131 //low_power_manager->cleanup();
133 vTaskDelete(xHciHostTaskHandle);
134 vQueueDelete(xHciHostQueue);
138 void hci_host_task_post(void)
142 if (hci_host_startup_flag == false) {
149 if (xQueueSend(xHciHostQueue, &evt, 10 / portTICK_RATE_MS) != pdTRUE) {
150 LOG_ERROR("xHciHostQueue failed\n");
154 static int hci_layer_init_env(void)
156 command_waiting_response_t *cmd_wait_q;
158 // The host is only allowed to send at most one command initially,
159 // as per the Bluetooth spec, Volume 2, Part E, 4.4 (Command Flow Control)
160 // This value can change when you get a command complete or command status event.
161 hci_host_env.command_credits = 1;
162 hci_host_env.command_queue = fixed_queue_new(SIZE_MAX);
163 if (hci_host_env.command_queue) {
164 fixed_queue_register_dequeue(hci_host_env.command_queue, event_command_ready);
166 LOG_ERROR("%s unable to create pending command queue.", __func__);
170 hci_host_env.packet_queue = fixed_queue_new(SIZE_MAX);
171 if (hci_host_env.packet_queue) {
172 fixed_queue_register_dequeue(hci_host_env.packet_queue, event_packet_ready);
174 LOG_ERROR("%s unable to create pending packet queue.", __func__);
178 // Init Commands waiting response list and timer
179 cmd_wait_q = &hci_host_env.cmd_waiting_q;
180 cmd_wait_q->timer_is_set = false;
181 cmd_wait_q->commands_pending_response = list_new(NULL);
182 if (!cmd_wait_q->commands_pending_response) {
183 LOG_ERROR("%s unable to create list for commands pending response.", __func__);
186 pthread_mutex_init(&cmd_wait_q->commands_pending_response_lock, NULL);
187 cmd_wait_q->command_response_timer = osi_alarm_new("cmd_rsp_to", command_timed_out, cmd_wait_q, COMMAND_PENDING_TIMEOUT, false);
188 if (!cmd_wait_q->command_response_timer) {
189 LOG_ERROR("%s unable to create command response timer.", __func__);
196 static void hci_layer_deinit_env(void)
198 command_waiting_response_t *cmd_wait_q;
200 if (hci_host_env.command_queue) {
201 fixed_queue_free(hci_host_env.command_queue, allocator_calloc.free);
203 if (hci_host_env.packet_queue) {
204 fixed_queue_free(hci_host_env.packet_queue, buffer_allocator->free);
207 cmd_wait_q = &hci_host_env.cmd_waiting_q;
208 list_free(cmd_wait_q->commands_pending_response);
209 pthread_mutex_destroy(&cmd_wait_q->commands_pending_response_lock);
210 osi_alarm_free(cmd_wait_q->command_response_timer);
211 cmd_wait_q->command_response_timer = NULL;
214 static void hci_host_thread_handler(void *arg)
217 * Previous task handles RX queue and two TX Queues, Since there is
218 * a RX Thread Task in H4 layer which receives packet from driver layer.
219 * Now HCI Host Task has been optimized to only process TX Queue
220 * including command and data queue. And command queue has high priority,
221 * All packets will be directly copied to single queue in driver layer with
222 * H4 type header added (1 byte).
227 if (pdTRUE == xQueueReceive(xHciHostQueue, &e, (portTickType)portMAX_DELAY)) {
229 if (API_vhci_host_check_send_available()) {
230 /*Now Target only allowed one packet per TX*/
231 BT_HDR *pkt = packet_fragmenter->fragment_current_packet();
233 packet_fragmenter->fragment_and_dispatch(pkt);
235 if (!fixed_queue_is_empty(hci_host_env.command_queue) &&
236 hci_host_env.command_credits > 0) {
237 fixed_queue_process(hci_host_env.command_queue);
238 } else if (!fixed_queue_is_empty(hci_host_env.packet_queue)) {
239 fixed_queue_process(hci_host_env.packet_queue);
248 static void set_data_queue(fixed_queue_t *queue)
250 hci_host_env.upwards_data_queue = queue;
253 static void transmit_command(
255 command_complete_cb complete_callback,
256 command_status_cb status_callback,
260 waiting_command_t *wait_entry = osi_calloc(sizeof(waiting_command_t));
262 LOG_ERROR("%s couldn't allocate space for wait entry.", __func__);
266 stream = command->data + command->offset;
267 STREAM_TO_UINT16(wait_entry->opcode, stream);
268 wait_entry->complete_callback = complete_callback;
269 wait_entry->status_callback = status_callback;
270 wait_entry->command = command;
271 wait_entry->context = context;
273 // Store the command message type in the event field
274 // in case the upper layer didn't already
275 command->event = MSG_STACK_TO_HC_HCI_CMD;
276 LOG_DEBUG("HCI Enqueue Comamnd opcode=0x%x\n", wait_entry->opcode);
277 BTTRC_DUMP_BUFFER(NULL, command->data + command->offset, command->len);
279 fixed_queue_enqueue(hci_host_env.command_queue, wait_entry);
280 hci_host_task_post();
283 static future_t *transmit_command_futured(BT_HDR *command)
285 waiting_command_t *wait_entry = osi_calloc(sizeof(waiting_command_t));
286 assert(wait_entry != NULL);
288 future_t *future = future_new();
290 uint8_t *stream = command->data + command->offset;
291 STREAM_TO_UINT16(wait_entry->opcode, stream);
292 wait_entry->complete_future = future;
293 wait_entry->command = command;
295 // Store the command message type in the event field
296 // in case the upper layer didn't already
297 command->event = MSG_STACK_TO_HC_HCI_CMD;
299 fixed_queue_enqueue(hci_host_env.command_queue, wait_entry);
300 hci_host_task_post();
304 static void transmit_downward(uint16_t type, void *data)
306 if (type == MSG_STACK_TO_HC_HCI_CMD) {
307 transmit_command((BT_HDR *)data, NULL, NULL, NULL);
308 LOG_WARN("%s legacy transmit of command. Use transmit_command instead.\n", __func__);
310 fixed_queue_enqueue(hci_host_env.packet_queue, data);
312 //ke_event_set(KE_EVENT_HCI_HOST_THREAD);
313 hci_host_task_post();
317 // Command/packet transmitting functions
318 static void event_command_ready(fixed_queue_t *queue)
320 waiting_command_t *wait_entry = NULL;
321 command_waiting_response_t *cmd_wait_q = &hci_host_env.cmd_waiting_q;
323 wait_entry = fixed_queue_dequeue(queue);
324 hci_host_env.command_credits--;
326 // Move it to the list of commands awaiting response
327 pthread_mutex_lock(&cmd_wait_q->commands_pending_response_lock);
328 list_append(cmd_wait_q->commands_pending_response, wait_entry);
329 pthread_mutex_unlock(&cmd_wait_q->commands_pending_response_lock);
332 packet_fragmenter->fragment_and_dispatch(wait_entry->command);
334 wait_entry->sent_time = osi_alarm_now();
335 restart_comamnd_waiting_response_timer(cmd_wait_q, true);
338 static void event_packet_ready(fixed_queue_t *queue)
340 BT_HDR *packet = (BT_HDR *)fixed_queue_dequeue(queue);
341 // The queue may be the command queue or the packet queue, we don't care
343 packet_fragmenter->fragment_and_dispatch(packet);
346 // Callback for the fragmenter to send a fragment
347 static void transmit_fragment(BT_HDR *packet, bool send_transmit_finished)
349 uint16_t event = packet->event & MSG_EVT_MASK;
350 serial_data_type_t type = event_to_data_type(event);
352 hal->transmit_data(type, packet->data + packet->offset, packet->len);
354 if (event != MSG_STACK_TO_HC_HCI_CMD && send_transmit_finished) {
355 buffer_allocator->free(packet);
359 static void fragmenter_transmit_finished(BT_HDR *packet, bool all_fragments_sent)
361 if (all_fragments_sent) {
362 buffer_allocator->free(packet);
364 // This is kind of a weird case, since we're dispatching a partially sent packet
365 // up to a higher layer.
366 // TODO(zachoverflow): rework upper layer so this isn't necessary.
367 dispatch_reassembled(packet);
368 //data_dispatcher_dispatch(interface.event_dispatcher, packet->event & MSG_EVT_MASK, packet);
372 static void restart_comamnd_waiting_response_timer(
373 command_waiting_response_t *cmd_wait_q,
374 bool tigger_by_sending_command)
377 waiting_command_t *wait_entry;
382 if (cmd_wait_q->timer_is_set) {
383 if (tigger_by_sending_command) {
387 //Cancel Previous command timeout timer setted when sending command
388 osi_alarm_cancel(cmd_wait_q->command_response_timer);
389 cmd_wait_q->timer_is_set = false;
392 pthread_mutex_lock(&cmd_wait_q->commands_pending_response_lock);
393 wait_entry = (list_is_empty(cmd_wait_q->commands_pending_response) ?
394 NULL : list_front(cmd_wait_q->commands_pending_response));
395 pthread_mutex_unlock(&cmd_wait_q->commands_pending_response_lock);
397 if (wait_entry == NULL) {
401 timeout = osi_alarm_time_diff(osi_alarm_now(), wait_entry->sent_time);
402 timeout = osi_alarm_time_diff(COMMAND_PENDING_TIMEOUT, timeout);
403 timeout = (timeout <= COMMAND_PENDING_TIMEOUT) ? timeout : COMMAND_PENDING_TIMEOUT;
405 cmd_wait_q->timer_is_set = true;
406 osi_alarm_set(cmd_wait_q->command_response_timer, timeout);
409 static void command_timed_out(void *context)
411 command_waiting_response_t *cmd_wait_q = (command_waiting_response_t *)context;
412 waiting_command_t *wait_entry;
414 pthread_mutex_lock(&cmd_wait_q->commands_pending_response_lock);
415 wait_entry = (list_is_empty(cmd_wait_q->commands_pending_response) ?
416 NULL : list_front(cmd_wait_q->commands_pending_response));
417 pthread_mutex_unlock(&cmd_wait_q->commands_pending_response_lock);
419 if (wait_entry == NULL) {
420 LOG_ERROR("%s with no commands pending response", __func__);
422 // We shouldn't try to recover the stack from this command timeout.
423 // If it's caused by a software bug, fix it. If it's a hardware bug, fix it.
425 LOG_ERROR("%s hci layer timeout waiting for response to a command. opcode: 0x%x", __func__, wait_entry->opcode);
429 // Event/packet receiving functions
430 static void hal_says_packet_ready(BT_HDR *packet)
432 if (packet->event != MSG_HC_TO_STACK_HCI_EVT) {
433 packet_fragmenter->reassemble_and_dispatch(packet);
434 } else if (!filter_incoming_event(packet)) {
435 dispatch_reassembled(packet);
439 // Returns true if the event was intercepted and should not proceed to
440 // higher layers. Also inspects an incoming event for interesting
441 // information, like how many commands are now able to be sent.
442 static bool filter_incoming_event(BT_HDR *packet)
444 waiting_command_t *wait_entry = NULL;
445 uint8_t *stream = packet->data + packet->offset;
447 command_opcode_t opcode;
449 STREAM_TO_UINT8(event_code, stream);
450 STREAM_SKIP_UINT8(stream); // Skip the parameter total length field
452 LOG_DEBUG("Receive packet event_code=0x%x\n", event_code);
454 if (event_code == HCI_COMMAND_COMPLETE_EVT) {
455 STREAM_TO_UINT8(hci_host_env.command_credits, stream);
456 STREAM_TO_UINT16(opcode, stream);
458 wait_entry = get_waiting_command(opcode);
460 LOG_WARN("%s command complete event with no matching command. opcode: 0x%x.", __func__, opcode);
461 } else if (wait_entry->complete_callback) {
462 wait_entry->complete_callback(packet, wait_entry->context);
463 } else if (wait_entry->complete_future) {
464 future_ready(wait_entry->complete_future, packet);
468 } else if (event_code == HCI_COMMAND_STATUS_EVT) {
470 STREAM_TO_UINT8(status, stream);
471 STREAM_TO_UINT8(hci_host_env.command_credits, stream);
472 STREAM_TO_UINT16(opcode, stream);
474 // If a command generates a command status event, it won't be getting a command complete event
476 wait_entry = get_waiting_command(opcode);
478 LOG_WARN("%s command status event with no matching command. opcode: 0x%x", __func__, opcode);
479 } else if (wait_entry->status_callback) {
480 wait_entry->status_callback(status, wait_entry->command, wait_entry->context);
488 restart_comamnd_waiting_response_timer(&hci_host_env.cmd_waiting_q, false);
490 /*Tell HCI Host Task to continue TX Pending commands*/
491 if (hci_host_env.command_credits &&
492 !fixed_queue_is_empty(hci_host_env.command_queue)) {
493 hci_host_task_post();
495 //ke_event_set(KE_EVENT_HCI_HOST_THREAD);
498 // If it has a callback, it's responsible for freeing the packet
499 if (event_code == HCI_COMMAND_STATUS_EVT ||
500 (!wait_entry->complete_callback && !wait_entry->complete_future)) {
501 buffer_allocator->free(packet);
504 // If it has a callback, it's responsible for freeing the command
505 if (event_code == HCI_COMMAND_COMPLETE_EVT || !wait_entry->status_callback) {
506 buffer_allocator->free(wait_entry->command);
509 osi_free(wait_entry);
511 buffer_allocator->free(packet);
517 // Callback for the fragmenter to dispatch up a completely reassembled packet
518 static void dispatch_reassembled(BT_HDR *packet)
520 // Events should already have been dispatched before this point
522 if (hci_host_env.upwards_data_queue) {
523 fixed_queue_enqueue(hci_host_env.upwards_data_queue, packet);
524 btu_task_post(SIG_BTU_WORK);
525 //Tell Up-layer received packet.
527 LOG_DEBUG("%s had no queue to place upwards data packet in. Dropping it on the floor.", __func__);
528 buffer_allocator->free(packet);
532 // Misc internal functions
534 // TODO(zachoverflow): we seem to do this a couple places, like the HCI inject module. #centralize
535 static serial_data_type_t event_to_data_type(uint16_t event)
537 if (event == MSG_STACK_TO_HC_HCI_ACL) {
538 return DATA_TYPE_ACL;
539 } else if (event == MSG_STACK_TO_HC_HCI_SCO) {
540 return DATA_TYPE_SCO;
541 } else if (event == MSG_STACK_TO_HC_HCI_CMD) {
542 return DATA_TYPE_COMMAND;
544 LOG_ERROR("%s invalid event type, could not translate 0x%x\n", __func__, event);
550 static waiting_command_t *get_waiting_command(command_opcode_t opcode)
552 command_waiting_response_t *cmd_wait_q = &hci_host_env.cmd_waiting_q;
553 pthread_mutex_lock(&cmd_wait_q->commands_pending_response_lock);
555 for (const list_node_t *node = list_begin(cmd_wait_q->commands_pending_response);
556 node != list_end(cmd_wait_q->commands_pending_response);
557 node = list_next(node)) {
558 waiting_command_t *wait_entry = list_node(node);
559 if (!wait_entry || wait_entry->opcode != opcode) {
563 list_remove(cmd_wait_q->commands_pending_response, wait_entry);
565 pthread_mutex_unlock(&cmd_wait_q->commands_pending_response_lock);
569 pthread_mutex_unlock(&cmd_wait_q->commands_pending_response_lock);
573 static void init_layer_interface()
575 if (!interface_created) {
576 interface.set_data_queue = set_data_queue;
577 interface.transmit_command = transmit_command;
578 interface.transmit_command_futured = transmit_command_futured;
579 interface.transmit_downward = transmit_downward;
580 interface_created = true;
584 static const hci_hal_callbacks_t hal_callbacks = {
585 hal_says_packet_ready
588 static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks = {
590 dispatch_reassembled,
591 fragmenter_transmit_finished
594 const hci_t *hci_layer_get_interface()
596 buffer_allocator = buffer_allocator_get_interface();
597 hal = hci_hal_h4_get_interface();
598 packet_fragmenter = packet_fragmenter_get_interface();
600 init_layer_interface();