-
Notifications
You must be signed in to change notification settings - Fork 606
/
hci.c
5060 lines (4453 loc) · 198 KB
/
hci.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (C) 2014 BlueKitchen GmbH
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holders nor the names of
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
* 4. Any redistribution, use, or modification is done solely for
* personal benefit and not for any commercial purpose or for
* monetary gain.
*
* THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
* ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
* RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
* THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* Please inquire about commercial licensing options at
* contact@bluekitchen-gmbh.com
*
*/
#define __BTSTACK_FILE__ "hci.c"
/*
* hci.c
*
* Created by Matthias Ringwald on 4/29/09.
*
*/
#include "btstack_config.h"
#ifdef ENABLE_CLASSIC
#ifdef HAVE_EMBEDDED_TICK
#include "btstack_run_loop_embedded.h"
#endif
#endif
#ifdef HAVE_PLATFORM_IPHONE_OS
#include "../port/ios/src/btstack_control_iphone.h"
#endif
#ifdef ENABLE_BLE
#include "gap.h"
#endif
#include <stdarg.h>
#include <string.h>
#include <stdio.h>
#include <inttypes.h>
#include "btstack_debug.h"
#include "btstack_event.h"
#include "btstack_linked_list.h"
#include "btstack_memory.h"
#include "bluetooth_company_id.h"
#include "bluetooth_data_types.h"
#include "gap.h"
#include "hci.h"
#include "hci_cmd.h"
#include "hci_dump.h"
#include "ad_parser.h"
#ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
#ifndef HCI_HOST_ACL_PACKET_NUM
#error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_NUM"
#endif
#ifndef HCI_HOST_ACL_PACKET_LEN
#error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_ACL_PACKET_LEN"
#endif
#ifndef HCI_HOST_SCO_PACKET_NUM
#error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_NUM"
#endif
#ifndef HCI_HOST_SCO_PACKET_LEN
#error "ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL requires to define HCI_HOST_SCO_PACKET_LEN"
#endif
#endif
#define HCI_CONNECTION_TIMEOUT_MS 10000
#define HCI_RESET_RESEND_TIMEOUT_MS 200
// Names are arbitrarily shortened to 32 bytes if not requested otherwise
#ifndef GAP_INQUIRY_MAX_NAME_LEN
#define GAP_INQUIRY_MAX_NAME_LEN 32
#endif
// GAP inquiry state: 0 = off, 0x01 - 0x30 = requested duration, 0xfe = active, 0xff = stop requested
#define GAP_INQUIRY_DURATION_MIN 0x01
#define GAP_INQUIRY_DURATION_MAX 0x30
#define GAP_INQUIRY_STATE_ACTIVE 0x80
#define GAP_INQUIRY_STATE_IDLE 0
#define GAP_INQUIRY_STATE_W2_CANCEL 0x81
#define GAP_INQUIRY_STATE_W4_CANCELLED 0x82
// GAP Remote Name Request
#define GAP_REMOTE_NAME_STATE_IDLE 0
#define GAP_REMOTE_NAME_STATE_W2_SEND 1
#define GAP_REMOTE_NAME_STATE_W4_COMPLETE 2
// GAP Pairing
#define GAP_PAIRING_STATE_IDLE 0
#define GAP_PAIRING_STATE_SEND_PIN 1
#define GAP_PAIRING_STATE_SEND_PIN_NEGATIVE 2
#define GAP_PAIRING_STATE_SEND_PASSKEY 3
#define GAP_PAIRING_STATE_SEND_PASSKEY_NEGATIVE 4
#define GAP_PAIRING_STATE_SEND_CONFIRMATION 5
#define GAP_PAIRING_STATE_SEND_CONFIRMATION_NEGATIVE 6
// prototypes
#ifdef ENABLE_CLASSIC
static void hci_update_scan_enable(void);
static void hci_emit_discoverable_enabled(uint8_t enabled);
static int hci_local_ssp_activated(void);
static int hci_remote_ssp_supported(hci_con_handle_t con_handle);
static void hci_notify_if_sco_can_send_now(void);
static void hci_emit_connection_complete(bd_addr_t address, hci_con_handle_t con_handle, uint8_t status);
static gap_security_level_t gap_security_level_for_connection(hci_connection_t * connection);
static void hci_emit_security_level(hci_con_handle_t con_handle, gap_security_level_t level);
static void hci_connection_timeout_handler(btstack_timer_source_t *timer);
static void hci_connection_timestamp(hci_connection_t *connection);
static void hci_emit_l2cap_check_timeout(hci_connection_t *conn);
static void gap_inquiry_explode(uint8_t * packet);
#endif
static int hci_power_control_on(void);
static void hci_power_control_off(void);
static void hci_state_reset(void);
static void hci_emit_transport_packet_sent(void);
static void hci_emit_disconnection_complete(hci_con_handle_t con_handle, uint8_t reason);
static void hci_emit_nr_connections_changed(void);
static void hci_emit_hci_open_failed(void);
static void hci_emit_dedicated_bonding_result(bd_addr_t address, uint8_t status);
static void hci_emit_event(uint8_t * event, uint16_t size, int dump);
static void hci_emit_acl_packet(uint8_t * packet, uint16_t size);
static void hci_run(void);
static int hci_is_le_connection(hci_connection_t * connection);
static int hci_number_free_acl_slots_for_connection_type( bd_addr_type_t address_type);
#ifdef ENABLE_BLE
#ifdef ENABLE_LE_CENTRAL
// called from test/ble_client/advertising_data_parser.c
void le_handle_advertisement_report(uint8_t *packet, uint16_t size);
static void hci_remove_from_whitelist(bd_addr_type_t address_type, bd_addr_t address);
static hci_connection_t * gap_get_outgoing_connection(void);
#endif
#endif
// the STACK is here
#ifndef HAVE_MALLOC
static hci_stack_t hci_stack_static;
#endif
static hci_stack_t * hci_stack = NULL;
#ifdef ENABLE_CLASSIC
// default name
static const char * default_classic_name = "BTstack 00:00:00:00:00:00";
// test helper
static uint8_t disable_l2cap_timeouts = 0;
#endif
/**
* create connection for given address
*
* @return connection OR NULL, if no memory left
*/
static hci_connection_t * create_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
log_info("create_connection_for_addr %s, type %x", bd_addr_to_str(addr), addr_type);
hci_connection_t * conn = btstack_memory_hci_connection_get();
if (!conn) return NULL;
bd_addr_copy(conn->address, addr);
conn->address_type = addr_type;
conn->con_handle = 0xffff;
conn->authentication_flags = AUTH_FLAGS_NONE;
conn->bonding_flags = 0;
conn->requested_security_level = LEVEL_0;
#ifdef ENABLE_CLASSIC
btstack_run_loop_set_timer_handler(&conn->timeout, hci_connection_timeout_handler);
btstack_run_loop_set_timer_context(&conn->timeout, conn);
hci_connection_timestamp(conn);
conn->num_sco_bytes_sent = 0;
#endif
conn->acl_recombination_length = 0;
conn->acl_recombination_pos = 0;
conn->num_packets_sent = 0;
conn->le_con_parameter_update_state = CON_PARAMETER_UPDATE_NONE;
#ifdef ENABLE_BLE
conn->le_phy_update_all_phys = 0xff;
#endif
btstack_linked_list_add(&hci_stack->connections, (btstack_linked_item_t *) conn);
return conn;
}
/**
* get le connection parameter range
*
* @return le connection parameter range struct
*/
void gap_get_connection_parameter_range(le_connection_parameter_range_t * range){
*range = hci_stack->le_connection_parameter_range;
}
/**
* set le connection parameter range
*
*/
void gap_set_connection_parameter_range(le_connection_parameter_range_t *range){
hci_stack->le_connection_parameter_range = *range;
}
/**
* @brief Test if connection parameters are inside in existing rage
* @param conn_interval_min (unit: 1.25ms)
* @param conn_interval_max (unit: 1.25ms)
* @param conn_latency
* @param supervision_timeout (unit: 10ms)
* @returns 1 if included
*/
int gap_connection_parameter_range_included(le_connection_parameter_range_t * existing_range, uint16_t le_conn_interval_min, uint16_t le_conn_interval_max, uint16_t le_conn_latency, uint16_t le_supervision_timeout){
if (le_conn_interval_min < existing_range->le_conn_interval_min) return 0;
if (le_conn_interval_max > existing_range->le_conn_interval_max) return 0;
if (le_conn_latency < existing_range->le_conn_latency_min) return 0;
if (le_conn_latency > existing_range->le_conn_latency_max) return 0;
if (le_supervision_timeout < existing_range->le_supervision_timeout_min) return 0;
if (le_supervision_timeout > existing_range->le_supervision_timeout_max) return 0;
return 1;
}
/**
* @brief Set max number of connections in LE Peripheral role (if Bluetooth Controller supports it)
* @note: default: 1
* @param max_peripheral_connections
*/
#ifdef ENABLE_LE_PERIPHERAL
void gap_set_max_number_peripheral_connections(int max_peripheral_connections){
hci_stack->le_max_number_peripheral_connections = max_peripheral_connections;
}
#endif
/**
* get hci connections iterator
*
* @return hci connections iterator
*/
void hci_connections_get_iterator(btstack_linked_list_iterator_t *it){
btstack_linked_list_iterator_init(it, &hci_stack->connections);
}
/**
* get connection for a given handle
*
* @return connection OR NULL, if not found
*/
hci_connection_t * hci_connection_for_handle(hci_con_handle_t con_handle){
btstack_linked_list_iterator_t it;
btstack_linked_list_iterator_init(&it, &hci_stack->connections);
while (btstack_linked_list_iterator_has_next(&it)){
hci_connection_t * item = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
if ( item->con_handle == con_handle ) {
return item;
}
}
return NULL;
}
/**
* get connection for given address
*
* @return connection OR NULL, if not found
*/
hci_connection_t * hci_connection_for_bd_addr_and_type(bd_addr_t addr, bd_addr_type_t addr_type){
btstack_linked_list_iterator_t it;
btstack_linked_list_iterator_init(&it, &hci_stack->connections);
while (btstack_linked_list_iterator_has_next(&it)){
hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
if (connection->address_type != addr_type) continue;
if (memcmp(addr, connection->address, 6) != 0) continue;
return connection;
}
return NULL;
}
#ifdef ENABLE_CLASSIC
#ifdef ENABLE_SCO_OVER_HCI
static int hci_number_sco_connections(void){
int connections = 0;
btstack_linked_list_iterator_t it;
btstack_linked_list_iterator_init(&it, &hci_stack->connections);
while (btstack_linked_list_iterator_has_next(&it)){
hci_connection_t * connection = (hci_connection_t *) btstack_linked_list_iterator_next(&it);
if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
connections++;
}
return connections;
}
#endif
static void hci_connection_timeout_handler(btstack_timer_source_t *timer){
hci_connection_t * connection = (hci_connection_t *) btstack_run_loop_get_timer_context(timer);
#ifdef HAVE_EMBEDDED_TICK
if (btstack_run_loop_embedded_get_ticks() > connection->timestamp + btstack_run_loop_embedded_ticks_for_ms(HCI_CONNECTION_TIMEOUT_MS)){
// connections might be timed out
hci_emit_l2cap_check_timeout(connection);
}
#else
if (btstack_run_loop_get_time_ms() > connection->timestamp + HCI_CONNECTION_TIMEOUT_MS){
// connections might be timed out
hci_emit_l2cap_check_timeout(connection);
}
#endif
}
static void hci_connection_timestamp(hci_connection_t *connection){
#ifdef HAVE_EMBEDDED_TICK
connection->timestamp = btstack_run_loop_embedded_get_ticks();
#else
connection->timestamp = btstack_run_loop_get_time_ms();
#endif
}
inline static void connectionSetAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags | flags);
}
inline static void connectionClearAuthenticationFlags(hci_connection_t * conn, hci_authentication_flags_t flags){
conn->authentication_flags = (hci_authentication_flags_t)(conn->authentication_flags & ~flags);
}
/**
* add authentication flags and reset timer
* @note: assumes classic connection
* @note: bd_addr is passed in as litle endian uint8_t * as it is called from parsing packets
*/
static void hci_add_connection_flags_for_flipped_bd_addr(uint8_t *bd_addr, hci_authentication_flags_t flags){
bd_addr_t addr;
reverse_bd_addr(bd_addr, addr);
hci_connection_t * conn = hci_connection_for_bd_addr_and_type(addr, BD_ADDR_TYPE_CLASSIC);
if (conn) {
connectionSetAuthenticationFlags(conn, flags);
hci_connection_timestamp(conn);
}
}
int hci_authentication_active_for_handle(hci_con_handle_t handle){
hci_connection_t * conn = hci_connection_for_handle(handle);
if (!conn) return 0;
if (conn->authentication_flags & LEGACY_PAIRING_ACTIVE) return 1;
if (conn->authentication_flags & SSP_PAIRING_ACTIVE) return 1;
return 0;
}
void gap_drop_link_key_for_bd_addr(bd_addr_t addr){
if (!hci_stack->link_key_db) return;
log_info("gap_drop_link_key_for_bd_addr: %s", bd_addr_to_str(addr));
hci_stack->link_key_db->delete_link_key(addr);
}
void gap_store_link_key_for_bd_addr(bd_addr_t addr, link_key_t link_key, link_key_type_t type){
if (!hci_stack->link_key_db) return;
log_info("gap_store_link_key_for_bd_addr: %s, type %u", bd_addr_to_str(addr), type);
hci_stack->link_key_db->put_link_key(addr, link_key, type);
}
void gap_delete_all_link_keys(void){
bd_addr_t addr;
link_key_t link_key;
link_key_type_t type;
btstack_link_key_iterator_t it;
int ok = gap_link_key_iterator_init(&it);
if (!ok) {
log_error("could not initialize iterator");
return;
}
while (gap_link_key_iterator_get_next(&it, addr, link_key, &type)){
gap_drop_link_key_for_bd_addr(addr);
}
gap_link_key_iterator_done(&it);
}
int gap_link_key_iterator_init(btstack_link_key_iterator_t * it){
if (!hci_stack->link_key_db) return 0;
if (!hci_stack->link_key_db->iterator_init) return 0;
return hci_stack->link_key_db->iterator_init(it);
}
int gap_link_key_iterator_get_next(btstack_link_key_iterator_t * it, bd_addr_t bd_addr, link_key_t link_key, link_key_type_t * type){
if (!hci_stack->link_key_db) return 0;
return hci_stack->link_key_db->iterator_get_next(it, bd_addr, link_key, type);
}
void gap_link_key_iterator_done(btstack_link_key_iterator_t * it){
if (!hci_stack->link_key_db) return;
hci_stack->link_key_db->iterator_done(it);
}
#endif
static int hci_is_le_connection(hci_connection_t * connection){
switch (connection->address_type){
case BD_ADDR_TYPE_LE_PUBLIC:
case BD_ADDR_TYPE_LE_RANDOM:
case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_PUBLIC:
case BD_ADDR_TYPE_LE_PRIVAT_FALLBACK_RANDOM:
return 1;
default:
return 0;
}
}
/**
* count connections
*/
static int nr_hci_connections(void){
int count = 0;
btstack_linked_item_t *it;
for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next, count++);
return count;
}
static int hci_number_free_acl_slots_for_connection_type(bd_addr_type_t address_type){
unsigned int num_packets_sent_classic = 0;
unsigned int num_packets_sent_le = 0;
btstack_linked_item_t *it;
for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
hci_connection_t * connection = (hci_connection_t *) it;
if (hci_is_le_connection(connection)){
num_packets_sent_le += connection->num_packets_sent;
}
if (connection->address_type == BD_ADDR_TYPE_CLASSIC){
num_packets_sent_classic += connection->num_packets_sent;
}
}
log_debug("ACL classic buffers: %u used of %u", num_packets_sent_classic, hci_stack->acl_packets_total_num);
int free_slots_classic = hci_stack->acl_packets_total_num - num_packets_sent_classic;
int free_slots_le = 0;
if (free_slots_classic < 0){
log_error("hci_number_free_acl_slots: outgoing classic packets (%u) > total classic packets (%u)", num_packets_sent_classic, hci_stack->acl_packets_total_num);
return 0;
}
if (hci_stack->le_acl_packets_total_num){
// if we have LE slots, they are used
free_slots_le = hci_stack->le_acl_packets_total_num - num_packets_sent_le;
if (free_slots_le < 0){
log_error("hci_number_free_acl_slots: outgoing le packets (%u) > total le packets (%u)", num_packets_sent_le, hci_stack->le_acl_packets_total_num);
return 0;
}
} else {
// otherwise, classic slots are used for LE, too
free_slots_classic -= num_packets_sent_le;
if (free_slots_classic < 0){
log_error("hci_number_free_acl_slots: outgoing classic + le packets (%u + %u) > total packets (%u)", num_packets_sent_classic, num_packets_sent_le, hci_stack->acl_packets_total_num);
return 0;
}
}
switch (address_type){
case BD_ADDR_TYPE_UNKNOWN:
log_error("hci_number_free_acl_slots: unknown address type");
return 0;
case BD_ADDR_TYPE_CLASSIC:
return free_slots_classic;
default:
if (hci_stack->le_acl_packets_total_num){
return free_slots_le;
}
return free_slots_classic;
}
}
int hci_number_free_acl_slots_for_handle(hci_con_handle_t con_handle){
// get connection type
hci_connection_t * connection = hci_connection_for_handle(con_handle);
if (!connection){
log_error("hci_number_free_acl_slots: handle 0x%04x not in connection list", con_handle);
return 0;
}
return hci_number_free_acl_slots_for_connection_type(connection->address_type);
}
#ifdef ENABLE_CLASSIC
static int hci_number_free_sco_slots(void){
unsigned int num_sco_packets_sent = 0;
btstack_linked_item_t *it;
if (hci_stack->synchronous_flow_control_enabled){
// explicit flow control
for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
hci_connection_t * connection = (hci_connection_t *) it;
if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
num_sco_packets_sent += connection->num_packets_sent;
}
} else {
// implicit flow control
uint16_t num_sco_bytes_sent = 0;
for (it = (btstack_linked_item_t *) hci_stack->connections; it ; it = it->next){
hci_connection_t * connection = (hci_connection_t *) it;
if (connection->address_type != BD_ADDR_TYPE_SCO) continue;
num_sco_bytes_sent += connection->num_sco_bytes_sent;
}
// deduce used slots from num sco bytes (plus 2 extra to be on the safe side)
unsigned int sco_payload_len = hci_get_sco_packet_length() - 3;
num_sco_packets_sent = (num_sco_bytes_sent / sco_payload_len) + 2;
log_info("hci_number_free_sco_slots: bytes sent %u -> packets sent %u", num_sco_bytes_sent, num_sco_packets_sent);
}
if (num_sco_packets_sent > hci_stack->sco_packets_total_num){
log_info("hci_number_free_sco_slots:packets (%u) > total packets (%u)", num_sco_packets_sent, hci_stack->sco_packets_total_num);
return 0;
}
return hci_stack->sco_packets_total_num - num_sco_packets_sent;
}
#endif
// only used to send HCI Host Number Completed Packets
static int hci_can_send_comand_packet_transport(void){
if (hci_stack->hci_packet_buffer_reserved) return 0;
// check for async hci transport implementations
if (hci_stack->hci_transport->can_send_packet_now){
if (!hci_stack->hci_transport->can_send_packet_now(HCI_COMMAND_DATA_PACKET)){
return 0;
}
}
return 1;
}
// new functions replacing hci_can_send_packet_now[_using_packet_buffer]
int hci_can_send_command_packet_now(void){
if (hci_can_send_comand_packet_transport() == 0) return 0;
return hci_stack->num_cmd_packets > 0;
}
static int hci_transport_can_send_prepared_packet_now(uint8_t packet_type){
// check for async hci transport implementations
if (!hci_stack->hci_transport->can_send_packet_now) return 1;
return hci_stack->hci_transport->can_send_packet_now(packet_type);
}
static int hci_can_send_prepared_acl_packet_for_address_type(bd_addr_type_t address_type){
if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
return hci_number_free_acl_slots_for_connection_type(address_type) > 0;
}
int hci_can_send_acl_le_packet_now(void){
if (hci_stack->hci_packet_buffer_reserved) return 0;
return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_LE_PUBLIC);
}
int hci_can_send_prepared_acl_packet_now(hci_con_handle_t con_handle) {
if (!hci_transport_can_send_prepared_packet_now(HCI_ACL_DATA_PACKET)) return 0;
return hci_number_free_acl_slots_for_handle(con_handle) > 0;
}
int hci_can_send_acl_packet_now(hci_con_handle_t con_handle){
if (hci_stack->hci_packet_buffer_reserved) return 0;
return hci_can_send_prepared_acl_packet_now(con_handle);
}
#ifdef ENABLE_CLASSIC
int hci_can_send_acl_classic_packet_now(void){
if (hci_stack->hci_packet_buffer_reserved) return 0;
return hci_can_send_prepared_acl_packet_for_address_type(BD_ADDR_TYPE_CLASSIC);
}
int hci_can_send_prepared_sco_packet_now(void){
if (!hci_transport_can_send_prepared_packet_now(HCI_SCO_DATA_PACKET)) return 0;
return hci_number_free_sco_slots() > 0;
}
int hci_can_send_sco_packet_now(void){
if (hci_stack->hci_packet_buffer_reserved) return 0;
return hci_can_send_prepared_sco_packet_now();
}
void hci_request_sco_can_send_now_event(void){
hci_stack->sco_waiting_for_can_send_now = 1;
hci_notify_if_sco_can_send_now();
}
#endif
// used for internal checks in l2cap.c
int hci_is_packet_buffer_reserved(void){
return hci_stack->hci_packet_buffer_reserved;
}
// reserves outgoing packet buffer. @returns 1 if successful
int hci_reserve_packet_buffer(void){
if (hci_stack->hci_packet_buffer_reserved) {
log_error("hci_reserve_packet_buffer called but buffer already reserved");
return 0;
}
hci_stack->hci_packet_buffer_reserved = 1;
return 1;
}
void hci_release_packet_buffer(void){
hci_stack->hci_packet_buffer_reserved = 0;
}
// assumption: synchronous implementations don't provide can_send_packet_now as they don't keep the buffer after the call
static int hci_transport_synchronous(void){
return hci_stack->hci_transport->can_send_packet_now == NULL;
}
static int hci_send_acl_packet_fragments(hci_connection_t *connection){
// log_info("hci_send_acl_packet_fragments %u/%u (con 0x%04x)", hci_stack->acl_fragmentation_pos, hci_stack->acl_fragmentation_total_size, connection->con_handle);
// max ACL data packet length depends on connection type (LE vs. Classic) and available buffers
uint16_t max_acl_data_packet_length = hci_stack->acl_data_packet_length;
if (hci_is_le_connection(connection) && hci_stack->le_data_packets_length > 0){
max_acl_data_packet_length = hci_stack->le_data_packets_length;
}
// testing: reduce buffer to minimum
// max_acl_data_packet_length = 52;
log_debug("hci_send_acl_packet_fragments entered");
int err;
// multiple packets could be send on a synchronous HCI transport
while (1){
log_debug("hci_send_acl_packet_fragments loop entered");
// get current data
const uint16_t acl_header_pos = hci_stack->acl_fragmentation_pos - 4;
int current_acl_data_packet_length = hci_stack->acl_fragmentation_total_size - hci_stack->acl_fragmentation_pos;
int more_fragments = 0;
// if ACL packet is larger than Bluetooth packet buffer, only send max_acl_data_packet_length
if (current_acl_data_packet_length > max_acl_data_packet_length){
more_fragments = 1;
current_acl_data_packet_length = max_acl_data_packet_length;
}
// copy handle_and_flags if not first fragment and update packet boundary flags to be 01 (continuing fragmnent)
if (acl_header_pos > 0){
uint16_t handle_and_flags = little_endian_read_16(hci_stack->hci_packet_buffer, 0);
handle_and_flags = (handle_and_flags & 0xcfff) | (1 << 12);
little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos, handle_and_flags);
}
// update header len
little_endian_store_16(hci_stack->hci_packet_buffer, acl_header_pos + 2, current_acl_data_packet_length);
// count packet
connection->num_packets_sent++;
log_debug("hci_send_acl_packet_fragments loop before send (more fragments %d)", more_fragments);
// update state for next fragment (if any) as "transport done" might be sent during send_packet already
if (more_fragments){
// update start of next fragment to send
hci_stack->acl_fragmentation_pos += current_acl_data_packet_length;
} else {
// done
hci_stack->acl_fragmentation_pos = 0;
hci_stack->acl_fragmentation_total_size = 0;
}
// send packet
uint8_t * packet = &hci_stack->hci_packet_buffer[acl_header_pos];
const int size = current_acl_data_packet_length + 4;
hci_dump_packet(HCI_ACL_DATA_PACKET, 0, packet, size);
hci_stack->acl_fragmentation_tx_active = 1;
err = hci_stack->hci_transport->send_packet(HCI_ACL_DATA_PACKET, packet, size);
log_debug("hci_send_acl_packet_fragments loop after send (more fragments %d)", more_fragments);
// done yet?
if (!more_fragments) break;
// can send more?
if (!hci_can_send_prepared_acl_packet_now(connection->con_handle)) return err;
}
log_debug("hci_send_acl_packet_fragments loop over");
// release buffer now for synchronous transport
if (hci_transport_synchronous()){
hci_stack->acl_fragmentation_tx_active = 0;
hci_release_packet_buffer();
hci_emit_transport_packet_sent();
}
return err;
}
// pre: caller has reserved the packet buffer
int hci_send_acl_packet_buffer(int size){
// log_info("hci_send_acl_packet_buffer size %u", size);
if (!hci_stack->hci_packet_buffer_reserved) {
log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
return 0;
}
uint8_t * packet = hci_stack->hci_packet_buffer;
hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
// check for free places on Bluetooth module
if (!hci_can_send_prepared_acl_packet_now(con_handle)) {
log_error("hci_send_acl_packet_buffer called but no free ACL buffers on controller");
hci_release_packet_buffer();
hci_emit_transport_packet_sent();
return BTSTACK_ACL_BUFFERS_FULL;
}
hci_connection_t *connection = hci_connection_for_handle( con_handle);
if (!connection) {
log_error("hci_send_acl_packet_buffer called but no connection for handle 0x%04x", con_handle);
hci_release_packet_buffer();
hci_emit_transport_packet_sent();
return 0;
}
#ifdef ENABLE_CLASSIC
hci_connection_timestamp(connection);
#endif
// hci_dump_packet( HCI_ACL_DATA_PACKET, 0, packet, size);
// setup data
hci_stack->acl_fragmentation_total_size = size;
hci_stack->acl_fragmentation_pos = 4; // start of L2CAP packet
return hci_send_acl_packet_fragments(connection);
}
#ifdef ENABLE_CLASSIC
// pre: caller has reserved the packet buffer
int hci_send_sco_packet_buffer(int size){
// log_info("hci_send_acl_packet_buffer size %u", size);
if (!hci_stack->hci_packet_buffer_reserved) {
log_error("hci_send_acl_packet_buffer called without reserving packet buffer");
return 0;
}
uint8_t * packet = hci_stack->hci_packet_buffer;
// skip checks in loopback mode
if (!hci_stack->loopback_mode){
hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet); // same for ACL and SCO
// check for free places on Bluetooth module
if (!hci_can_send_prepared_sco_packet_now()) {
log_error("hci_send_sco_packet_buffer called but no free SCO buffers on controller");
hci_release_packet_buffer();
hci_emit_transport_packet_sent();
return BTSTACK_ACL_BUFFERS_FULL;
}
// track send packet in connection struct
hci_connection_t *connection = hci_connection_for_handle( con_handle);
if (!connection) {
log_error("hci_send_sco_packet_buffer called but no connection for handle 0x%04x", con_handle);
hci_release_packet_buffer();
hci_emit_transport_packet_sent();
return 0;
}
if (hci_stack->synchronous_flow_control_enabled){
connection->num_packets_sent++;
} else {
uint16_t sco_payload_len = size - 3;
connection->num_sco_bytes_sent += sco_payload_len;
}
}
hci_dump_packet( HCI_SCO_DATA_PACKET, 0, packet, size);
int err = hci_stack->hci_transport->send_packet(HCI_SCO_DATA_PACKET, packet, size);
if (hci_transport_synchronous()){
hci_release_packet_buffer();
hci_emit_transport_packet_sent();
}
return err;
}
#endif
static void acl_handler(uint8_t *packet, int size){
// log_info("acl_handler: size %u", size);
// get info
hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
hci_connection_t *conn = hci_connection_for_handle(con_handle);
uint8_t acl_flags = READ_ACL_FLAGS(packet);
uint16_t acl_length = READ_ACL_LENGTH(packet);
// ignore non-registered handle
if (!conn){
log_error( "hci.c: acl_handler called with non-registered handle %u!" , con_handle);
return;
}
// assert packet is complete
if (acl_length + 4 != size){
log_error("hci.c: acl_handler called with ACL packet of wrong size %d, expected %u => dropping packet", size, acl_length + 4);
return;
}
#ifdef ENABLE_CLASSIC
// update idle timestamp
hci_connection_timestamp(conn);
#endif
#ifdef ENABLE_HCI_CONTROLLER_TO_HOST_FLOW_CONTROL
hci_stack->host_completed_packets = 1;
conn->num_packets_completed++;
#endif
// handle different packet types
switch (acl_flags & 0x03) {
case 0x01: // continuation fragment
// sanity checks
if (conn->acl_recombination_pos == 0) {
log_error( "ACL Cont Fragment but no first fragment for handle 0x%02x", con_handle);
return;
}
if (conn->acl_recombination_pos + acl_length > 4 + HCI_ACL_BUFFER_SIZE){
log_error( "ACL Cont Fragment to large: combined packet %u > buffer size %u for handle 0x%02x",
conn->acl_recombination_pos + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
conn->acl_recombination_pos = 0;
return;
}
// append fragment payload (header already stored)
memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE + conn->acl_recombination_pos], &packet[4], acl_length );
conn->acl_recombination_pos += acl_length;
// log_error( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u", acl_length,
// conn->acl_recombination_pos, conn->acl_recombination_length);
// forward complete L2CAP packet if complete.
if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
hci_emit_acl_packet(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], conn->acl_recombination_pos);
// reset recombination buffer
conn->acl_recombination_length = 0;
conn->acl_recombination_pos = 0;
}
break;
case 0x02: { // first fragment
// sanity check
if (conn->acl_recombination_pos) {
log_error( "ACL First Fragment but data in buffer for handle 0x%02x, dropping stale fragments", con_handle);
conn->acl_recombination_pos = 0;
}
// peek into L2CAP packet!
uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
// log_info( "ACL First Fragment: acl_len %u, l2cap_len %u", acl_length, l2cap_length);
// compare fragment size to L2CAP packet size
if (acl_length >= l2cap_length + 4){
// forward fragment as L2CAP packet
hci_emit_acl_packet(packet, acl_length + 4);
} else {
if (acl_length > HCI_ACL_BUFFER_SIZE){
log_error( "ACL First Fragment to large: fragment %u > buffer size %u for handle 0x%02x",
4 + acl_length, 4 + HCI_ACL_BUFFER_SIZE, con_handle);
return;
}
// store first fragment and tweak acl length for complete package
memcpy(&conn->acl_recombination_buffer[HCI_INCOMING_PRE_BUFFER_SIZE], packet, acl_length + 4);
conn->acl_recombination_pos = acl_length + 4;
conn->acl_recombination_length = l2cap_length;
little_endian_store_16(conn->acl_recombination_buffer, HCI_INCOMING_PRE_BUFFER_SIZE + 2, l2cap_length +4);
}
break;
}
default:
log_error( "hci.c: acl_handler called with invalid packet boundary flags %u", acl_flags & 0x03);
return;
}
// execute main loop
hci_run();
}
static void hci_shutdown_connection(hci_connection_t *conn){
log_info("Connection closed: handle 0x%x, %s", conn->con_handle, bd_addr_to_str(conn->address));
#ifdef ENABLE_CLASSIC
#ifdef ENABLE_SCO_OVER_HCI
int addr_type = conn->address_type;
#endif
#endif
btstack_run_loop_remove_timer(&conn->timeout);
btstack_linked_list_remove(&hci_stack->connections, (btstack_linked_item_t *) conn);
btstack_memory_hci_connection_free( conn );
// now it's gone
hci_emit_nr_connections_changed();
#ifdef ENABLE_CLASSIC
#ifdef ENABLE_SCO_OVER_HCI
// update SCO
if (addr_type == BD_ADDR_TYPE_SCO && hci_stack->hci_transport && hci_stack->hci_transport->set_sco_config){
hci_stack->hci_transport->set_sco_config(hci_stack->sco_voice_setting_active, hci_number_sco_connections());
}
#endif
#endif
}
#ifdef ENABLE_CLASSIC
static const uint16_t packet_type_sizes[] = {
0, HCI_ACL_2DH1_SIZE, HCI_ACL_3DH1_SIZE, HCI_ACL_DM1_SIZE,
HCI_ACL_DH1_SIZE, 0, 0, 0,
HCI_ACL_2DH3_SIZE, HCI_ACL_3DH3_SIZE, HCI_ACL_DM3_SIZE, HCI_ACL_DH3_SIZE,
HCI_ACL_2DH5_SIZE, HCI_ACL_3DH5_SIZE, HCI_ACL_DM5_SIZE, HCI_ACL_DH5_SIZE
};
static const uint8_t packet_type_feature_requirement_bit[] = {
0, // 3 slot packets
1, // 5 slot packets
25, // EDR 2 mpbs
26, // EDR 3 mbps
39, // 3 slot EDR packts
40, // 5 slot EDR packet
};
static const uint16_t packet_type_feature_packet_mask[] = {
0x0f00, // 3 slot packets
0xf000, // 5 slot packets
0x1102, // EDR 2 mpbs
0x2204, // EDR 3 mbps
0x0300, // 3 slot EDR packts
0x3000, // 5 slot EDR packet
};
static uint16_t hci_acl_packet_types_for_buffer_size_and_local_features(uint16_t buffer_size, uint8_t * local_supported_features){
// enable packet types based on size
uint16_t packet_types = 0;
unsigned int i;
for (i=0;i<16;i++){
if (packet_type_sizes[i] == 0) continue;
if (packet_type_sizes[i] <= buffer_size){
packet_types |= 1 << i;
}
}
// disable packet types due to missing local supported features
for (i=0;i<sizeof(packet_type_feature_requirement_bit);i++){
unsigned int bit_idx = packet_type_feature_requirement_bit[i];
int feature_set = (local_supported_features[bit_idx >> 3] & (1<<(bit_idx & 7))) != 0;
if (feature_set) continue;
log_info("Features bit %02u is not set, removing packet types 0x%04x", bit_idx, packet_type_feature_packet_mask[i]);
packet_types &= ~packet_type_feature_packet_mask[i];
}
// flip bits for "may not be used"
packet_types ^= 0x3306;
return packet_types;
}
uint16_t hci_usable_acl_packet_types(void){
return hci_stack->packet_types;
}
#endif