]> granicus.if.org Git - esp-idf/blob - components/bt/bluedroid/hci/hci_layer.c
component/bt: Merge branch 'master' into feature/btdm_a2dp
[esp-idf] / components / bt / bluedroid / hci / 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 #include <string.h>
19 #include "bt.h"
20 #include "bt_defs.h"
21 #include "bt_trace.h"
22 #include "hcidefs.h"
23 #include "hcimsgs.h"
24 #include "bt_vendor_lib.h"
25 #include "hci_internals.h"
26 #include "hci_hal.h"
27 #include "hci_layer.h"
28 #include "allocator.h"
29 #include "packet_fragmenter.h"
30 #include "buffer_allocator.h"
31 #include "list.h"
32 #include "alarm.h"
33 #include "thread.h"
34
35 typedef struct {
36     uint16_t opcode;
37     future_t *complete_future;
38     command_complete_cb complete_callback;
39     command_status_cb status_callback;
40     void *context;
41     uint32_t sent_time;
42     BT_HDR *command;
43 } waiting_command_t;
44
45 typedef struct {
46     bool timer_is_set;
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;
51
52 typedef struct {
53     int command_credits;
54     fixed_queue_t *command_queue;
55     fixed_queue_t *packet_queue;
56
57     // The hand-off point for data going to a higher layer, set by the higher layer
58     fixed_queue_t *upwards_data_queue;
59
60     command_waiting_response_t cmd_waiting_q;
61
62     /*
63       non_repeating_timer_t *command_response_timer;
64       list_t *commands_pending_response;
65       pthread_mutex_t commands_pending_response_lock;
66     */
67 } hci_host_env_t;
68
69 // Using a define here, because it can be stringified for the property lookup
70 static const uint32_t COMMAND_PENDING_TIMEOUT = 8000;
71
72 // Our interface
73 static bool interface_created;
74 static hci_t interface;
75 static hci_host_env_t hci_host_env;
76
77 static xTaskHandle  xHciHostTaskHandle;
78 static xQueueHandle xHciHostQueue;
79
80 static bool hci_host_startup_flag;
81
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;
88
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);
103
104 // Module lifecycle functions
105 int hci_start_up(void)
106 {
107     if (hci_layer_init_env()) {
108         goto error;
109     }
110
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);
113
114     packet_fragmenter->init(&packet_fragmenter_callbacks);
115     hal->open(&hal_callbacks);
116
117     hci_host_startup_flag = true;
118     return 0;
119 error:
120     hci_shut_down();
121     return -1;
122 }
123
124 void hci_shut_down(void)
125 {
126     hci_host_startup_flag  = false;
127     hci_layer_deinit_env();
128
129     packet_fragmenter->cleanup();
130
131     //low_power_manager->cleanup();
132     hal->close();
133     vTaskDelete(xHciHostTaskHandle);
134     vQueueDelete(xHciHostQueue);
135 }
136
137
138 void hci_host_task_post(void)
139 {
140     BtTaskEvt_t evt;
141
142     if (hci_host_startup_flag == false) {
143         return;
144     }
145
146     evt.sig = 0xff;
147     evt.par = 0;
148
149     if (xQueueSend(xHciHostQueue, &evt, 10 / portTICK_RATE_MS) != pdTRUE) {
150         LOG_ERROR("xHciHostQueue failed\n");
151     }
152 }
153
154 static int hci_layer_init_env(void)
155 {
156     command_waiting_response_t *cmd_wait_q;
157
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);
165     } else {
166         LOG_ERROR("%s unable to create pending command queue.", __func__);
167         return -1;
168     }
169
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);
173     } else {
174         LOG_ERROR("%s unable to create pending packet queue.", __func__);
175         return -1;
176     }
177
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__);
184         return -1;
185     }
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__);
190         return -1;
191     }
192
193     return 0;
194 }
195
196 static void hci_layer_deinit_env(void)
197 {
198     command_waiting_response_t *cmd_wait_q;
199
200     if (hci_host_env.command_queue) {
201         fixed_queue_free(hci_host_env.command_queue, allocator_calloc.free);
202     }
203     if (hci_host_env.packet_queue) {
204         fixed_queue_free(hci_host_env.packet_queue, buffer_allocator->free);
205     }
206
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;
212 }
213
214 static void hci_host_thread_handler(void *arg)
215 {
216     /*
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).
223      */
224
225     BtTaskEvt_t e;
226     for (;;) {
227         if (pdTRUE == xQueueReceive(xHciHostQueue, &e, (portTickType)portMAX_DELAY)) {
228             if (e.sig == 0xff) {
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();
232                     if (pkt != NULL) {
233                         packet_fragmenter->fragment_and_dispatch(pkt);
234                     } else {
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);
240                         }
241                     }
242                 }
243             }
244         }
245     }
246 }
247
248 static void set_data_queue(fixed_queue_t *queue)
249 {
250     hci_host_env.upwards_data_queue = queue;
251 }
252
253 static void transmit_command(
254     BT_HDR *command,
255     command_complete_cb complete_callback,
256     command_status_cb status_callback,
257     void *context)
258 {
259     uint8_t *stream;
260     waiting_command_t *wait_entry = osi_calloc(sizeof(waiting_command_t));
261     if (!wait_entry) {
262         LOG_ERROR("%s couldn't allocate space for wait entry.", __func__);
263         return;
264     }
265
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;
272
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);
278
279     fixed_queue_enqueue(hci_host_env.command_queue, wait_entry);
280     hci_host_task_post();
281 }
282
283 static future_t *transmit_command_futured(BT_HDR *command)
284 {
285     waiting_command_t *wait_entry = osi_calloc(sizeof(waiting_command_t));
286     assert(wait_entry != NULL);
287
288     future_t *future = future_new();
289
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;
294
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;
298
299     fixed_queue_enqueue(hci_host_env.command_queue, wait_entry);
300     hci_host_task_post();
301     return future;
302 }
303
304 static void transmit_downward(uint16_t type, void *data)
305 {
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__);
309     } else {
310         fixed_queue_enqueue(hci_host_env.packet_queue, data);
311     }
312     //ke_event_set(KE_EVENT_HCI_HOST_THREAD);
313     hci_host_task_post();
314 }
315
316
317 // Command/packet transmitting functions
318 static void event_command_ready(fixed_queue_t *queue)
319 {
320     waiting_command_t *wait_entry = NULL;
321     command_waiting_response_t *cmd_wait_q = &hci_host_env.cmd_waiting_q;
322
323     wait_entry = fixed_queue_dequeue(queue);
324     hci_host_env.command_credits--;
325
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);
330
331     // Send it off
332     packet_fragmenter->fragment_and_dispatch(wait_entry->command);
333
334     wait_entry->sent_time = osi_alarm_now();
335     restart_comamnd_waiting_response_timer(cmd_wait_q, true);
336 }
337
338 static void event_packet_ready(fixed_queue_t *queue)
339 {
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
342
343     packet_fragmenter->fragment_and_dispatch(packet);
344 }
345
346 // Callback for the fragmenter to send a fragment
347 static void transmit_fragment(BT_HDR *packet, bool send_transmit_finished)
348 {
349     uint16_t event = packet->event & MSG_EVT_MASK;
350     serial_data_type_t type = event_to_data_type(event);
351
352     hal->transmit_data(type, packet->data + packet->offset, packet->len);
353
354     if (event != MSG_STACK_TO_HC_HCI_CMD && send_transmit_finished) {
355         buffer_allocator->free(packet);
356     }
357 }
358
359 static void fragmenter_transmit_finished(BT_HDR *packet, bool all_fragments_sent)
360 {
361     if (all_fragments_sent) {
362         buffer_allocator->free(packet);
363     } else {
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);
369     }
370 }
371
372 static void restart_comamnd_waiting_response_timer(
373     command_waiting_response_t *cmd_wait_q,
374     bool tigger_by_sending_command)
375 {
376     uint32_t timeout;
377     waiting_command_t *wait_entry;
378     if (!cmd_wait_q) {
379         return;
380     }
381
382     if (cmd_wait_q->timer_is_set) {
383         if (tigger_by_sending_command) {
384             return;
385         }
386
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;
390     }
391
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);
396
397     if (wait_entry == NULL) {
398         return;
399     }
400
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;
404
405     cmd_wait_q->timer_is_set = true;
406     osi_alarm_set(cmd_wait_q->command_response_timer, timeout);
407 }
408
409 static void command_timed_out(void *context)
410 {
411     command_waiting_response_t *cmd_wait_q = (command_waiting_response_t *)context;
412     waiting_command_t *wait_entry;
413
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);
418
419     if (wait_entry == NULL) {
420         LOG_ERROR("%s with no commands pending response", __func__);
421     } else
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.
424     {
425         LOG_ERROR("%s hci layer timeout waiting for response to a command. opcode: 0x%x", __func__, wait_entry->opcode);
426     }
427 }
428
429 // Event/packet receiving functions
430 static void hal_says_packet_ready(BT_HDR *packet)
431 {
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);
436     }
437 }
438
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)
443 {
444     waiting_command_t *wait_entry = NULL;
445     uint8_t *stream = packet->data + packet->offset;
446     uint8_t event_code;
447     command_opcode_t opcode;
448
449     STREAM_TO_UINT8(event_code, stream);
450     STREAM_SKIP_UINT8(stream); // Skip the parameter total length field
451
452     LOG_DEBUG("Receive packet event_code=0x%x\n", event_code);
453
454     if (event_code == HCI_COMMAND_COMPLETE_EVT) {
455         STREAM_TO_UINT8(hci_host_env.command_credits, stream);
456         STREAM_TO_UINT16(opcode, stream);
457
458         wait_entry = get_waiting_command(opcode);
459         if (!wait_entry) {
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);
465         }
466
467         goto intercepted;
468     } else if (event_code == HCI_COMMAND_STATUS_EVT) {
469         uint8_t status;
470         STREAM_TO_UINT8(status, stream);
471         STREAM_TO_UINT8(hci_host_env.command_credits, stream);
472         STREAM_TO_UINT16(opcode, stream);
473
474         // If a command generates a command status event, it won't be getting a command complete event
475
476         wait_entry = get_waiting_command(opcode);
477         if (!wait_entry) {
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);
481         }
482
483         goto intercepted;
484     }
485
486     return false;
487 intercepted:
488     restart_comamnd_waiting_response_timer(&hci_host_env.cmd_waiting_q, false);
489
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();
494     }
495     //ke_event_set(KE_EVENT_HCI_HOST_THREAD);
496
497     if (wait_entry) {
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);
502         }
503
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);
507         }
508
509         osi_free(wait_entry);
510     } else {
511         buffer_allocator->free(packet);
512     }
513
514     return true;
515 }
516
517 // Callback for the fragmenter to dispatch up a completely reassembled packet
518 static void dispatch_reassembled(BT_HDR *packet)
519 {
520     // Events should already have been dispatched before this point
521
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.
526     } else {
527         LOG_DEBUG("%s had no queue to place upwards data packet in. Dropping it on the floor.", __func__);
528         buffer_allocator->free(packet);
529     }
530 }
531
532 // Misc internal functions
533
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)
536 {
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;
543     } else {
544         LOG_ERROR("%s invalid event type, could not translate 0x%x\n", __func__, event);
545     }
546
547     return 0;
548 }
549
550 static waiting_command_t *get_waiting_command(command_opcode_t opcode)
551 {
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);
554
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) {
560             continue;
561         }
562
563         list_remove(cmd_wait_q->commands_pending_response, wait_entry);
564
565         pthread_mutex_unlock(&cmd_wait_q->commands_pending_response_lock);
566         return wait_entry;
567     }
568
569     pthread_mutex_unlock(&cmd_wait_q->commands_pending_response_lock);
570     return NULL;
571 }
572
573 static void init_layer_interface()
574 {
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;
581     }
582 }
583
584 static const hci_hal_callbacks_t hal_callbacks = {
585     hal_says_packet_ready
586 };
587
588 static const packet_fragmenter_callbacks_t packet_fragmenter_callbacks = {
589     transmit_fragment,
590     dispatch_reassembled,
591     fragmenter_transmit_finished
592 };
593
594 const hci_t *hci_layer_get_interface()
595 {
596     buffer_allocator = buffer_allocator_get_interface();
597     hal = hci_hal_h4_get_interface();
598     packet_fragmenter = packet_fragmenter_get_interface();
599
600     init_layer_interface();
601     return &interface;
602 }
603