1 /******************************************************************************
2  *
3  *  Copyright 1999-2012 Broadcom Corporation
4  *
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at:
8  *
9  *  http://www.apache.org/licenses/LICENSE-2.0
10  *
11  *  Unless required by applicable law or agreed to in writing, software
12  *  distributed under the License is distributed on an "AS IS" BASIS,
13  *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  *  See the License for the specific language governing permissions and
15  *  limitations under the License.
16  *
17  ******************************************************************************/
18 
19 /******************************************************************************
20  *
21  *  this file contains the L2CAP API definitions
22  *
23  ******************************************************************************/
24 #ifndef L2C_API_H
25 #define L2C_API_H
26 
27 #include <bluetooth/log.h>
28 #include <stdbool.h>
29 
30 #include <cstdint>
31 #include <vector>
32 
33 #include "hcidefs.h"
34 #include "stack/include/bt_hdr.h"
35 #include "types/bt_transport.h"
36 #include "types/hci_role.h"
37 #include "types/raw_address.h"
38 
39 /*****************************************************************************
40  *  Constants
41  ****************************************************************************/
42 
43 /* Define the minimum offset that L2CAP needs in a buffer. This is made up of
44  * HCI type(1), len(2), handle(2), L2CAP len(2) and CID(2) => 9
45  */
46 #define L2CAP_MIN_OFFSET 13 /* plus control(2), SDU length(2) */
47 
48 #define L2CAP_LCC_SDU_LENGTH 2
49 #define L2CAP_LCC_OFFSET \
50   (L2CAP_MIN_OFFSET + L2CAP_LCC_SDU_LENGTH) /* plus SDU length(2) */
51 
52 #define L2CAP_FCS_LENGTH 2
53 
54 /* result code for L2CA_DataWrite() */
55 typedef enum : uint8_t {
56   L2CAP_DW_FAILED = 0,
57   L2CAP_DW_SUCCESS = 1,
58   L2CAP_DW_CONGESTED = 2,
59 } tL2CAP_DW_RESULT;
60 
61 /* Values for priority parameter to L2CA_SetAclPriority */
62 typedef enum : uint8_t {
63   L2CAP_PRIORITY_NORMAL = 0,
64   L2CAP_PRIORITY_HIGH = 1,
65 } tL2CAP_PRIORITY;
66 
67 /* Values for priority parameter to L2CA_SetAclLatency */
68 typedef enum : uint8_t {
69   L2CAP_LATENCY_NORMAL = 0,
70   L2CAP_LATENCY_LOW = 1,
71 } tL2CAP_LATENCY;
72 
73 /* Values for priority parameter to L2CA_SetTxPriority */
74 #define L2CAP_CHNL_PRIORITY_HIGH 0
75 #define L2CAP_CHNL_PRIORITY_LOW 2
76 
77 typedef uint8_t tL2CAP_CHNL_PRIORITY;
78 
79 /* Values for Tx/Rx data rate parameter to L2CA_SetChnlDataRate */
80 #define L2CAP_CHNL_DATA_RATE_LOW 1
81 
82 typedef uint8_t tL2CAP_CHNL_DATA_RATE;
83 
84 /* Data Packet Flags  (bits 2-15 are reserved) */
85 /* layer specific 14-15 bits are used for FCR SAR */
86 #define L2CAP_FLUSHABLE_MASK 0x0003
87 #define L2CAP_FLUSHABLE_CH_BASED 0x0000
88 #define L2CAP_FLUSHABLE_PKT 0x0001
89 #define L2CAP_NON_FLUSHABLE_PKT 0x0002
90 
91 /* L2CA_FlushChannel num_to_flush definitions */
92 #define L2CAP_FLUSH_CHANS_ALL 0xffff
93 #define L2CAP_FLUSH_CHANS_GET 0x0000
94 
95 /* Values for 'allowed_modes' field passed in structure tL2CAP_ERTM_INFO
96  */
97 #define L2CAP_FCR_CHAN_OPT_BASIC (1 << L2CAP_FCR_BASIC_MODE)
98 #define L2CAP_FCR_CHAN_OPT_ERTM (1 << L2CAP_FCR_ERTM_MODE)
99 
100 #define L2CAP_FCR_CHAN_OPT_ALL_MASK \
101   (L2CAP_FCR_CHAN_OPT_BASIC | L2CAP_FCR_CHAN_OPT_ERTM)
102 
103 /* Validity check for PSM.  PSM values must be odd.  Also, all PSM values must
104  * be assigned such that the least significant bit of the most sigificant
105  * octet equals zero.
106  */
107 #define L2C_INVALID_PSM(psm) (((psm)&0x0101) != 0x0001)
108 #define L2C_IS_VALID_PSM(psm) (((psm)&0x0101) == 0x0001)
109 #define L2C_IS_VALID_LE_PSM(psm) (((psm) > 0x0000) && ((psm) < 0x0100))
110 
111 #define L2CAP_NO_IDLE_TIMEOUT 0xFFFF
112 
113 /*****************************************************************************
114  *  Type Definitions
115  ****************************************************************************/
116 
117 typedef struct {
118 #define L2CAP_FCR_BASIC_MODE 0x00
119 #define L2CAP_FCR_ERTM_MODE 0x03
120 #define L2CAP_FCR_LE_COC_MODE 0x05
121 
122   uint8_t mode;
123 
124   uint8_t tx_win_sz;
125   uint8_t max_transmit;
126   uint16_t rtrans_tout;
127   uint16_t mon_tout;
128   uint16_t mps;
129 } tL2CAP_FCR_OPTS;
130 
131 /* default options for ERTM mode */
132 constexpr tL2CAP_FCR_OPTS kDefaultErtmOptions = {
133     L2CAP_FCR_ERTM_MODE,
134     10,    /* Tx window size */
135     20,    /* Maximum transmissions before disconnecting */
136     2000,  /* Retransmission timeout (2 secs) */
137     12000, /* Monitor timeout (12 secs) */
138     1010   /* MPS segment size */
139 };
140 
141 typedef struct {
142   uint8_t qos_flags;          /* TBD */
143   uint8_t service_type;       /* see below */
144   uint32_t token_rate;        /* bytes/second */
145   uint32_t token_bucket_size; /* bytes */
146   uint32_t peak_bandwidth;    /* bytes/second */
147   uint32_t latency;           /* microseconds */
148   uint32_t delay_variation;   /* microseconds */
149 } FLOW_SPEC;
150 
151 /* Values for service_type */
152 #define SVC_TYPE_BEST_EFFORT 1
153 #define SVC_TYPE_GUARANTEED 2
154 
155 /* Define a structure to hold the configuration parameters. Since the
156  * parameters are optional, for each parameter there is a boolean to
157  * use to signify its presence or absence.
158  */
159 typedef struct {
160   uint16_t result; /* Only used in confirm messages */
161   bool mtu_present;
162   uint16_t mtu;
163   bool qos_present;
164   FLOW_SPEC qos;
165   bool flush_to_present;
166   uint16_t flush_to;
167   bool fcr_present;
168   tL2CAP_FCR_OPTS fcr;
169   bool fcs_present; /* Optionally bypasses FCS checks */
170   uint8_t fcs;      /* '0' if desire is to bypass FCS, otherwise '1' */
171   bool ext_flow_spec_present;
172   tHCI_EXT_FLOW_SPEC ext_flow_spec;
173   uint16_t flags; /* bit 0: 0-no continuation, 1-continuation */
174 } tL2CAP_CFG_INFO;
175 
176 /* LE credit based L2CAP connection parameters */
177 constexpr uint16_t L2CAP_LE_MIN_MTU = 23;  // Minimum SDU size
178 constexpr uint16_t L2CAP_LE_MIN_MPS = 23;
179 constexpr uint16_t L2CAP_LE_MAX_MPS = 65533;
180 constexpr uint16_t L2CAP_LE_CREDIT_MAX = 65535;
181 
182 // This is initial amout of credits we send, and amount to which we increase
183 // credits once they fall below threshold
184 uint16_t L2CA_LeCreditDefault();
185 
186 // If credit count on remote fall below this value, we send back credits to
187 // reach default value.
188 uint16_t L2CA_LeCreditThreshold();
189 
190 // Max number of CIDs in the L2CAP CREDIT BASED CONNECTION REQUEST
191 constexpr uint16_t L2CAP_CREDIT_BASED_MAX_CIDS = 5;
192 
193 /* Define a structure to hold the configuration parameter for LE L2CAP
194  * connection oriented channels.
195  */
196 struct tL2CAP_LE_CFG_INFO {
197   uint16_t result; /* Only used in confirm messages */
198   uint16_t mtu = 100;
199   uint16_t mps = 100;
200   uint16_t credits = L2CA_LeCreditDefault();
201   uint8_t number_of_channels = L2CAP_CREDIT_BASED_MAX_CIDS;
202 };
203 
204 /*********************************
205  *  Callback Functions Prototypes
206  *********************************/
207 
208 /* Connection indication callback prototype. Parameters are
209  *              BD Address of remote
210  *              Local CID assigned to the connection
211  *              PSM that the remote wants to connect to
212  *              Identifier that the remote sent
213  */
214 typedef void(tL2CA_CONNECT_IND_CB)(const RawAddress&, uint16_t, uint16_t,
215                                    uint8_t);
216 
217 /* Connection confirmation callback prototype. Parameters are
218  *              Local CID
219  *              Result - 0 = connected
220  *              If there is an error, tL2CA_ERROR_CB is invoked
221  */
222 typedef void(tL2CA_CONNECT_CFM_CB)(uint16_t, uint16_t);
223 
224 /* Configuration indication callback prototype. Parameters are
225  *              Local CID assigned to the connection
226  *              Pointer to configuration info
227  */
228 typedef void(tL2CA_CONFIG_IND_CB)(uint16_t, tL2CAP_CFG_INFO*);
229 
230 constexpr uint16_t L2CAP_INITIATOR_LOCAL = 1;
231 constexpr uint16_t L2CAP_INITIATOR_REMOTE = 0;
232 /* Configuration confirm callback prototype. Parameters are
233  *              Local CID assigned to the connection
234  *              Initiator (1 for local, 0 for remote)
235  *              Initial config from remote
236  * If there is an error, tL2CA_ERROR_CB is invoked
237  */
238 typedef void(tL2CA_CONFIG_CFM_CB)(uint16_t, uint16_t, tL2CAP_CFG_INFO*);
239 
240 /* Disconnect indication callback prototype. Parameters are
241  *              Local CID
242  *              Boolean whether upper layer should ack this
243  */
244 typedef void(tL2CA_DISCONNECT_IND_CB)(uint16_t, bool);
245 
246 /* Disconnect confirm callback prototype. Parameters are
247  *              Local CID
248  *              Result
249  */
250 typedef void(tL2CA_DISCONNECT_CFM_CB)(uint16_t, uint16_t);
251 
252 /* Disconnect confirm callback prototype. Parameters are
253  *              Local CID
254  *              Result
255  */
256 typedef void(tL2CA_DATA_IND_CB)(uint16_t, BT_HDR*);
257 
258 /* Congestion status callback protype. This callback is optional. If
259  * an application tries to send data when the transmit queue is full,
260  * the data will anyways be dropped. The parameter is:
261  *              Local CID
262  *              true if congested, false if uncongested
263  */
264 typedef void(tL2CA_CONGESTION_STATUS_CB)(uint16_t, bool);
265 
266 /* Transmit complete callback protype. This callback is optional. If
267  * set, L2CAP will call it when packets are sent or flushed. If the
268  * count is 0xFFFF, it means all packets are sent for that CID (eRTM
269  * mode only). The parameters are:
270  *              Local CID
271  *              Number of SDUs sent or dropped
272  */
273 typedef void(tL2CA_TX_COMPLETE_CB)(uint16_t, uint16_t);
274 
275 /*
276  * Notify the user when the remote send error result on ConnectRsp or ConfigRsp
277  * The parameters are:
278  *              Local CID
279  *              Error type (L2CAP_CONN_OTHER_ERROR for ConnectRsp,
280  *                          L2CAP_CFG_FAILED_NO_REASON for ConfigRsp)
281  */
282 typedef void(tL2CA_ERROR_CB)(uint16_t, uint16_t);
283 
284 /* Create credit based connection request callback prototype. Parameters are
285  *              BD Address of remote
286  *              Vector of allocated local cids to accept
287  *              PSM
288  *              Peer MTU
289  *              Identifier that the remote sent
290  */
291 typedef void(tL2CA_CREDIT_BASED_CONNECT_IND_CB)(const RawAddress& bdaddr,
292                                                 std::vector<uint16_t>& lcids,
293                                                 uint16_t psm, uint16_t peer_mtu,
294                                                 uint8_t identifier);
295 
296 /* Collision Indication callback prototype. Used to notify upper layer that
297  * remote devices sent Credit Based Connection Request but it was rejected due
298  * to ongoing local request. Upper layer might want to sent another request when
299  * local request is completed. Parameters are:
300  *              BD Address of remote
301  */
302 typedef void(tL2CA_CREDIT_BASED_COLLISION_IND_CB)(const RawAddress& bdaddr);
303 
304 /* Credit based connection confirmation callback prototype. Parameters are
305  *              BD Address of remote
306  *              Connected Local CIDs
307  *              Peer MTU
308  *              Result - 0 = connected, non-zero means CID is not connected
309  */
310 typedef void(tL2CA_CREDIT_BASED_CONNECT_CFM_CB)(const RawAddress& bdaddr,
311                                                 uint16_t lcid,
312                                                 uint16_t peer_mtu,
313                                                 uint16_t result);
314 
315 /* Credit based reconfiguration confirm callback prototype. Parameters are
316  *              BD Address of remote
317  *              Local CID assigned to the connection
318  *              Flag indicating if this is local or peer configuration
319  *              Pointer to configuration info
320  */
321 typedef void(tL2CA_CREDIT_BASED_RECONFIG_COMPLETED_CB)(
322     const RawAddress& bdaddr, uint16_t lcid, bool is_local_cfg,
323     tL2CAP_LE_CFG_INFO* p_cfg);
324 
325 /* Define the structure that applications use to register with
326  * L2CAP. This structure includes callback functions. All functions
327  * MUST be provided, with the exception of the "connect pending"
328  * callback and "congestion status" callback.
329  */
330 typedef struct {
331   tL2CA_CONNECT_IND_CB* pL2CA_ConnectInd_Cb;
332   tL2CA_CONNECT_CFM_CB* pL2CA_ConnectCfm_Cb;
333   tL2CA_CONFIG_IND_CB* pL2CA_ConfigInd_Cb;
334   tL2CA_CONFIG_CFM_CB* pL2CA_ConfigCfm_Cb;
335   tL2CA_DISCONNECT_IND_CB* pL2CA_DisconnectInd_Cb;
336   tL2CA_DISCONNECT_CFM_CB* pL2CA_DisconnectCfm_Cb;
337   tL2CA_DATA_IND_CB* pL2CA_DataInd_Cb;
338   tL2CA_CONGESTION_STATUS_CB* pL2CA_CongestionStatus_Cb;
339   tL2CA_TX_COMPLETE_CB* pL2CA_TxComplete_Cb;
340   tL2CA_ERROR_CB* pL2CA_Error_Cb;
341   tL2CA_CREDIT_BASED_CONNECT_IND_CB* pL2CA_CreditBasedConnectInd_Cb;
342   tL2CA_CREDIT_BASED_CONNECT_CFM_CB* pL2CA_CreditBasedConnectCfm_Cb;
343   tL2CA_CREDIT_BASED_RECONFIG_COMPLETED_CB*
344       pL2CA_CreditBasedReconfigCompleted_Cb;
345   tL2CA_CREDIT_BASED_COLLISION_IND_CB* pL2CA_CreditBasedCollisionInd_Cb;
346 } tL2CAP_APPL_INFO;
347 
348 /* Define the structure that applications use to create or accept
349  * connections with enhanced retransmission mode.
350  */
351 typedef struct {
352   uint8_t preferred_mode;
353 } tL2CAP_ERTM_INFO;
354 
355 /**
356  * Stack management declarations
357  */
358 void l2c_init();
359 void l2c_free();
360 
361 /*****************************************************************************
362  *  External Function Declarations
363  ****************************************************************************/
364 
365 // Also does security for you
366 [[nodiscard]] uint16_t L2CA_RegisterWithSecurity(
367     uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop,
368     tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu,
369     uint16_t required_remote_mtu, uint16_t sec_level);
370 
371 /*******************************************************************************
372  *
373  * Function         L2CA_Register
374  *
375  * Description      Other layers call this function to register for L2CAP
376  *                  services.
377  *
378  * Returns          PSM to use or zero if error. Typically, the PSM returned
379  *                  is the same as was passed in, but for an outgoing-only
380  *                  connection to a dynamic PSM, a "virtual" PSM is returned
381  *                  and should be used in the calls to L2CA_ConnectReq() and
382  *                  BTM_SetSecurityLevel().
383  *
384  ******************************************************************************/
385 [[nodiscard]] uint16_t L2CA_Register(
386     uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info, bool enable_snoop,
387     tL2CAP_ERTM_INFO* p_ertm_info, uint16_t my_mtu,
388     uint16_t required_remote_mtu, uint16_t sec_level);
389 
390 /*******************************************************************************
391  *
392  * Function         L2CA_Deregister
393  *
394  * Description      Other layers call this function to deregister for L2CAP
395  *                  services.
396  *
397  * Returns          void
398  *
399  ******************************************************************************/
400 void L2CA_Deregister(uint16_t psm);
401 
402 /*******************************************************************************
403  *
404  * Function         L2CA_AllocateLePSM
405  *
406  * Description      Other layers call this function to find an unused LE PSM for
407  *                  L2CAP services.
408  *
409  * Returns          LE_PSM to use if success. Otherwise returns 0.
410  *
411  ******************************************************************************/
412 [[nodiscard]] uint16_t L2CA_AllocateLePSM(void);
413 
414 /*******************************************************************************
415  *
416  * Function         L2CA_FreeLePSM
417  *
418  * Description      Free an assigned LE PSM.
419  *
420  * Returns          void
421  *
422  ******************************************************************************/
423 void L2CA_FreeLePSM(uint16_t psm);
424 
425 [[nodiscard]] uint16_t L2CA_ConnectReqWithSecurity(uint16_t psm,
426                                                    const RawAddress& p_bd_addr,
427                                                    uint16_t sec_level);
428 /*******************************************************************************
429  *
430  * Function         L2CA_ConnectReq
431  *
432  * Description      Higher layers call this function to create an L2CAP
433  *                  connection.
434  *                  Note that the connection is not established at this time,
435  *                  but connection establishment gets started. The callback
436  *                  will be invoked when connection establishes or fails.
437  *
438  * Returns          the CID of the connection, or 0 if it failed to start
439  *
440  ******************************************************************************/
441 [[nodiscard]] uint16_t L2CA_ConnectReq(uint16_t psm,
442                                        const RawAddress& p_bd_addr);
443 
444 /*******************************************************************************
445  *
446  * Function         L2CA_RegisterLECoc
447  *
448  * Description      Other layers call this function to register for L2CAP
449  *                  Connection Oriented Channel.
450  *
451  * Returns          PSM to use or zero if error. Typically, the PSM returned
452  *                  is the same as was passed in, but for an outgoing-only
453  *                  connection to a dynamic PSM, a "virtual" PSM is returned
454  *                  and should be used in the calls to L2CA_ConnectLECocReq()
455  *                  and BTM_SetSecurityLevel().
456  *
457  ******************************************************************************/
458 [[nodiscard]] uint16_t L2CA_RegisterLECoc(uint16_t psm,
459                                           const tL2CAP_APPL_INFO& p_cb_info,
460                                           uint16_t sec_level,
461                                           tL2CAP_LE_CFG_INFO cfg);
462 
463 /*******************************************************************************
464  *
465  * Function         L2CA_DeregisterLECoc
466  *
467  * Description      Other layers call this function to deregister for L2CAP
468  *                  Connection Oriented Channel.
469  *
470  * Returns          void
471  *
472  ******************************************************************************/
473 void L2CA_DeregisterLECoc(uint16_t psm);
474 
475 /*******************************************************************************
476  *
477  * Function         L2CA_ConnectLECocReq
478  *
479  * Description      Higher layers call this function to create an L2CAP LE COC.
480  *                  Note that the connection is not established at this time,
481  *                  but connection establishment gets started. The callback
482  *                  will be invoked when connection establishes or fails.
483  *
484  * Returns          the CID of the connection, or 0 if it failed to start
485  *
486  ******************************************************************************/
487 [[nodiscard]] uint16_t L2CA_ConnectLECocReq(uint16_t psm,
488                                             const RawAddress& p_bd_addr,
489                                             tL2CAP_LE_CFG_INFO* p_cfg,
490                                             uint16_t sec_level);
491 
492 /*******************************************************************************
493  *
494  *  Function         L2CA_GetPeerLECocConfig
495  *
496  *  Description      Get peers configuration for LE Connection Oriented Channel.
497  *
498  *  Return value:    true if peer is connected
499  *
500  ******************************************************************************/
501 [[nodiscard]] bool L2CA_GetPeerLECocConfig(uint16_t lcid,
502                                            tL2CAP_LE_CFG_INFO* peer_cfg);
503 
504 /*******************************************************************************
505  *
506  *  Function         L2CA_GetPeerLECocCredit
507  *
508  *  Description      Get peers current credit for LE Connection Oriented
509  *                   Channel.
510  *
511  *  Return value:    Number of the peer current credit
512  *
513  ******************************************************************************/
514 [[nodiscard]] uint16_t L2CA_GetPeerLECocCredit(const RawAddress& bd_addr,
515                                                uint16_t lcid);
516 
517 /*******************************************************************************
518  *
519  *  Function         L2CA_ReconfigCreditBasedConnsReq
520  *
521  *  Description      Start reconfigure procedure on Connection Oriented Channel.
522  *
523  *  Return value:    true if peer is connected
524  *
525  ******************************************************************************/
526 
527 [[nodiscard]] bool L2CA_ReconfigCreditBasedConnsReq(
528     const RawAddress& bd_addr, std::vector<uint16_t>& lcids,
529     tL2CAP_LE_CFG_INFO* p_cfg);
530 
531 /*******************************************************************************
532  *
533  *  Function         L2CA_ConnectCreditBasedReq
534  *
535  *  Description      With this function L2CAP will initiate setup of up to 5 credit
536  *                   based connections for given psm using provided configuration.
537  *                   L2CAP will notify user on the connection result, by calling
538  *                   pL2CA_CreditBasedConnectCfm_Cb for each cid with a result.
539  *
540  *  Return value: vector of allocated local cids for the connection
541  *
542  ******************************************************************************/
543 
544 [[nodiscard]] std::vector<uint16_t> L2CA_ConnectCreditBasedReq(
545     uint16_t psm, const RawAddress& p_bd_addr, tL2CAP_LE_CFG_INFO* p_cfg);
546 
547 /*******************************************************************************
548  *
549  *  Function         L2CA_ConnectCreditBasedRsp
550  *
551  *  Description      Response for the pL2CA_CreditBasedConnectInd_Cb which is the
552  *                   indication for peer requesting credit based connection.
553  *
554  *  Return value: true if peer is connected
555  *
556  ******************************************************************************/
557 
558 [[nodiscard]] bool L2CA_ConnectCreditBasedRsp(
559     const RawAddress& p_bd_addr, uint8_t id,
560     std::vector<uint16_t>& accepted_lcids, uint16_t result,
561     tL2CAP_LE_CFG_INFO* p_cfg);
562 /*******************************************************************************
563  *
564  * Function         L2CA_DisconnectReq
565  *
566  * Description      Higher layers call this function to disconnect a channel.
567  *
568  * Returns          true if disconnect sent, else false
569  *
570  ******************************************************************************/
571 [[nodiscard]] bool L2CA_DisconnectReq(uint16_t cid);
572 
573 [[nodiscard]] bool L2CA_DisconnectLECocReq(uint16_t cid);
574 
575 /*******************************************************************************
576  *
577  * Function         L2CA_DataWrite
578  *
579  * Description      Higher layers call this function to write data.
580  *
581  * Returns          L2CAP_DW_SUCCESS, if data accepted, else false
582  *                  L2CAP_DW_CONGESTED, if data accepted and the channel is
583  *                                      congested
584  *                  L2CAP_DW_FAILED, if error
585  *
586  ******************************************************************************/
587 [[nodiscard]] uint8_t L2CA_DataWrite(uint16_t cid, BT_HDR* p_data);
588 
589 [[nodiscard]] uint8_t L2CA_LECocDataWrite(uint16_t cid, BT_HDR* p_data);
590 
591 /*******************************************************************************
592  *
593  *  Function        L2CA_GetRemoteChannelId
594  *
595  *  Description     Given a local channel identifier, |lcid|, this function
596  *                  returns the bound remote channel identifier, |rcid|. If
597  *                  |lcid| is not known or is invalid, this function returns
598  *                  false and does not modify the value pointed at by |rcid|.
599  *
600  *  Parameters:     lcid: Local CID
601  *                  rcid: Pointer to remote CID must NOT be nullptr
602  *
603  *  Return value:   true if rcid lookup was successful
604  *
605  ******************************************************************************/
606 [[nodiscard]] bool L2CA_GetRemoteChannelId(uint16_t lcid, uint16_t* rcid);
607 
608 /*******************************************************************************
609  *
610  * Function         L2CA_SetIdleTimeoutByBdAddr
611  *
612  * Description      Higher layers call this function to set the idle timeout for
613  *                  a connection. The "idle timeout" is the amount of time that
614  *                  a connection can remain up with no L2CAP channels on it.
615  *                  A timeout of zero means that the connection will be torn
616  *                  down immediately when the last channel is removed.
617  *                  A timeout of 0xFFFF means no timeout. Values are in seconds.
618  *                  A bd_addr is the remote BD address. If bd_addr =
619  *                  RawAddress::kAny, then the idle timeouts for all active
620  *                  l2cap links will be changed.
621  *
622  * Returns          true if command succeeded, false if failed
623  *
624  * NOTE             This timeout applies to all logical channels active on the
625  *                  ACL link.
626  ******************************************************************************/
627 [[nodiscard]] bool L2CA_SetIdleTimeoutByBdAddr(const RawAddress& bd_addr,
628                                                uint16_t timeout,
629                                                tBT_TRANSPORT transport);
630 
631 /*******************************************************************************
632  *
633  * Function     L2CA_FlushChannel
634  *
635  * Description  This function flushes none, some or all buffers queued up
636  *              for xmission for a particular CID. If called with
637  *              L2CAP_FLUSH_CHANS_GET (0), it simply returns the number
638  *              of buffers queued for that CID L2CAP_FLUSH_CHANS_ALL (0xffff)
639  *              flushes all buffers.  All other values specifies the maximum
640  *              buffers to flush.
641  *
642  * Returns      Number of buffers left queued for that CID
643  *
644  ******************************************************************************/
645 [[nodiscard]] uint16_t L2CA_FlushChannel(uint16_t lcid, uint16_t num_to_flush);
646 
647 /*******************************************************************************
648  *
649  * Function         L2CA_UseLatencyMode
650  *
651  * Description      Sets use latency mode for an ACL channel.
652  *
653  * Returns          true if a valid channel, else false
654  *
655  ******************************************************************************/
656 [[nodiscard]] bool L2CA_UseLatencyMode(const RawAddress& bd_addr,
657                                        bool use_latency_mode);
658 
659 /*******************************************************************************
660  *
661  * Function         L2CA_SetAclPriority
662  *
663  * Description      Sets the transmission priority for an ACL channel.
664  *                  (For initial implementation only two values are valid.
665  *                  L2CAP_PRIORITY_NORMAL and L2CAP_PRIORITY_HIGH).
666  *
667  * Returns          true if a valid channel, else false
668  *
669  ******************************************************************************/
670 [[nodiscard]] bool L2CA_SetAclPriority(const RawAddress& bd_addr,
671                                        tL2CAP_PRIORITY priority);
672 
673 /*******************************************************************************
674  *
675  * Function         L2CA_SetAclLatency
676  *
677  * Description      Sets the transmission latency for a channel.
678  *
679  * Returns          true if a valid channel, else false
680  *
681  ******************************************************************************/
682 [[nodiscard]] bool L2CA_SetAclLatency(const RawAddress& bd_addr,
683                                       tL2CAP_LATENCY latency);
684 
685 /*******************************************************************************
686  *
687  * Function         L2CA_SetTxPriority
688  *
689  * Description      Sets the transmission priority for a channel. (FCR Mode)
690  *
691  * Returns          true if a valid channel, else false
692  *
693  ******************************************************************************/
694 [[nodiscard]] bool L2CA_SetTxPriority(uint16_t cid,
695                                       tL2CAP_CHNL_PRIORITY priority);
696 
697 /*******************************************************************************
698  *
699  * Function         L2CA_SetChnlFlushability
700  *
701  * Description      Higher layers call this function to set a channels
702  *                  flushability flags
703  *
704  * Returns          true if CID found, else false
705  *
706  ******************************************************************************/
707 [[nodiscard]] bool L2CA_SetChnlFlushability(uint16_t cid, bool is_flushable);
708 
709 /*******************************************************************************
710  *
711  *  Function         L2CA_GetPeerFeatures
712  *
713  *  Description      Get a peers features and fixed channel map
714  *
715  *  Parameters:      BD address of the peer
716  *                   Pointers to features and channel mask storage area
717  *
718  *  Return value:    true if peer is connected
719  *
720  ******************************************************************************/
721 [[nodiscard]] bool L2CA_GetPeerFeatures(const RawAddress& bd_addr,
722                                         uint32_t* p_ext_feat,
723                                         uint8_t* p_chnl_mask);
724 
725 /*******************************************************************************
726  *
727  *                      Fixed Channel callback prototypes
728  *
729  ******************************************************************************/
730 
731 /* Fixed channel connected and disconnected. Parameters are
732  *      channel
733  *      BD Address of remote
734  *      true if channel is connected, false if disconnected
735  *      Reason for connection failure
736  *      transport : physical transport, BR/EDR or LE
737  */
738 typedef void(tL2CA_FIXED_CHNL_CB)(uint16_t, const RawAddress&, bool, uint16_t,
739                                   tBT_TRANSPORT);
740 
741 /* Signalling data received. Parameters are
742  *      channel
743  *      BD Address of remote
744  *      Pointer to buffer with data
745  */
746 typedef void(tL2CA_FIXED_DATA_CB)(uint16_t, const RawAddress&, BT_HDR*);
747 
748 /* Congestion status callback protype. This callback is optional. If
749  * an application tries to send data when the transmit queue is full,
750  * the data will anyways be dropped. The parameter is:
751  *      remote BD_ADDR
752  *      true if congested, false if uncongested
753  */
754 typedef void(tL2CA_FIXED_CONGESTION_STATUS_CB)(const RawAddress&, bool);
755 
756 /* Fixed channel registration info (the callback addresses and channel config)
757  */
758 typedef struct {
759   tL2CA_FIXED_CHNL_CB* pL2CA_FixedConn_Cb;
760   tL2CA_FIXED_DATA_CB* pL2CA_FixedData_Cb;
761   tL2CA_FIXED_CONGESTION_STATUS_CB* pL2CA_FixedCong_Cb;
762 
763   uint16_t default_idle_tout;
764   tL2CA_TX_COMPLETE_CB*
765       pL2CA_FixedTxComplete_Cb; /* fixed channel tx complete callback */
766 } tL2CAP_FIXED_CHNL_REG;
767 
768 /*******************************************************************************
769  *
770  *  Function        L2CA_RegisterFixedChannel
771  *
772  *  Description     Register a fixed channel.
773  *
774  *  Parameters:     Fixed Channel #
775  *                  Channel Callbacks and config
776  *
777  *  Return value:   true if registered OK
778  *
779  ******************************************************************************/
780 [[nodiscard]] bool L2CA_RegisterFixedChannel(uint16_t fixed_cid,
781                                              tL2CAP_FIXED_CHNL_REG* p_freg);
782 
783 /*******************************************************************************
784  *
785  *  Function        L2CA_ConnectFixedChnl
786  *
787  *  Description     Connect an fixed signalling channel to a remote device.
788  *
789  *  Parameters:     Fixed CID
790  *                  BD Address of remote
791  *
792  *  Return value:   true if connection started
793  *
794  ******************************************************************************/
795 [[nodiscard]] bool L2CA_ConnectFixedChnl(uint16_t fixed_cid,
796                                          const RawAddress& bd_addr);
797 
798 /*******************************************************************************
799  *
800  *  Function        L2CA_SendFixedChnlData
801  *
802  *  Description     Write data on a fixed signalling channel.
803  *
804  *  Parameters:     Fixed CID
805  *                  BD Address of remote
806  *                  Pointer to buffer of type BT_HDR
807  *
808  * Return value     L2CAP_DW_SUCCESS, if data accepted
809  *                  L2CAP_DW_FAILED,  if error
810  *
811  ******************************************************************************/
812 [[nodiscard]] uint16_t L2CA_SendFixedChnlData(uint16_t fixed_cid,
813                                               const RawAddress& rem_bda,
814                                               BT_HDR* p_buf);
815 
816 /*******************************************************************************
817  *
818  *  Function        L2CA_RemoveFixedChnl
819  *
820  *  Description     Remove a fixed channel to a remote device.
821  *
822  *  Parameters:     Fixed CID
823  *                  BD Address of remote
824  *                  Idle timeout to use (or 0xFFFF if don't care)
825  *
826  *  Return value:   true if channel removed
827  *
828  ******************************************************************************/
829 [[nodiscard]] bool L2CA_RemoveFixedChnl(uint16_t fixed_cid,
830                                         const RawAddress& rem_bda);
831 
832 /*******************************************************************************
833  *
834  * Function         L2CA_SetLeGattTimeout
835  *
836  * Description      Higher layers call this function to set the idle timeout for
837  *                  a fixed channel. The "idle timeout" is the amount of time
838  *                  that a connection can remain up with no L2CAP channels on
839  *                  it. A timeout of zero means that the connection will be torn
840  *                  down immediately when the last channel is removed.
841  *                  A timeout of 0xFFFF means no timeout. Values are in seconds.
842  *                  A bd_addr is the remote BD address. If bd_addr =
843  *                  RawAddress::kAny, then the idle timeouts for all active
844  *                  l2cap links will be changed.
845  *
846  * Returns          true if command succeeded, false if failed
847  *
848  ******************************************************************************/
849 [[nodiscard]] bool L2CA_SetLeGattTimeout(const RawAddress& rem_bda,
850                                          uint16_t idle_tout);
851 
852 [[nodiscard]] bool L2CA_MarkLeLinkAsActive(const RawAddress& rem_bda);
853 
854 [[nodiscard]] bool L2CA_UpdateBleConnParams(const RawAddress& rem_bda,
855                                             uint16_t min_int, uint16_t max_int,
856                                             uint16_t latency, uint16_t timeout,
857                                             uint16_t min_ce_len,
858                                             uint16_t max_ce_len);
859 
860 /* When called with lock=true, LE connection parameters will be locked on
861  * fastest value, and we won't accept request to change it from remote. When
862  * called with lock=false, parameters are relaxed.
863  */
864 void L2CA_LockBleConnParamsForServiceDiscovery(const RawAddress& rem_bda,
865                                                bool lock);
866 
867 /* When called with lock=true, LE connection parameters will be locked on
868  * fastest value, and we won't accept request to change it from remote. When
869  * called with lock=false, parameters are relaxed.
870  */
871 void L2CA_LockBleConnParamsForProfileConnection(const RawAddress& rem_bda,
872                                                 bool lock);
873 
874 /*******************************************************************************
875  *
876  * Function         L2CA_GetBleConnRole
877  *
878  * Description      This function returns the connection role.
879  *
880  * Returns          link role.
881  *
882  ******************************************************************************/
883 void L2CA_Consolidate(const RawAddress& identity_addr, const RawAddress& rpa);
884 [[nodiscard]] tHCI_ROLE L2CA_GetBleConnRole(const RawAddress& bd_addr);
885 
886 void L2CA_AdjustConnectionIntervals(uint16_t* min_interval,
887                                     uint16_t* max_interval,
888                                     uint16_t floor_interval);
889 
890 void L2CA_SetEcosystemBaseInterval(uint32_t base_interval);
891 
892 /**
893  * Check whether an ACL or LE link to the remote device is established
894  */
895 [[nodiscard]] bool L2CA_IsLinkEstablished(const RawAddress& bd_addr,
896                                           tBT_TRANSPORT transport);
897 
898 /*******************************************************************************
899  *
900  *  Function        L2CA_SetDefaultSubrate
901  *
902  *  Description     BLE Set Default Subrate.
903  *
904  *  Parameters:     Subrate parameters
905  *
906  *  Return value:   void
907  *
908  ******************************************************************************/
909 void L2CA_SetDefaultSubrate(uint16_t subrate_min, uint16_t subrate_max,
910                             uint16_t max_latency, uint16_t cont_num,
911                             uint16_t timeout);
912 
913 /*******************************************************************************
914  *
915  *  Function        L2CA_SubrateRequest
916  *
917  *  Description     BLE Subrate request.
918  *
919  *  Parameters:     Subrate parameters
920  *
921  *  Return value:   true if update started
922  *
923  ******************************************************************************/
924 [[nodiscard]] bool L2CA_SubrateRequest(const RawAddress& rem_bda,
925                                        uint16_t subrate_min,
926                                        uint16_t subrate_max,
927                                        uint16_t max_latency, uint16_t cont_num,
928                                        uint16_t timeout);
929 
930 /*******************************************************************************
931 **
932 ** Function         L2CA_SetMediaStreamChannel
933 **
934 ** Description      This function is called to set/reset the ccb of active media
935 **                      streaming channel
936 **
937 **  Parameters:     local_media_cid: The local cid provided to A2DP to be used
938 **                      for streaming
939 **                  status: The status of media streaming on this channel
940 **
941 ** Returns          void
942 **
943 *******************************************************************************/
944 void L2CA_SetMediaStreamChannel(uint16_t local_media_cid, bool status);
945 
946 /*******************************************************************************
947 **
948 ** Function         L2CA_isMediaChannel
949 **
950 ** Description      This function returns if the channel id passed as parameter
951 **                      is an A2DP streaming channel
952 **
953 **  Parameters:     handle: Connection handle with the remote device
954 **                  channel_id: Channel ID
955 **                  is_local_cid: Signifies if the channel id passed is local
956 **                      cid or remote cid (true if local, remote otherwise)
957 **
958 ** Returns          bool
959 **
960 *******************************************************************************/
961 [[nodiscard]] bool L2CA_isMediaChannel(uint16_t handle, uint16_t channel_id,
962                                        bool is_local_cid);
963 
964 namespace fmt {
965 template <>
966 struct formatter<tL2CAP_LATENCY> : enum_formatter<tL2CAP_LATENCY> {};
967 template <>
968 struct formatter<tL2CAP_PRIORITY> : enum_formatter<tL2CAP_PRIORITY> {};
969 }  // namespace fmt
970 
971 /*******************************************************************************
972 **
973 ** Function         L2CA_Dumpsys
974 **
975 ** Description      This function provides dumpsys data during the dumpsys
976 **                  procedure.
977 **
978 ** Parameters:      fd: Descriptor used to write the L2CAP internals
979 **
980 ** Returns          void
981 **
982 *******************************************************************************/
983 void L2CA_Dumpsys(int fd);
984 
985 #endif /* L2C_API_H */
986