xref: /btstack/src/l2cap.h (revision f0fb4cd727a7cb54eb1a1c2b1dc9efdf67d42fde)
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     uint16_t len;
127 } l2cap_ertm_tx_packet_state_t;
128 
129 
130 // info regarding an actual connection
131 typedef struct {
132     // linked list - assert: first field
133     btstack_linked_item_t    item;
134 
135     // packet handler
136     btstack_packet_handler_t packet_handler;
137 
138     // timer
139     btstack_timer_source_t rtx; // also used for ertx
140 
141     L2CAP_STATE state;
142     L2CAP_CHANNEL_STATE_VAR state_var;
143 
144     // info
145     hci_con_handle_t con_handle;
146 
147     bd_addr_t address;
148     bd_addr_type_t address_type;
149 
150     uint8_t   remote_sig_id;    // used by other side, needed for delayed response
151     uint8_t   local_sig_id;     // own signaling identifier
152 
153     uint16_t  local_cid;
154     uint16_t  remote_cid;
155 
156     uint16_t  local_mtu;
157     uint16_t  remote_mtu;
158 
159     uint16_t  flush_timeout;    // default 0xffff
160 
161     uint16_t  psm;
162 
163     gap_security_level_t required_security_level;
164 
165     uint8_t   reason; // used in decline internal
166     uint8_t   waiting_for_can_send_now;
167 
168     // LE Data Channels
169 
170     // incoming SDU
171     uint8_t * receive_sdu_buffer;
172     uint16_t  receive_sdu_len;
173     uint16_t  receive_sdu_pos;
174 
175     // outgoing SDU
176     uint8_t  * send_sdu_buffer;
177     uint16_t   send_sdu_len;
178     uint16_t   send_sdu_pos;
179 
180     // max PDU size
181     uint16_t  remote_mps;
182 
183     // credits for outgoing traffic
184     uint16_t credits_outgoing;
185 
186     // number of packets remote will be granted
187     uint16_t new_credits_incoming;
188 
189     // credits for incoming traffic
190     uint16_t credits_incoming;
191 
192     // automatic credits incoming
193     uint16_t automatic_credits;
194 
195 #ifdef ENABLE_L2CAP_ENHANCED_RETRANSMISSION_MODE
196     // l2cap channel mode: basic or enhanced retransmission mode
197     l2cap_channel_mode_t mode;
198 
199     // local/remote config options
200     uint16_t local_retransmission_timeout_ms;
201     uint16_t local_monitor_timeout_ms;
202 
203     uint16_t remote_retransmission_timeout_ms;
204     uint16_t remote_monitor_timeout_ms;
205 
206     uint8_t remote_tx_window_size;
207 
208     uint8_t local_max_transmit;
209     uint8_t remote_max_transmit;
210 
211     // if ertm is not mandatory, allow fallback to L2CAP Basic Mode - flag
212     uint8_t ertm_mandatory;
213 
214     // sender: buffer index to store tx packet
215     uint8_t tx_write_index;
216 
217     // sender: buffer index of packet to send next
218     uint8_t tx_read_index;
219 
220     // sender: next seq nr used for sending
221     uint8_t next_tx_seq;
222 
223     // receiver: send RR frame - flag
224     uint8_t send_supervisor_frame_receiver_ready;
225 
226     // receiver: value of tx_seq in next expected i-frame
227     uint8_t expected_tx_seq;
228 
229     // receiver: request transmiissoin with tx_seq = req_seq and ack up to and including req_seq
230     uint8_t req_seq;
231 
232     // max um out-of-order packets // tx_window
233     uint8_t num_rx_buffers;
234 
235     // max num of unacknowledged outgoing packets
236     uint8_t num_tx_buffers;
237 
238     // re-assembly state
239     l2cap_ertm_rx_packet_state_t * rx_packets_state;
240 
241     // retransmission state
242     l2cap_ertm_tx_packet_state_t * tx_packets_state;
243 
244     // data, each of size local_mtu
245     uint8_t * rx_packets_data;
246 
247     // data, each of size local_mtu
248     uint8_t * tx_packets_data;
249 #endif
250 } l2cap_channel_t;
251 
252 // info regarding potential connections
253 typedef struct {
254     // linked list - assert: first field
255     btstack_linked_item_t    item;
256 
257     // service id
258     uint16_t  psm;
259 
260     // incoming MTU
261     uint16_t mtu;
262 
263     // internal connection
264     btstack_packet_handler_t packet_handler;
265 
266     // required security level
267     gap_security_level_t required_security_level;
268 
269 } l2cap_service_t;
270 
271 
272 typedef struct l2cap_signaling_response {
273     hci_con_handle_t handle;
274     uint8_t  sig_id;
275     uint8_t  code;
276     uint16_t cid;  // source cid for CONNECTION REQUEST
277     uint16_t data; // infoType for INFORMATION REQUEST, result for CONNECTION REQUEST and COMMAND UNKNOWN
278 } l2cap_signaling_response_t;
279 
280 
281 void l2cap_register_fixed_channel(btstack_packet_handler_t packet_handler, uint16_t channel_id);
282 int  l2cap_can_send_fixed_channel_packet_now(hci_con_handle_t con_handle, uint16_t channel_id);
283 void l2cap_request_can_send_fix_channel_now_event(hci_con_handle_t con_handle, uint16_t channel_id);
284 int  l2cap_send_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint8_t *data, uint16_t len);
285 int  l2cap_send_prepared_connectionless(hci_con_handle_t con_handle, uint16_t cid, uint16_t len);
286 
287 // PTS Testing
288 int l2cap_send_echo_request(hci_con_handle_t con_handle, uint8_t *data, uint16_t len);
289 void l2cap_require_security_level_2_for_outgoing_sdp(void);
290 
291 // Used by RFCOMM - similar to l2cap_can-send_packet_now but does not check if outgoing buffer is reserved
292 int  l2cap_can_send_prepared_packet_now(uint16_t local_cid);
293 
294 /* API_START */
295 
296 /**
297  * @brief Set up L2CAP and register L2CAP with HCI layer.
298  */
299 void l2cap_init(void);
300 
301 /**
302  * @brief Registers packet handler for LE Connection Parameter Update events
303  */
304 void l2cap_register_packet_handler(void (*handler)(uint8_t packet_type, uint16_t channel, uint8_t *packet, uint16_t size));
305 
306 /**
307  * @brief Get max MTU for Classic connections based on btstack configuration
308  */
309 uint16_t l2cap_max_mtu(void);
310 
311 /**
312  * @brief Get max MTU for LE connections based on btstack configuration
313  */
314 uint16_t l2cap_max_le_mtu(void);
315 
316 /**
317  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address. A new baseband connection will be initiated if necessary.
318  * @param packet_handler
319  * @param address
320  * @param psm
321  * @param mtu
322  * @param local_cid
323  * @return status
324  */
325 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);
326 
327 /**
328  * @brief Creates L2CAP channel to the PSM of a remote device with baseband address using Enhanced Retransmission Mode.
329  *        A new baseband connection will be initiated if necessary.
330  * @param packet_handler
331  * @param address
332  * @param psm
333  * @param ertm_mandatory If not mandatory, the use of ERTM can be decided by the remote
334  * @param max_transmit Number of retransmissions that L2CAP is allowed to try before accepting that a packet and the channel is lost.
335  * @param retransmission_timeout_ms Recommended : 2000 ms (ACL Flush timeout not used)
336  * @param monitor_timeout_ms Recommended: 12000 ms (ACL Flush timeout not used)
337  * @param num_tx_buffers Number of unacknowledged packets stored in buffer
338  * @param num_rx_buffers Number of packets that can be received out of order (-> our tx_window size)
339  * @param buffer to store out-of-order packets and unacknowledged outgoing packets with their tretransmission timers
340  * @param size of buffer
341  * @param local_cid
342  * @return status
343  */
344 uint8_t l2cap_create_ertm_channel(btstack_packet_handler_t packet_handler, bd_addr_t address, uint16_t psm,
345     int ertm_mandatory, uint8_t max_transmit, uint16_t retransmission_timeout_ms, uint16_t monitor_timeout_ms,
346     uint8_t num_tx_buffers, uint8_t num_rx_buffers, uint8_t * buffer, uint32_t size, uint16_t * out_local_cid);
347 
348 /**
349  * @brief Disconnects L2CAP channel with given identifier.
350  */
351 void l2cap_disconnect(uint16_t local_cid, uint8_t reason);
352 
353 /**
354  * @brief Queries the maximal transfer unit (MTU) for L2CAP channel with given identifier.
355  */
356 uint16_t l2cap_get_remote_mtu_for_local_cid(uint16_t local_cid);
357 
358 /**
359  * @brief Sends L2CAP data packet to the channel with given identifier.
360  */
361 int l2cap_send(uint16_t local_cid, uint8_t *data, uint16_t len);
362 
363 /**
364  * @brief Registers L2CAP service with given PSM and MTU, and assigns a packet handler.
365  */
366 uint8_t l2cap_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, uint16_t mtu, gap_security_level_t security_level);
367 
368 /**
369  * @brief Unregisters L2CAP service with given PSM.
370  */
371 uint8_t l2cap_unregister_service(uint16_t psm);
372 
373 /**
374  * @brief Accepts incoming L2CAP connection.
375  */
376 void l2cap_accept_connection(uint16_t local_cid);
377 
378 /**
379  * @brief Accepts incoming L2CAP connection for Enhanced Retransmission Mode
380  * @param ertm_mandatory If not mandatory, the use of ERTM can be decided by the remote
381  * @param max_transmit Number of retransmissions that L2CAP is allowed to try before accepting that a packet and the channel is lost. Recommended: 1
382  * @param retransmission_timeout_ms Recommended : 2000 ms (ACL Flush timeout not used)
383  * @param monitor_timeout_ms Recommended: 12000 ms (ACL Flush timeout not used)
384  * @param num_tx_buffers Number of unacknowledged packets stored in buffer
385  * @param num_rx_buffers Number of packets that can be received out of order (-> our tx_window size)
386  * @param buffer to store out-of-order packets and unacknowledged outgoing packets with their tretransmission timers
387  * @param size of buffer
388  * @return status
389  */
390 uint8_t l2cap_accept_ertm_connection(uint16_t local_cid, int ertm_mandatory, uint8_t max_transmit,
391     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);
392 
393 /**
394  * @brief Deny incoming L2CAP connection.
395  */
396 void l2cap_decline_connection(uint16_t local_cid);
397 
398 /**
399  * @brief Check if outgoing buffer is available and that there's space on the Bluetooth module
400  */
401 int  l2cap_can_send_packet_now(uint16_t local_cid);
402 
403 /**
404  * @brief Request emission of L2CAP_EVENT_CAN_SEND_NOW as soon as possible
405  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
406  *       so packet handler should be ready to handle it
407  * @param local_cid
408  */
409 void l2cap_request_can_send_now_event(uint16_t local_cid);
410 
411 /**
412  * @brief Reserve outgoing buffer
413  */
414 int  l2cap_reserve_packet_buffer(void);
415 
416 /**
417  * @brief Get outgoing buffer and prepare data.
418  */
419 uint8_t *l2cap_get_outgoing_buffer(void);
420 
421 /**
422  * @brief Send L2CAP packet prepared in outgoing buffer to channel
423  */
424 int l2cap_send_prepared(uint16_t local_cid, uint16_t len);
425 
426 /**
427  * @brief Release outgoing buffer (only needed if l2cap_send_prepared is not called)
428  */
429 void l2cap_release_packet_buffer(void);
430 
431 
432 //
433 // LE Connection Oriented Channels feature with the LE Credit Based Flow Control Mode == LE Data Channel
434 //
435 
436 
437 /**
438  * @brief Register L2CAP LE Data Channel service
439  * @note MTU and initial credits are specified in l2cap_le_accept_connection(..) call
440  * @param packet_handler
441  * @param psm
442  * @param security_level
443  */
444 uint8_t l2cap_le_register_service(btstack_packet_handler_t packet_handler, uint16_t psm, gap_security_level_t security_level);
445 
446 /**
447  * @brief Unregister L2CAP LE Data Channel service
448  * @param psm
449  */
450 
451 uint8_t l2cap_le_unregister_service(uint16_t psm);
452 
453 /*
454  * @brief Accept incoming LE Data Channel connection
455  * @param local_cid             L2CAP LE Data Channel Identifier
456  * @param receive_buffer        buffer used for reassembly of L2CAP LE Information Frames into service data unit (SDU) with given MTU
457  * @param receive_buffer_size   buffer size equals MTU
458  * @param initial_credits       Number of initial credits provided to peer or L2CAP_LE_AUTOMATIC_CREDITS to enable automatic credits
459  */
460 
461 uint8_t l2cap_le_accept_connection(uint16_t local_cid, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits);
462 
463 /**
464  * @brief Deny incoming LE Data Channel connection due to resource constraints
465  * @param local_cid             L2CAP LE Data Channel Identifier
466  */
467 
468 uint8_t l2cap_le_decline_connection(uint16_t local_cid);
469 
470 /**
471  * @brief Create LE Data Channel
472  * @param packet_handler        Packet handler for this connection
473  * @param con_handle            ACL-LE HCI Connction Handle
474  * @param psm                   Service PSM to connect to
475  * @param receive_buffer        buffer used for reassembly of L2CAP LE Information Frames into service data unit (SDU) with given MTU
476  * @param receive_buffer_size   buffer size equals MTU
477  * @param initial_credits       Number of initial credits provided to peer or L2CAP_LE_AUTOMATIC_CREDITS to enable automatic credits
478  * @param security_level        Minimum required security level
479  * @param out_local_cid         L2CAP LE Channel Identifier is stored here
480  */
481 uint8_t l2cap_le_create_channel(btstack_packet_handler_t packet_handler, hci_con_handle_t con_handle,
482     uint16_t psm, uint8_t * receive_sdu_buffer, uint16_t mtu, uint16_t initial_credits, gap_security_level_t security_level,
483     uint16_t * out_local_cid);
484 
485 /**
486  * @brief Provide credtis for LE Data Channel
487  * @param local_cid             L2CAP LE Data Channel Identifier
488  * @param credits               Number additional credits for peer
489  */
490 uint8_t l2cap_le_provide_credits(uint16_t cid, uint16_t credits);
491 
492 /**
493  * @brief Check if packet can be scheduled for transmission
494  * @param local_cid             L2CAP LE Data Channel Identifier
495  */
496 int l2cap_le_can_send_now(uint16_t cid);
497 
498 /**
499  * @brief Request emission of L2CAP_EVENT_LE_CAN_SEND_NOW as soon as possible
500  * @note L2CAP_EVENT_CAN_SEND_NOW might be emitted during call to this function
501  *       so packet handler should be ready to handle it
502  * @param local_cid             L2CAP LE Data Channel Identifier
503  */
504 uint8_t l2cap_le_request_can_send_now_event(uint16_t cid);
505 
506 /**
507  * @brief Send data via LE Data Channel
508  * @note Since data larger then the maximum PDU needs to be segmented into multiple PDUs, data needs to stay valid until ... event
509  * @param local_cid             L2CAP LE Data Channel Identifier
510  * @param data                  data to send
511  * @param size                  data size
512  */
513 uint8_t l2cap_le_send_data(uint16_t cid, uint8_t * data, uint16_t size);
514 
515 /**
516  * @brief Disconnect from LE Data Channel
517  * @param local_cid             L2CAP LE Data Channel Identifier
518  */
519 uint8_t l2cap_le_disconnect(uint16_t cid);
520 
521 /* API_END */
522 
523 #if defined __cplusplus
524 }
525 #endif
526 
527 #endif // __L2CAP_H
528