xref: /btstack/src/hci.c (revision 56cf178b4d86dc32c1e368720abe75bf679ac66b)
1 /*
2  * Copyright (C) 2009 by Matthias Ringwald
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  * 3. Neither the name of the copyright holders nor the names of
14  *    contributors may be used to endorse or promote products derived
15  *    from this software without specific prior written permission.
16  *
17  * THIS SOFTWARE IS PROVIDED BY MATTHIAS RINGWALD AND CONTRIBUTORS
18  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
19  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
20  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
21  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
22  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
23  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
24  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
25  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
26  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
27  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  *
30  */
31 
32 /*
33  *  hci.c
34  *
35  *  Created by Matthias Ringwald on 4/29/09.
36  *
37  */
38 
39 #include "hci.h"
40 
41 #include <unistd.h>
42 #include <stdarg.h>
43 #include <string.h>
44 #include <stdio.h>
45 
46 #include "debug.h"
47 #include "hci_dump.h"
48 
49 #include "../include/btstack/hci_cmds.h"
50 #include "../include/btstack/version.h"
51 
52 // temp
53 #include "l2cap.h"
54 
55 #define HCI_CONNECTION_TIMEOUT_MS 10000
56 
57 // the STACK is here
58 static hci_stack_t       hci_stack;
59 
60 /**
61  * get connection for a given handle
62  *
63  * @return connection OR NULL, if not found
64  */
65 hci_connection_t * connection_for_handle(hci_con_handle_t con_handle){
66     linked_item_t *it;
67     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
68         if ( ((hci_connection_t *) it)->con_handle == con_handle){
69             return (hci_connection_t *) it;
70         }
71     }
72     return NULL;
73 }
74 
75 static void hci_connection_timeout_handler(timer_source_t *timer){
76     hci_connection_t * connection = linked_item_get_user(&timer->item);
77     struct timeval tv;
78     gettimeofday(&tv, NULL);
79     if (tv.tv_sec >= connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000) {
80         // connections might be timed out
81         hci_emit_l2cap_check_timeout(connection);
82         run_loop_set_timer(timer, HCI_CONNECTION_TIMEOUT_MS);
83     } else {
84         // next timeout check at
85         timer->timeout.tv_sec = connection->timestamp.tv_sec + HCI_CONNECTION_TIMEOUT_MS/1000;
86     }
87     run_loop_add_timer(timer);
88 }
89 
90 static void hci_connection_timestamp(hci_connection_t *connection){
91     gettimeofday(&connection->timestamp, NULL);
92 }
93 
94 /**
95  * create connection for given address
96  *
97  * @return connection OR NULL, if not found
98  */
99 static hci_connection_t * create_connection_for_addr(bd_addr_t addr){
100     hci_connection_t * conn = malloc( sizeof(hci_connection_t) );
101     if (!conn) return NULL;
102     BD_ADDR_COPY(conn->address, addr);
103     conn->con_handle = 0xffff;
104     conn->flags = 0;
105     linked_item_set_user(&conn->timeout.item, conn);
106     conn->timeout.process = hci_connection_timeout_handler;
107     hci_connection_timestamp(conn);
108     conn->acl_recombination_length = 0;
109     conn->acl_recombination_pos = 0;
110     conn->num_acl_packets_sent = 0;
111     linked_list_add(&hci_stack.connections, (linked_item_t *) conn);
112     return conn;
113 }
114 
115 /**
116  * get connection for given address
117  *
118  * @return connection OR NULL, if not found
119  */
120 static hci_connection_t * connection_for_address(bd_addr_t address){
121     linked_item_t *it;
122     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next){
123         if ( ! BD_ADDR_CMP( ((hci_connection_t *) it)->address, address) ){
124             return (hci_connection_t *) it;
125         }
126     }
127     return NULL;
128 }
129 
130 /**
131  * count connections
132  */
133 static int nr_hci_connections(){
134     int count = 0;
135     linked_item_t *it;
136     for (it = (linked_item_t *) hci_stack.connections; it ; it = it->next, count++);
137     return count;
138 }
139 
140 /**
141  * Dummy handler called by HCI
142  */
143 static void dummy_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
144 }
145 
146 /**
147  * Dummy control handler
148  */
149 static int null_control_function(void *config){
150     return 0;
151 }
152 static const char * null_control_name(void *config){
153     return "Hardware unknown";
154 }
155 static bt_control_t null_control = {
156     null_control_function,
157     null_control_function,
158     null_control_function,
159     null_control_name
160 };
161 
162 
163 int hci_send_acl_packet(uint8_t *packet, int size){
164 
165     // update idle timestamp
166     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
167     hci_connection_t *connection = connection_for_handle( con_handle);
168     if (!connection) return 0;
169     hci_connection_timestamp(connection);
170 
171     // count packet
172     connection->num_acl_packets_sent++;
173     // log_dbg("hci_send_acl_packet - handle %u, sent %u\n", connection->con_handle, connection->num_acl_packets_sent);
174 
175     // send packet
176     return hci_stack.hci_transport->send_acl_packet(packet, size);
177 }
178 
179 static void acl_handler(uint8_t *packet, int size){
180 
181     // get info
182     hci_con_handle_t con_handle = READ_ACL_CONNECTION_HANDLE(packet);
183     hci_connection_t *conn      = connection_for_handle(con_handle);
184     uint8_t  acl_flags          = READ_ACL_FLAGS(packet);
185     uint16_t acl_length         = READ_ACL_LENGTH(packet);
186 
187     // ignore non-registered handle
188     if (!conn){
189         log_err( "hci.c: acl_handler called with non-registered handle %u!\n" , con_handle);
190         return;
191     }
192 
193     // update idle timestamp
194     hci_connection_timestamp(conn);
195 
196     // handle different packet types
197     switch (acl_flags & 0x03) {
198 
199         case 0x01: // continuation fragment
200 
201             // sanity check
202             if (conn->acl_recombination_pos == 0) {
203                 log_err( "ACL Cont Fragment but no first fragment for handle 0x%02x\n", con_handle);
204                 return;
205             }
206 
207             // append fragment payload (header already stored)
208             memcpy(&conn->acl_recombination_buffer[conn->acl_recombination_pos], &packet[4], acl_length );
209             conn->acl_recombination_pos += acl_length;
210 
211             // log_err( "ACL Cont Fragment: acl_len %u, combined_len %u, l2cap_len %u\n",
212             //        acl_length, connection->acl_recombination_pos, connection->acl_recombination_length);
213 
214             // forward complete L2CAP packet if complete.
215             if (conn->acl_recombination_pos >= conn->acl_recombination_length + 4 + 4){ // pos already incl. ACL header
216 
217                 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, conn->acl_recombination_buffer, conn->acl_recombination_pos);
218                 // reset recombination buffer
219                 conn->acl_recombination_length = 0;
220                 conn->acl_recombination_pos = 0;
221             }
222             break;
223 
224         case 0x02: { // first fragment
225 
226             // sanity check
227             if (conn->acl_recombination_pos) {
228                 log_err( "ACL First Fragment but data in buffer for handle 0x%02x\n", con_handle);
229                 return;
230             }
231 
232             // peek into L2CAP packet!
233             uint16_t l2cap_length = READ_L2CAP_LENGTH( packet );
234 
235             // compare fragment size to L2CAP packet size
236             if (acl_length >= l2cap_length + 4){
237 
238                 // forward fragment as L2CAP packet
239                 hci_stack.packet_handler(HCI_ACL_DATA_PACKET, packet, acl_length + 4);
240 
241             } else {
242                 // store first fragment and tweak acl length for complete package
243                 memcpy(conn->acl_recombination_buffer, packet, acl_length + 4);
244                 conn->acl_recombination_pos    = acl_length + 4;
245                 conn->acl_recombination_length = l2cap_length;
246                 bt_store_16(conn->acl_recombination_buffer, 2, acl_length +4);
247                 // log_err( "ACL First Fragment: acl_len %u, l2cap_len %u\n", acl_length, l2cap_length);
248             }
249             break;
250 
251         }
252         default:
253             log_err( "hci.c: acl_handler called with invalid packet boundary flags %u\n", acl_flags & 0x03);
254             return;
255     }
256 
257     // execute main loop
258     hci_run();
259 }
260 
261 static void event_handler(uint8_t *packet, int size){
262     bd_addr_t addr;
263     hci_con_handle_t handle;
264     hci_connection_t * conn;
265     int i;
266 
267     // get num_cmd_packets
268     if (packet[0] == HCI_EVENT_COMMAND_COMPLETE || packet[0] == HCI_EVENT_COMMAND_STATUS){
269         // Get Num_HCI_Command_Packets
270         hci_stack.num_cmd_packets = packet[2];
271     }
272 
273     switch (packet[0]) {
274 
275         case HCI_EVENT_COMMAND_COMPLETE:
276             if (COMMAND_COMPLETE_EVENT(packet, hci_read_buffer_size)){
277                 // from offset 5
278                 // status
279                 hci_stack.acl_data_packet_length = READ_BT_16(packet, 6);
280                 // ignore: SCO data packet len (8)
281                 hci_stack.total_num_acl_packets  = packet[9];
282                 // ignore: total num SCO packets
283                 if (hci_stack.state == HCI_STATE_INITIALIZING){
284                     log_dbg("hci_read_buffer_size: size %u, count %u\n", hci_stack.acl_data_packet_length, hci_stack.total_num_acl_packets);
285                 }
286             }
287             break;
288 
289         case HCI_EVENT_NUMBER_OF_COMPLETED_PACKETS:
290             for (i=0; i<packet[2];i++){
291                 handle = READ_BT_16(packet, 3 + 2*i);
292                 uint16_t num_packets = READ_BT_16(packet, 3 + packet[2]*2 + 2*i);
293                 conn = connection_for_handle(handle);
294                 if (!conn){
295                     log_err("hci_number_completed_packet lists unused con handle %u\n", handle);
296                     continue;
297                 }
298                 conn->num_acl_packets_sent -= num_packets;
299                 // log_dbg("hci_number_completed_packet %u processed for handle %u, outstanding %u\n", num_packets, handle, conn->num_acl_packets_sent);
300             }
301             break;
302 
303         case HCI_EVENT_CONNECTION_REQUEST:
304             bt_flip_addr(addr, &packet[2]);
305             // TODO: eval COD 8-10
306             uint8_t link_type = packet[11];
307             log_dbg("Connection_incoming: "); print_bd_addr(addr); log_dbg(", type %u\n", link_type);
308             if (link_type == 1) { // ACL
309                 conn = connection_for_address(addr);
310                 if (!conn) {
311                     conn = create_connection_for_addr(addr);
312                 }
313                 // TODO: check for malloc failure
314                 conn->state = ACCEPTED_CONNECTION_REQUEST;
315                 hci_send_cmd(&hci_accept_connection_request, addr, 1);
316             } else {
317                 // TODO: decline request
318             }
319             break;
320 
321         case HCI_EVENT_CONNECTION_COMPLETE:
322             // Connection management
323             bt_flip_addr(addr, &packet[5]);
324             log_dbg("Connection_complete (status=%u)", packet[2]); print_bd_addr(addr); log_dbg("\n");
325             conn = connection_for_address(addr);
326             if (conn) {
327                 if (!packet[2]){
328                     conn->state = OPEN;
329                     conn->con_handle = READ_BT_16(packet, 3);
330                     conn->flags = 0;
331 
332                     gettimeofday(&conn->timestamp, NULL);
333                     run_loop_set_timer(&conn->timeout, HCI_CONNECTION_TIMEOUT_MS);
334                     run_loop_add_timer(&conn->timeout);
335 
336                     log_dbg("New connection: handle %u, ", conn->con_handle);
337                     print_bd_addr( conn->address );
338                     log_dbg("\n");
339 
340                     hci_emit_nr_connections_changed();
341                 } else {
342                     // connection failed, remove entry
343                     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
344                     free( conn );
345                 }
346             }
347             break;
348 
349         case HCI_EVENT_DISCONNECTION_COMPLETE:
350             if (!packet[2]){
351                 handle = READ_BT_16(packet, 3);
352                 hci_connection_t * conn = connection_for_handle(handle);
353                 if (conn) {
354                     log_dbg("Connection closed: handle %u, ", conn->con_handle);
355                     print_bd_addr( conn->address );
356                     log_dbg("\n");
357                     run_loop_remove_timer(&conn->timeout);
358                     linked_list_remove(&hci_stack.connections, (linked_item_t *) conn);
359                     free( conn );
360                     hci_emit_nr_connections_changed();
361                 }
362             }
363             break;
364 
365         default:
366             break;
367     }
368 
369     // handle BT initialization
370     if (hci_stack.state == HCI_STATE_INITIALIZING){
371         // handle H4 synchronization loss on restart
372         // if (hci_stack.substate == 1 && packet[0] == HCI_EVENT_HARDWARE_ERROR){
373         //    hci_stack.substate = 0;
374         // }
375         // handle normal init sequence
376         if (hci_stack.substate % 2){
377             // odd: waiting for event
378             if (packet[0] == HCI_EVENT_COMMAND_COMPLETE){
379                 hci_stack.substate++;
380             }
381         }
382     }
383 
384     hci_stack.packet_handler(HCI_EVENT_PACKET, packet, size);
385 
386 	// execute main loop
387 	hci_run();
388 }
389 
390 void packet_handler(uint8_t packet_type, uint8_t *packet, uint16_t size){
391     switch (packet_type) {
392         case HCI_EVENT_PACKET:
393             event_handler(packet, size);
394             break;
395         case HCI_ACL_DATA_PACKET:
396             acl_handler(packet, size);
397             break;
398         default:
399             break;
400     }
401 }
402 
403 /** Register HCI packet handlers */
404 void hci_register_packet_handler(void (*handler)(uint8_t packet_type, uint8_t *packet, uint16_t size)){
405     hci_stack.packet_handler = handler;
406 }
407 
408 void hci_init(hci_transport_t *transport, void *config, bt_control_t *control){
409 
410     // reference to use transport layer implementation
411     hci_stack.hci_transport = transport;
412 
413     // references to used control implementation
414     if (control) {
415         hci_stack.control = control;
416     } else {
417         hci_stack.control = &null_control;
418     }
419 
420     // reference to used config
421     hci_stack.config = config;
422 
423     // no connections yet
424     hci_stack.connections = NULL;
425 
426     // empty cmd buffer
427     hci_stack.hci_cmd_buffer = malloc(3+255);
428 
429     // higher level handler
430     hci_stack.packet_handler = dummy_handler;
431 
432     // register packet handlers with transport
433     transport->register_packet_handler(&packet_handler);
434 }
435 
436 int hci_power_control(HCI_POWER_MODE power_mode){
437     if (power_mode == HCI_POWER_ON && hci_stack.state == HCI_STATE_OFF) {
438 
439         // power on
440         int err = hci_stack.control->on(hci_stack.config);
441         if (err){
442             log_err( "POWER_ON failed\n");
443             hci_emit_hci_open_failed();
444             return err;
445         }
446 
447         // open low-level device
448         err = hci_stack.hci_transport->open(hci_stack.config);
449         if (err){
450             log_err( "HCI_INIT failed, turning Bluetooth off again\n");
451             hci_stack.control->off(hci_stack.config);
452             hci_emit_hci_open_failed();
453             return err;
454         }
455 
456         // set up state machine
457         hci_stack.num_cmd_packets = 1; // assume that one cmd can be sent
458         hci_stack.state = HCI_STATE_INITIALIZING;
459         hci_stack.substate = 0;
460 
461     } else if (power_mode == HCI_POWER_OFF && hci_stack.state == HCI_STATE_WORKING){
462 
463         // close low-level device
464         hci_stack.hci_transport->close(hci_stack.config);
465 
466         // power off
467         hci_stack.control->off(hci_stack.config);
468 
469         // we're off now
470         hci_stack.state = HCI_STATE_OFF;
471     }
472 
473     // create internal event
474 	hci_emit_state();
475 
476 	// trigger next/first action
477 	hci_run();
478 
479     return 0;
480 }
481 
482 void hci_run(){
483     switch (hci_stack.state){
484         case HCI_STATE_INITIALIZING:
485             if (hci_stack.substate % 2) {
486                 // odd: waiting for command completion
487                 return;
488             }
489             if (hci_stack.num_cmd_packets == 0) {
490                 // cannot send command yet
491                 return;
492             }
493             switch (hci_stack.substate/2){
494                 case 0:
495                     hci_send_cmd(&hci_reset);
496                     break;
497 				case 1:
498 					hci_send_cmd(&hci_read_bd_addr);
499 					break;
500 				case 2:
501 					hci_send_cmd(&hci_read_buffer_size);
502 					break;
503                 case 3:
504                     // ca. 15 sec
505                     hci_send_cmd(&hci_write_page_timeout, 0x6000);
506                     break;
507 				case 4:
508 					hci_send_cmd(&hci_write_scan_enable, 3); // 3 inq scan + page scan
509 					break;
510                 case 5:
511                     // done.
512                     hci_stack.state = HCI_STATE_WORKING;
513                     hci_emit_state();
514                     break;
515                 default:
516                     break;
517             }
518             hci_stack.substate++;
519             break;
520         default:
521             break;
522     }
523 }
524 
525 int hci_send_cmd_packet(uint8_t *packet, int size){
526     bd_addr_t addr;
527     hci_connection_t * conn;
528     // house-keeping
529 
530     // create_connection?
531     if (IS_COMMAND(packet, hci_create_connection)){
532         bt_flip_addr(addr, &packet[3]);
533         log_dbg("Create_connection to "); print_bd_addr(addr); log_dbg("\n");
534         conn = connection_for_address(addr);
535         if (conn) {
536             // if connection exists
537             if (conn->state == OPEN) {
538                 // if OPEN, emit connection complete command
539                 hci_emit_connection_complete(conn);
540             }
541             //    otherwise, just ignore
542             return 0; // don't sent packet to controller
543 
544         } else{
545             conn = create_connection_for_addr(addr);
546             if (conn){
547                 //    create connection struct and register, state = SENT_CREATE_CONNECTION
548                 conn->state = SENT_CREATE_CONNECTION;
549             }
550         }
551     }
552 
553     // accept connection
554 
555     // reject connection
556 
557     // close_connection?
558       // set state = SENT_DISCONNECT
559 
560     hci_stack.num_cmd_packets--;
561     return hci_stack.hci_transport->send_cmd_packet(packet, size);
562 }
563 
564 /**
565  * pre: numcmds >= 0 - it's allowed to send a command to the controller
566  */
567 int hci_send_cmd(hci_cmd_t *cmd, ...){
568     va_list argptr;
569     va_start(argptr, cmd);
570     uint8_t * hci_cmd_buffer = hci_stack.hci_cmd_buffer;
571     uint16_t size = hci_create_cmd_internal(hci_stack.hci_cmd_buffer, cmd, argptr);
572     va_end(argptr);
573     return hci_send_cmd_packet(hci_cmd_buffer, size);
574 }
575 
576 // Create various non-HCI events.
577 // TODO: generalize, use table similar to hci_create_command
578 
579 void hci_emit_state(){
580     uint8_t len = 3;
581     uint8_t event[len];
582     event[0] = BTSTACK_EVENT_STATE;
583     event[1] = len - 3;
584     event[2] = hci_stack.state;
585     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
586     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
587 }
588 
589 void hci_emit_connection_complete(hci_connection_t *conn){
590     uint8_t len = 13;
591     uint8_t event[len];
592     event[0] = HCI_EVENT_CONNECTION_COMPLETE;
593     event[1] = len - 3;
594     event[2] = 0; // status = OK
595     bt_store_16(event, 3, conn->con_handle);
596     bt_flip_addr(&event[5], conn->address);
597     event[11] = 1; // ACL connection
598     event[12] = 0; // encryption disabled
599     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
600     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
601 }
602 
603 void hci_emit_l2cap_check_timeout(hci_connection_t *conn){
604     uint8_t len = 4;
605     uint8_t event[len];
606     event[0] = L2CAP_EVENT_TIMEOUT_CHECK;
607     event[1] = len - 2;
608     bt_store_16(event, 2, conn->con_handle);
609     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
610     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
611 }
612 
613 void hci_emit_nr_connections_changed(){
614     uint8_t len = 3;
615     uint8_t event[len];
616     event[0] = BTSTACK_EVENT_NR_CONNECTIONS_CHANGED;
617     event[1] = len - 2;
618     event[2] = nr_hci_connections();
619     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
620     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
621 }
622 
623 void hci_emit_hci_open_failed(){
624     uint8_t len = 2;
625     uint8_t event[len];
626     event[0] = BTSTACK_EVENT_POWERON_FAILED;
627     event[1] = len - 2;
628     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
629     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
630 }
631 
632 
633 void hci_emit_btstack_version() {
634     uint8_t len = 6;
635     uint8_t event[len];
636     event[0] = BTSTACK_EVENT_VERSION;
637     event[1] = len - 2;
638     event[len++] = BTSTACK_MAJOR;
639     event[len++] = BTSTACK_MINOR;
640     bt_store_16(event, len, BTSTACK_REVISION);
641     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
642     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
643 }
644 
645 void hci_emit_system_bluetooth_enabled(uint8_t enabled){
646     uint8_t len = 3;
647     uint8_t event[len];
648     event[0] = BTSTACK_EVENT_SYSTEM_BLUETOOTH_ENABLED;
649     event[1] = len - 2;
650     event[2] = enabled;
651     hci_dump_packet( HCI_EVENT_PACKET, 0, event, len);
652     hci_stack.packet_handler(HCI_EVENT_PACKET, event, len);
653 }
654