xref: /btstack/src/l2cap.h (revision d84e866fb87b02372d5534d4932cd5fa66d5315b)
1 /*
2  * Copyright (C) 2014 BlueKitchen GmbH
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  * 4. Any redistribution, use, or modification is done solely for
17  *    personal benefit and not for any commercial purpose or for
18  *    monetary gain.
19  *
20  * THIS SOFTWARE IS PROVIDED BY BLUEKITCHEN GMBH AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
22  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
23  * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL MATTHIAS
24  * RINGWALD OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
25  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
26  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
27  * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
28  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
29  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF
30  * THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31  * SUCH DAMAGE.
32  *
33  * Please inquire about commercial licensing options at
34  * [email protected]
35  *
36  */
37 
38 /*
39  *  l2cap.h
40  *
41  *  Logical Link Control and Adaption Protocol (L2CAP)
42  *
43  *  Created by Matthias Ringwald on 5/16/09.
44  */
45 
46 #ifndef __L2CAP_H
47 #define __L2CAP_H
48 
49 #include "hci.h"
50 #include "l2cap_signaling.h"
51 #include "btstack_util.h"
52 #include "bluetooth.h"
53 
54 #if defined __cplusplus
55 extern "C" {
56 #endif
57 
58 // check L2CAP MTU
59 #ifdef ENABLE_CLASSIC
60 #if (L2CAP_HEADER_SIZE + L2CAP_MINIMAL_MTU) > HCI_ACL_PAYLOAD_SIZE
61 #error "HCI_ACL_PAYLOAD_SIZE too small for minimal L2CAP MTU of 48 bytes"
62 #endif
63 #endif
64 #ifdef ENABLE_BLE
65 #if (L2CAP_HEADER_SIZE + L2CAP_LE_DEFAULT_MTU) > HCI_ACL_PAYLOAD_SIZE
66 #error "HCI_ACL_PAYLOAD_SIZE too small for minimal L2CAP LE MTU of 23 bytes"
67 #endif
68 #endif
69 
70 #define L2CAP_LE_AUTOMATIC_CREDITS 0xffff
71 
72 // private structs
73 typedef enum {
74     L2CAP_STATE_CLOSED = 1,           // no baseband
75     L2CAP_STATE_WILL_SEND_CREATE_CONNECTION,
76     L2CAP_STATE_WAIT_CONNECTION_COMPLETE,
77     L2CAP_STATE_WAIT_REMOTE_SUPPORTED_FEATURES,
78     L2CAP_STATE_WAIT_INCOMING_SECURITY_LEVEL_UPDATE,
79     L2CAP_STATE_WAIT_OUTGOING_SECURITY_LEVEL_UPDATE,
80     L2CAP_STATE_WAIT_INCOMING_EXTENDED_FEATURES,    // only for Enhanced Retransmission Mode
81     L2CAP_STATE_WAIT_OUTGOING_EXTENDED_FEATURES,    // only for Enhanced Retransmission Mode
82     L2CAP_STATE_WAIT_CLIENT_ACCEPT_OR_REJECT,
83     L2CAP_STATE_WAIT_CONNECT_RSP, // from peer
84     L2CAP_STATE_CONFIG,
85     L2CAP_STATE_OPEN,
86     L2CAP_STATE_WAIT_DISCONNECT,  // from application
87     L2CAP_STATE_WILL_SEND_CONNECTION_REQUEST,
88     L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_INSUFFICIENT_SECURITY,
89     L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_DECLINE,
90     L2CAP_STATE_WILL_SEND_CONNECTION_RESPONSE_ACCEPT,
91     L2CAP_STATE_WILL_SEND_DISCONNECT_REQUEST,
92     L2CAP_STATE_WILL_SEND_DISCONNECT_RESPONSE,
93     L2CAP_STATE_WILL_SEND_LE_CONNECTION_REQUEST,
94     L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_DECLINE,
95     L2CAP_STATE_WILL_SEND_LE_CONNECTION_RESPONSE_ACCEPT,
96     L2CAP_STATE_WAIT_LE_CONNECTION_RESPONSE,
97     L2CAP_STATE_INVALID,
98 } L2CAP_STATE;
99 
100 typedef enum {
101     L2CAP_CHANNEL_STATE_VAR_NONE                   = 0,
102     L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_REQ          = 1 << 0,
103     L2CAP_CHANNEL_STATE_VAR_RCVD_CONF_RSP          = 1 << 1,
104     L2CAP_CHANNEL_STATE_VAR_SEND_CONF_REQ          = 1 << 2,
105     L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP          = 1 << 3,
106     L2CAP_CHANNEL_STATE_VAR_SENT_CONF_REQ          = 1 << 4,
107     L2CAP_CHANNEL_STATE_VAR_SENT_CONF_RSP          = 1 << 5,
108     L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_MTU      = 1 << 6,   // in CONF RSP, add MTU field
109     L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_CONT     = 1 << 7,   // in CONF RSP, set CONTINUE flag
110     L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_INVALID  = 1 << 8,   // in CONF RSP, send UNKNOWN OPTIONS
111     L2CAP_CHANNEL_STATE_VAR_SEND_CONF_RSP_REJECTED = 1 << 9,   // in CONF RSP, send Unacceptable Parameters (ERTM)
112     L2CAP_CHANNEL_STATE_VAR_BASIC_FALLBACK_TRIED   = 1 << 10,  // set when ERTM was requested but we want only Basic mode (ERM)
113     L2CAP_CHANNEL_STATE_VAR_SEND_CMD_REJ_UNKNOWN   = 1 << 11,  // send CMD_REJ with reason unknown
114     L2CAP_CHANNEL_STATE_VAR_SEND_CONN_RESP_PEND    = 1 << 12,  // send Connection Respond with pending
115     L2CAP_CHANNEL_STATE_VAR_INCOMING               = 1 << 15,  // channel is incoming
116 } L2CAP_CHANNEL_STATE_VAR;
117 
118 typedef struct {
119     uint8_t tx_seq;
120     uint16_t pos;
121     uint16_t sdu_length;
122 } l2cap_ertm_rx_packet_state_t;
123 
124 typedef struct {
125     uint8_t tx_seq;
126 } l2cap_ertm_tx_packet_state_t;
127 
128 
129 // info regarding an actual connection
130 typedef struct {
131     // linked list - assert: first field
132     btstack_linked_item_t    item;
133 
134     // packet handler
135     btstack_packet_handler_t packet_handler;
136 
137     // timer
138     btstack_timer_source_t rtx; // also used for ertx
139 
140     L2CAP_STATE state;
141     L2CAP_CHANNEL_STATE_VAR state_var;
142 
143     // info
144     hci_con_handle_t con_handle;
145 
146     bd_addr_t address;
147     bd_addr_type_t address_type;
148 
149     uint8_t   remote_sig_id;    // used by other side, needed for delayed response
150     uint8_t   local_sig_id;     // own signaling identifier
151 
152     uint16_t  local_cid;
153     uint16_t  remote_cid;
154 
155     uint16_t  local_mtu;
156     uint16_t  remote_mtu;
157 
158     uint16_t  flush_timeout;    // default 0xffff
159 
160     uint16_t  psm;
161 
162     gap_security_level_t required_security_level;
163 
164     uint8_t   reason; // used in decline internal
165     uint8_t   waiting_for_can_send_now;
166 
167     // LE Data Channels
168 
169     // incoming SDU
170     uint8_t * receive_sdu_buffer;
171     uint16_t  receive_sdu_len;
172     uint16_t  receive_sdu_pos;
173 
174     // outgoing SDU
175     uint8_t  * send_sdu_buffer;
176     uint16_t   send_sdu_len;
177     uint16_t   send_sdu_pos;
178 
179     // max PDU size
180     uint16_t  remote_mps;
181 
182     // credits for outgoing traffic
183     uint16_t credits_outgoing;
184 
185     // number of packets remote will be granted
186     uint16_t new_credits_incoming;
187 
188     // credits for incoming traffic
189     uint16_t credits_incoming;
190 
191     // automatic credits incoming
192     uint16_t automatic_credits;
193 
194 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
195     // l2cap channel mode: basic or enhanced retransmission mode
196     l2cap_channel_mode_t mode;
197 
198     // local/remote config options
199     uint16_t local_retransmission_timeout_ms;
200     uint16_t local_monitor_timeout_ms;
201 
202     uint16_t remote_retransmission_timeout_ms;
203     uint16_t remote_monitor_timeout_ms;
204 
205     uint8_t remote_tx_window_size;
206 
207     uint8_t local_max_transmit;
208     uint8_t remote_max_transmit;
209 
210     // if ertm is not mandatory, allow fallback to L2CAP Basic Mode - flag
211     uint8_t ertm_mandatory;
212 
213     // receiver: send RR frame - flag
214     uint8_t send_supervisor_frame_receiver_ready;
215 
216     // sender: next seq nr used for sending
217     uint8_t next_tx_seq;
218 
219     // receiver: value of tx_seq in next expected i-frame
220     uint8_t expected_tx_seq;
221 
222     // receiver: request transmiissoin with tx_seq = req_seq and ack up to and including req_seq
223     uint8_t req_seq;
224 
225     // max um out-of-order packets // tx_window
226     uint8_t num_rx_buffers;
227 
228     // max num of unacknowledged outgoing packets
229     uint8_t num_tx_buffers;
230 
231     // re-assembly state
232     l2cap_ertm_rx_packet_state_t * rx_packets_state;
233 
234     // retransmission state
235     l2cap_ertm_tx_packet_state_t * tx_packets_state;
236 
237     // data, each of size local_mtu
238     uint8_t * rx_packets_data;
239 
240     // data, each of size local_mtu
241     uint8_t * tx_packets_data;
242 #endif
243 } l2cap_channel_t;
244 
245 // info regarding potential connections
246 typedef struct {
247     // linked list - assert: first field
248     btstack_linked_item_t    item;
249 
250     // service id
251     uint16_t  psm;
252 
253     // incoming MTU
254     uint16_t mtu;
255 
256     // internal connection
257     btstack_packet_handler_t packet_handler;
258 
259     // required security level
260     gap_security_level_t required_security_level;
261 
262 } l2cap_service_t;
263 
264 
265 typedef struct l2cap_signaling_response {
266     hci_con_handle_t handle;
267     uint8_t  sig_id;
268     uint8_t  code;
269     uint16_t cid;  // source cid for CONNECTION REQUEST
270     uint16_t data; // infoType for INFORMATION REQUEST, result for CONNECTION REQUEST and COMMAND UNKNOWN
271 } l2cap_signaling_response_t;
272 
273 
274 void l2cap_register_fixed_channel(btstack_packet_handler_t packet_handler, uint16_t channel_id);
275 int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id);
276 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id);
277 int  l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len);
278 int  l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len);
279 
280 // PTS Testing
281 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len);
282 void l2cap_require_security_level_2_for_outgoing_sdp(void);
283 
284 // Used by RFCOMM - similar to l2cap_can-send_packet_now but does not check if outgoing buffer is reserved
285 int  l2cap_can_send_prepared_packet_now(uint16_t local_cid);
286 
287 /* API_START */
288 
289 /**
290  * @brief Set up L2CAP and register L2CAP with HCI layer.
291  */
292 void l2cap_init(void);
293 
294 /**
295  * @brief Registers packet handler for LE Connection Parameter Update events
296  */
297 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size));
298 
299 /**
300  * @brief Get max MTU for Classic connections based on btstack configuration
301  */
302 uint16_t l2cap_max_mtu(void);
303 
304 /**
305  * @brief Get max MTU for LE connections based on btstack configuration
306  */
307 uint16_t l2cap_max_le_mtu(void);
308 
309 /**
310  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
311  * @param packet_handler
312  * @param address
313  * @param psm
314  * @param mtu
315  * @param local_cid
316  * @return status
317  */
318 uint8_t l2cap_create_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm, uint16_t mtu, uint16_t * out_local_cid);
319 
320 /**
321  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address using Enhanced Retransmission Mode.
322  *        A new baseband connection will be initiated if necessary.
323  * @param packet_handler
324  * @param address
325  * @param psm
326  * @param ertm_mandatory If not mandatory, the use of ERTM can be decided by the remote
327  * @param max_transmit Number of retransmissions that L2CAP is allowed to try before accepting that a packet and the channel is lost.
328  * @param retransmission_timeout_ms Recommended : 2000 ms (ACL Flush timeout not used)
329  * @param monitor_timeout_ms Recommended: 12000 ms (ACL Flush timeout not used)
330  * @param num_tx_buffers Number of unacknowledged packets stored in buffer
331  * @param num_rx_buffers Number of packets that can be received out of order (-> our tx_window size)
332  * @param buffer to store out-of-order packets and unacknowledged outgoing packets with their tretransmission timers
333  * @param size of buffer
334  * @param local_cid
335  * @return status
336  */
337 uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
338     int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms,
339     uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid);
340 
341 /**
342  * @brief Disconnects L2CAP channel with given identifier.
343  */
344 void l2cap_disconnect(uint16_t local_cid, uint8_t reason);
345 
346 /**
347  * @brief Queries the maximal transfer unit (MTU) for L2CAP channel with given identifier.
348  */
349 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid);
350 
351 /**
352  * @brief Sends L2CAP data packet to the channel with given identifier.
353  */
354 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len);
355 
356 /**
357  * @brief Registers L2CAP service with given PSM and MTU, and assigns a packet handler.
358  */
359 uint8_t l2cap_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level);
360 
361 /**
362  * @brief Unregisters L2CAP service with given PSM.
363  */
364 uint8_t l2cap_unregister_service(uint16_t psm);
365 
366 /**
367  * @brief Accepts incoming L2CAP connection.
368  */
369 void l2cap_accept_connection(uint16_t local_cid);
370 
371 /**
372  * @brief Accepts incoming L2CAP connection for Enhanced Retransmission Mode
373  * @param ertm_mandatory If not mandatory, the use of ERTM can be decided by the remote
374  * @param max_transmit Number of retransmissions that L2CAP is allowed to try before accepting that a packet and the channel is lost. Recommended: 1
375  * @param retransmission_timeout_ms Recommended : 2000 ms (ACL Flush timeout not used)
376  * @param monitor_timeout_ms Recommended: 12000 ms (ACL Flush timeout not used)
377  * @param num_tx_buffers Number of unacknowledged packets stored in buffer
378  * @param num_rx_buffers Number of packets that can be received out of order (-> our tx_window size)
379  * @param buffer to store out-of-order packets and unacknowledged outgoing packets with their tretransmission timers
380  * @param size of buffer
381  * @return status
382  */
383 uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, int ertm_mandatory, uint8_t max_transmit,
384     uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms, uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size);
385 
386 /**
387  * @brief Deny incoming L2CAP connection.
388  */
389 void l2cap_decline_connection(uint16_t local_cid);
390 
391 /**
392  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
393  */
394 int  l2cap_can_send_packet_now(uint16_t local_cid);
395 
396 /**
397  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
398  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
399  *       so packet handler should be ready to handle it
400  * @param local_cid
401  */
402 void l2cap_request_can_send_now_event(uint16_t local_cid);
403 
404 /**
405  * @brief Reserve outgoing buffer
406  */
407 int  l2cap_reserve_packet_buffer(void);
408 
409 /**
410  * @brief Get outgoing buffer and prepare data.
411  */
412 uint8_t *l2cap_get_outgoing_buffer(void);
413 
414 /**
415  * @brief Send L2CAP packet prepared in outgoing buffer to channel
416  */
417 int l2cap_send_prepared(uint16_t local_cid, uint16_t len);
418 
419 /**
420  * @brief Release outgoing buffer (only needed if l2cap_send_prepared is not called)
421  */
422 void l2cap_release_packet_buffer(void);
423 
424 
425 //
426 // LE Connection Oriented Channels feature with the LE Credit Based Flow Control Mode == LE Data Channel
427 //
428 
429 
430 /**
431  * @brief Register L2CAP LE Data Channel service
432  * @note MTU and initial credits are specified in l2cap_le_accept_connection(..) call
433  * @param packet_handler
434  * @param psm
435  * @param security_level
436  */
437 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level);
438 
439 /**
440  * @brief Unregister L2CAP LE Data Channel service
441  * @param psm
442  */
443 
444 uint8_t l2cap_le_unregister_service(uint16_t psm);
445 
446 /*
447  * @brief Accept incoming LE Data Channel connection
448  * @param local_cid             L2CAP LE Data Channel Identifier
449  * @param receive_buffer        buffer used for reassembly of L2CAP LE Information Frames into service data unit (SDU) with given MTU
450  * @param receive_buffer_size   buffer size equals MTU
451  * @param initial_credits       Number of initial credits provided to peer or L2CAP_LE_AUTOMATIC_CREDITS to enable automatic credits
452  */
453 
454 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits);
455 
456 /**
457  * @brief Deny incoming LE Data Channel connection due to resource constraints
458  * @param local_cid             L2CAP LE Data Channel Identifier
459  */
460 
461 uint8_t l2cap_le_decline_connection(uint16_t local_cid);
462 
463 /**
464  * @brief Create LE Data Channel
465  * @param packet_handler        Packet handler for this connection
466  * @param con_handle            ACL-LE HCI Connction Handle
467  * @param psm                   Service PSM to connect to
468  * @param receive_buffer        buffer used for reassembly of L2CAP LE Information Frames into service data unit (SDU) with given MTU
469  * @param receive_buffer_size   buffer size equals MTU
470  * @param initial_credits       Number of initial credits provided to peer or L2CAP_LE_AUTOMATIC_CREDITS to enable automatic credits
471  * @param security_level        Minimum required security level
472  * @param out_local_cid         L2CAP LE Channel Identifier is stored here
473  */
474 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
475     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
476     uint16_t * out_local_cid);
477 
478 /**
479  * @brief Provide credtis for LE Data Channel
480  * @param local_cid             L2CAP LE Data Channel Identifier
481  * @param credits               Number additional credits for peer
482  */
483 uint8_t l2cap_le_provide_credits(uint16_t cid, uint16_t credits);
484 
485 /**
486  * @brief Check if packet can be scheduled for transmission
487  * @param local_cid             L2CAP LE Data Channel Identifier
488  */
489 int l2cap_le_can_send_now(uint16_t cid);
490 
491 /**
492  * @brief Request emission of L2CAP_EVENT_LE_CAN_SEND_NOW as soon as possible
493  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
494  *       so packet handler should be ready to handle it
495  * @param local_cid             L2CAP LE Data Channel Identifier
496  */
497 uint8_t l2cap_le_request_can_send_now_event(uint16_t cid);
498 
499 /**
500  * @brief Send data via LE Data Channel
501  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
502  * @param local_cid             L2CAP LE Data Channel Identifier
503  * @param data                  data to send
504  * @param size                  data size
505  */
506 uint8_t l2cap_le_send_data(uint16_t cid, uint8_t * data, uint16_t size);
507 
508 /**
509  * @brief Disconnect from LE Data Channel
510  * @param local_cid             L2CAP LE Data Channel Identifier
511  */
512 uint8_t l2cap_le_disconnect(uint16_t cid);
513 
514 /* API_END */
515 
516 #if defined __cplusplus
517 }
518 #endif
519 
520 #endif // __L2CAP_H
521