• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 L2CAP internal definitions
22  *
23  ******************************************************************************/
24 #pragma once
25 
26 #include <bluetooth/log.h>
27 #include <stdbool.h>
28 
29 #include <string>
30 #include <vector>
31 
32 #include "include/macros.h"
33 #include "internal_include/bt_target.h"
34 #include "osi/include/alarm.h"
35 #include "osi/include/fixed_queue.h"
36 #include "osi/include/list.h"
37 #include "stack/include/bt_hdr.h"
38 #include "stack/include/btm_sec_api_types.h"
39 #include "stack/include/hci_error_code.h"
40 #include "stack/include/l2cap_interface.h"
41 #include "stack/l2cap/internal/l2c_api.h"
42 #include "types/hci_role.h"
43 #include "types/raw_address.h"
44 
45 #define L2CAP_MIN_MTU 48 /* Minimum acceptable MTU is 48 bytes */
46 
47 #define MAX_ACTIVE_AVDT_CONN 2
48 
49 constexpr uint16_t L2CAP_CREDIT_BASED_MIN_MTU = 64;
50 constexpr uint16_t L2CAP_CREDIT_BASED_MIN_MPS = 64;
51 
52 /*
53  * Timeout values (in milliseconds).
54  */
55 #define L2CAP_LINK_ROLE_SWITCH_TIMEOUT_MS (10 * 1000)  /* 10 seconds */
56 #define L2CAP_LINK_CONNECT_TIMEOUT_MS (60 * 1000)      /* 60 seconds */
57 #define L2CAP_LINK_CONNECT_EXT_TIMEOUT_MS (120 * 1000) /* 120 seconds */
58 #define L2CAP_LINK_FLOW_CONTROL_TIMEOUT_MS (2 * 1000)  /* 2 seconds */
59 #define L2CAP_LINK_DISCONNECT_TIMEOUT_MS (30 * 1000)   /* 30 seconds */
60 #define L2CAP_CHNL_CONNECT_TIMEOUT_MS (60 * 1000)      /* 60 seconds */
61 #define L2CAP_CHNL_CONNECT_EXT_TIMEOUT_MS (120 * 1000) /* 120 seconds */
62 #define L2CAP_CHNL_CFG_TIMEOUT_MS (30 * 1000)          /* 30 seconds */
63 #define L2CAP_CHNL_DISCONNECT_TIMEOUT_MS (10 * 1000)   /* 10 seconds */
64 #define L2CAP_DELAY_CHECK_SM4_TIMEOUT_MS (2 * 1000)    /* 2 seconds */
65 #define L2CAP_WAIT_INFO_RSP_TIMEOUT_MS (3 * 1000)      /* 3 seconds */
66 #define L2CAP_BLE_LINK_CONNECT_TIMEOUT_MS (30 * 1000)  /* 30 seconds */
67 #define L2CAP_FCR_ACK_TIMEOUT_MS 200                   /* 200 milliseconds */
68 
69 /* Define the possible L2CAP channel states. The names of
70  * the states may seem a bit strange, but they are taken from
71  * the Bluetooth specification.
72  */
73 typedef enum {
74   CST_CLOSED,                  /* Channel is in closed state */
75   CST_ORIG_W4_SEC_COMP,        /* Originator waits security clearence */
76   CST_TERM_W4_SEC_COMP,        /* Acceptor waits security clearence */
77   CST_W4_L2CAP_CONNECT_RSP,    /* Waiting for peer conenct response */
78   CST_W4_L2CA_CONNECT_RSP,     /* Waiting for upper layer connect rsp */
79   CST_CONFIG,                  /* Negotiating configuration */
80   CST_OPEN,                    /* Data transfer state */
81   CST_W4_L2CAP_DISCONNECT_RSP, /* Waiting for peer disconnect rsp */
82   CST_W4_L2CA_DISCONNECT_RSP   /* Waiting for upper layer disc rsp */
83 } tL2C_CHNL_STATE;
84 
channel_state_text(const tL2C_CHNL_STATE & state)85 inline std::string channel_state_text(const tL2C_CHNL_STATE& state) {
86   switch (state) {
87     CASE_RETURN_TEXT(CST_CLOSED);
88     CASE_RETURN_TEXT(CST_ORIG_W4_SEC_COMP);
89     CASE_RETURN_TEXT(CST_TERM_W4_SEC_COMP);
90     CASE_RETURN_TEXT(CST_W4_L2CAP_CONNECT_RSP);
91     CASE_RETURN_TEXT(CST_W4_L2CA_CONNECT_RSP);
92     CASE_RETURN_TEXT(CST_CONFIG);
93     CASE_RETURN_TEXT(CST_OPEN);
94     CASE_RETURN_TEXT(CST_W4_L2CAP_DISCONNECT_RSP);
95     CASE_RETURN_TEXT(CST_W4_L2CA_DISCONNECT_RSP);
96     default:
97       return std::format("UNKNOWN[{}]", static_cast<int>(state));
98   }
99 }
100 
101 /* Define the possible L2CAP link states
102  */
103 typedef enum {
104   LST_DISCONNECTED,
105   LST_CONNECT_HOLDING,
106   LST_CONNECTING_WAIT_SWITCH,
107   LST_CONNECTING,
108   LST_CONNECTED,
109   LST_DISCONNECTING
110 } tL2C_LINK_STATE;
111 
link_state_text(const tL2C_LINK_STATE & state)112 inline std::string link_state_text(const tL2C_LINK_STATE& state) {
113   switch (state) {
114     CASE_RETURN_STRING(LST_DISCONNECTED);
115     CASE_RETURN_STRING(LST_CONNECT_HOLDING);
116     CASE_RETURN_STRING(LST_CONNECTING_WAIT_SWITCH);
117     CASE_RETURN_STRING(LST_CONNECTING);
118     CASE_RETURN_STRING(LST_CONNECTED);
119     CASE_RETURN_STRING(LST_DISCONNECTING);
120   }
121   RETURN_UNKNOWN_TYPE_STRING(tL2C_LINK_STATE, state);
122 }
123 
124 /* Define input events to the L2CAP link and channel state machines. The names
125  * of the events may seem a bit strange, but they are taken from
126  * the Bluetooth specification.
127  */
128 typedef enum : uint16_t {
129   /* Lower layer */
130   L2CEVT_LP_CONNECT_CFM = 0,     /* connect confirm */
131   L2CEVT_LP_CONNECT_CFM_NEG = 1, /* connect confirm (failed) */
132   L2CEVT_LP_CONNECT_IND = 2,     /* connect indication */
133   L2CEVT_LP_DISCONNECT_IND = 3,  /* disconnect indication */
134 
135   /* Security */
136   L2CEVT_SEC_COMP = 7,     /* cleared successfully */
137   L2CEVT_SEC_COMP_NEG = 8, /* procedure failed */
138 
139   /* Peer connection */
140   L2CEVT_L2CAP_CONNECT_REQ = 10,     /* request */
141   L2CEVT_L2CAP_CONNECT_RSP = 11,     /* response */
142   L2CEVT_L2CAP_CONNECT_RSP_PND = 12, /* response pending */
143   L2CEVT_L2CAP_CONNECT_RSP_NEG = 13, /* response (failed) */
144 
145   /* Peer configuration */
146   L2CEVT_L2CAP_CONFIG_REQ = 14,     /* request */
147   L2CEVT_L2CAP_CONFIG_RSP = 15,     /* response */
148   L2CEVT_L2CAP_CONFIG_RSP_NEG = 16, /* response (failed) */
149 
150   L2CEVT_L2CAP_DISCONNECT_REQ = 17, /* Peer disconnect request */
151   L2CEVT_L2CAP_DISCONNECT_RSP = 18, /* Peer disconnect response */
152   L2CEVT_L2CAP_INFO_RSP = 19,       /* Peer information response */
153   L2CEVT_L2CAP_DATA = 20,           /* Peer data */
154 
155   /* Upper layer */
156   L2CEVT_L2CA_CONNECT_REQ = 21,     /* connect request */
157   L2CEVT_L2CA_CONNECT_RSP = 22,     /* connect response */
158   L2CEVT_L2CA_CONNECT_RSP_NEG = 23, /* connect response (failed)*/
159   L2CEVT_L2CA_CONFIG_REQ = 24,      /* config request */
160   L2CEVT_L2CA_CONFIG_RSP = 25,      /* config response */
161   L2CEVT_L2CA_DISCONNECT_REQ = 27,  /* disconnect request */
162   L2CEVT_L2CA_DISCONNECT_RSP = 28,  /* disconnect response */
163   L2CEVT_L2CA_DATA_READ = 29,       /* data read */
164   L2CEVT_L2CA_DATA_WRITE = 30,      /* data write */
165 
166   L2CEVT_TIMEOUT = 32,         /* Timeout */
167   L2CEVT_SEC_RE_SEND_CMD = 33, /* btm_sec has enough info to proceed */
168 
169   L2CEVT_ACK_TIMEOUT = 34, /* RR delay timeout */
170 
171   L2CEVT_L2CA_SEND_FLOW_CONTROL_CREDIT = 35,  // Upper layer credit packet
172   /* Peer credit based connection */
173   L2CEVT_L2CAP_RECV_FLOW_CONTROL_CREDIT = 36,     /* credit packet */
174   L2CEVT_L2CAP_CREDIT_BASED_CONNECT_REQ = 37,     /* credit based connection request */
175   L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP = 38,     /* accepted credit based connection */
176   L2CEVT_L2CAP_CREDIT_BASED_CONNECT_RSP_NEG = 39, /* rejected credit based connection */
177   L2CEVT_L2CAP_CREDIT_BASED_RECONFIG_REQ = 40,    /* credit based reconfig request*/
178   L2CEVT_L2CAP_CREDIT_BASED_RECONFIG_RSP = 41,    /* credit based reconfig response */
179 
180   /* Upper layer credit based connection */
181   L2CEVT_L2CA_CREDIT_BASED_CONNECT_REQ = 42,     /* connect request */
182   L2CEVT_L2CA_CREDIT_BASED_CONNECT_RSP = 43,     /* connect response */
183   L2CEVT_L2CA_CREDIT_BASED_CONNECT_RSP_NEG = 44, /* connect response (failed)*/
184   L2CEVT_L2CA_CREDIT_BASED_RECONFIG_REQ = 45,    /* reconfig request */
185 } tL2CEVT;
186 
187 /* Constants for LE Dynamic PSM values */
188 #define LE_DYNAMIC_PSM_START 0x0080
189 #define LE_DYNAMIC_PSM_END 0x00FF
190 #define LE_DYNAMIC_PSM_RANGE (LE_DYNAMIC_PSM_END - LE_DYNAMIC_PSM_START + 1)
191 
192 /* Return values for l2cu_process_peer_cfg_req() */
193 #define L2CAP_PEER_CFG_UNACCEPTABLE 0
194 #define L2CAP_PEER_CFG_OK 1
195 #define L2CAP_PEER_CFG_DISCONNECT 2
196 
197 /* eL2CAP option constants */
198 /* Min retransmission timeout if no flush timeout or PBF */
199 #define L2CAP_MIN_RETRANS_TOUT 2000
200 /* Min monitor timeout if no flush timeout or PBF */
201 #define L2CAP_MIN_MONITOR_TOUT 12000
202 
203 #define L2CAP_MAX_FCR_CFG_TRIES 2 /* Config attempts before disconnecting */
204 
205 typedef uint8_t tL2C_BLE_FIXED_CHNLS_MASK;
206 
207 struct tL2C_FCRB {
208   uint8_t next_tx_seq;       /* Next sequence number to be Tx'ed */
209   uint8_t last_rx_ack;       /* Last sequence number ack'ed by the peer */
210   uint8_t next_seq_expected; /* Next peer sequence number expected */
211   uint8_t last_ack_sent;     /* Last peer sequence number ack'ed */
212   uint8_t num_tries;         /* Number of retries to send a packet */
213   uint8_t max_held_acks;     /* Max acks we can hold before sending */
214 
215   bool remote_busy; /* true if peer has flowed us off */
216 
217   bool rej_sent;       /* Reject was sent */
218   bool srej_sent;      /* Selective Reject was sent */
219   bool wait_ack;       /* Transmitter is waiting ack (poll sent) */
220   bool rej_after_srej; /* Send a REJ when SREJ clears */
221 
222   bool send_f_rsp; /* We need to send an F-bit response */
223 
224   uint16_t rx_sdu_len;              /* Length of the SDU being received */
225   BT_HDR* p_rx_sdu;                 /* Buffer holding the SDU being received */
226   fixed_queue_t* waiting_for_ack_q; /* Buffers sent and waiting for peer to ack */
227   fixed_queue_t* srej_rcv_hold_q;   /* Buffers rcvd but held pending SREJ rsp */
228   fixed_queue_t* retrans_q;         /* Buffers being retransmitted */
229 
230   alarm_t* ack_timer;         /* Timer delaying RR */
231   alarm_t* mon_retrans_timer; /* Timer Monitor or Retransmission */
232 };
233 
234 struct tL2C_RCB {
235   bool in_use;
236   bool log_packets;
237   uint16_t psm;
238   uint16_t real_psm; /* This may be a dummy RCB for an o/b connection but */
239                      /* this is the real PSM that we need to connect to */
240   tL2CAP_APPL_INFO api;
241   tL2CAP_ERTM_INFO ertm_info;
242   tL2CAP_LE_CFG_INFO coc_cfg{};
243   uint16_t my_mtu;
244   uint16_t required_remote_mtu;
245 };
246 
247 #ifndef L2CAP_CBB_DEFAULT_DATA_RATE_BUFF_QUOTA
248 #define L2CAP_CBB_DEFAULT_DATA_RATE_BUFF_QUOTA 100
249 #endif
250 
251 struct tL2CAP_SEC_DATA {
252   uint16_t psm;
253   tBT_TRANSPORT transport;
254   bool is_originator;
255   tBTM_SEC_CALLBACK* p_callback;
256   void* p_ref_data;
257 };
258 
259 struct tL2C_LCB;
260 
261 /* Define a channel control block (CCB). There may be many channel control
262  * blocks between the same two Bluetooth devices (i.e. on the same link).
263  * Each CCB has unique local and remote CIDs. All channel control blocks on
264  * the same physical link and are chained together.
265  */
266 struct tL2C_CCB {
267   bool in_use;                       /* true when in use, false when not */
268   tL2C_CHNL_STATE chnl_state;        /* Channel state */
269   tL2CAP_LE_CFG_INFO local_conn_cfg; /* Our config for ble conn oriented channel */
270   tL2CAP_LE_CFG_INFO peer_conn_cfg;  /* Peer device config ble conn oriented channel */
271   bool is_first_seg;                 // Dtermine whether the received packet is the first
272                                      //   segment or not
273   BT_HDR* ble_sdu;                   /* Buffer for storing unassembled sdu*/
274   uint16_t ble_sdu_length;           /* Length of unassembled sdu length*/
275   tL2C_CCB* p_next_ccb;              /* Next CCB in the chain */
276   tL2C_CCB* p_prev_ccb;              /* Previous CCB in the chain */
277   tL2C_LCB* p_lcb;                   /* Link this CCB is assigned to */
278 
279   uint16_t local_cid;  /* Local CID */
280   uint16_t remote_cid; /* Remote CID */
281 
282   alarm_t* l2c_ccb_timer; /* CCB Timer Entry */
283 
284 #if (L2CAP_CONFORMANCE_TESTING == TRUE)
285   alarm_t* pts_config_delay_timer; /* Used to delay sending CONFIGURATION_REQ to overcome PTS issue
286                                     */
287 #endif
288 
289   tL2C_RCB* p_rcb; /* Registration CB for this Channel */
290 
291 #define IB_CFG_DONE 0x01
292 #define OB_CFG_DONE 0x02
293 #define RECONFIG_FLAG 0x04 /* True after initial configuration */
294 
295   uint8_t config_done;               /* Configuration flag word */
296   tL2CAP_CFG_RESULT remote_config_rsp_result; /* The config rsp result from remote */
297   uint8_t local_id;                  /* Transaction ID for local trans */
298   uint8_t remote_id;                 /* Transaction ID for local */
299 
300 #define CCB_FLAG_NO_RETRY 0x01     /* no more retry */
301 #define CCB_FLAG_SENT_PENDING 0x02 /* already sent pending response */
302   uint8_t flags;
303 
304   bool connection_initiator; /* true if we sent ConnectReq */
305 
306   tL2CAP_CFG_INFO our_cfg;  /* Our saved configuration options */
307   tL2CAP_CFG_INFO peer_cfg; /* Peer's saved configuration options */
308 
309   fixed_queue_t* xmit_hold_q; /* Transmit data hold queue */
310   bool cong_sent;             /* Set when congested status sent */
311   uint16_t buff_quota;        /* Buffer quota before sending congestion */
312 
313   tL2CAP_CHNL_PRIORITY ccb_priority;  /* Channel priority */
314   tL2CAP_CHNL_DATA_RATE tx_data_rate; /* Channel Tx data rate */
315   tL2CAP_CHNL_DATA_RATE rx_data_rate; /* Channel Rx data rate */
316 
317   /* Fields used for eL2CAP */
318   tL2CAP_ERTM_INFO ertm_info;
319   tL2C_FCRB fcrb;
320   uint16_t tx_mps; /* TX MPS adjusted based on current controller */
321   uint16_t max_rx_mtu;
322   uint8_t fcr_cfg_tries;          /* Max number of negotiation attempts */
323   bool peer_cfg_already_rejected; /* If mode rejected once, set to true */
324   bool out_cfg_fcr_present;       // true if cfg response should include fcr options
325 
326   bool is_flushable; /* true if channel is flushable */
327 
328   uint16_t fixed_chnl_idle_tout; /* Idle timeout to use for the fixed channel */
329   uint16_t tx_data_len;
330 
331   /* Number of LE frames that the remote can send to us (credit count in
332    * remote). Valid only for LE CoC */
333   uint16_t remote_credit_count;
334 
335   /* used to indicate that ECOC is used */
336   bool ecoc{false};
337   bool reconfig_started;
338 
339   struct {
340     struct {
341       unsigned bytes{0};
342       unsigned packets{0};
operatortL2C_CCB::__anon730a208b0b08::__anon730a208b0c08343       void operator()(unsigned bytes) {
344         this->bytes += bytes;
345         this->packets++;
346       }
347     } rx, tx;
348     struct {
349       struct {
350         unsigned bytes{0};
351         unsigned packets{0};
operatortL2C_CCB::__anon730a208b0b08::__anon730a208b0d08::__anon730a208b0e08352         void operator()(unsigned bytes) {
353           this->bytes += bytes;
354           this->packets++;
355         }
356       } rx, tx;
357     } dropped;
358   } metrics;
359 };
360 
361 /***********************************************************************
362  * Define a queue of linked CCBs.
363  */
364 struct tL2C_CCB_Q {
365   tL2C_CCB* p_first_ccb; /* The first channel in this queue */
366   tL2C_CCB* p_last_ccb;  /* The last  channel in this queue */
367 };
368 
369 /* Round-Robin service for the same priority channels */
370 #define L2CAP_NUM_CHNL_PRIORITY 3    /* Total number of priority group (high, medium, low)*/
371 #define L2CAP_CHNL_PRIORITY_WEIGHT 5 /* weight per priority for burst transmission quota */
372 #define L2CAP_GET_PRIORITY_QUOTA(pri) \
373   ((L2CAP_NUM_CHNL_PRIORITY - (pri)) * L2CAP_CHNL_PRIORITY_WEIGHT)
374 
375 /* CCBs within the same LCB are served in round robin with priority It will make
376  * sure that low priority channel (for example, HF signaling on RFCOMM) can be
377  * sent to the headset even if higher priority channel (for example, AV media
378  * channel) is congested.
379  */
380 
381 struct tL2C_RR_SERV {
382   tL2C_CCB* p_serve_ccb; /* current serving ccb within priority group */
383   tL2C_CCB* p_first_ccb; /* first ccb of priority group */
384   uint8_t num_ccb;       /* number of channels in priority group */
385   uint8_t quota;         /* burst transmission quota */
386 };
387 
388 enum tCONN_UPDATE_MASK : uint8_t {
389   /* disable update connection parameters */
390   L2C_BLE_CONN_UPDATE_DISABLE = (1u << 0),
391   /* new connection parameter to be set */
392   L2C_BLE_NEW_CONN_PARAM = (1u << 1),
393   /* waiting for connection update finished */
394   L2C_BLE_UPDATE_PENDING = (1u << 2),
395   /* not using default connection parameters */
396   L2C_BLE_NOT_DEFAULT_PARAM = (1u << 3),
397   /* Aggressive initial connection parameters are used */
398   L2C_BLE_AGGRESSIVE_INITIAL_PARAM = (1u << 4),
399 };
400 
401 /* Define a link control block. There is one link control block between
402  * this device and any other device (i.e. BD ADDR).
403  */
404 struct tL2C_LCB {
405   bool in_use; /* true when in use, false when not */
406   tL2C_LINK_STATE link_state;
407 
408   alarm_t* l2c_lcb_timer; /* Timer entry for timeout evt */
409 
410   //  This tracks if the link has ever either (a)
411   //  been used for a dynamic channel (EATT or L2CAP CoC), or (b) has been a
412   //  GATT client. If false, the local device is just a GATT server, so for
413   //  backwards compatibility we never do a link timeout.
414   bool with_active_local_clients{false};
415 
416 private:
417   uint16_t handle_; /* The handle used with LM */
418   friend void l2cu_set_lcb_handle(tL2C_LCB& p_lcb, uint16_t handle);
SetHandletL2C_LCB419   void SetHandle(uint16_t handle) { handle_ = handle; }
420 
421 public:
HandletL2C_LCB422   uint16_t Handle() const { return handle_; }
InvalidateHandletL2C_LCB423   void InvalidateHandle() { handle_ = HCI_INVALID_HANDLE; }
424 
425   tL2C_CCB_Q ccb_queue; /* Queue of CCBs on this LCB */
426 
427   tL2C_CCB* p_pending_ccb;   /* ccb of waiting channel during link disconnect */
428   alarm_t* info_resp_timer;  /* Timer entry for info resp timeout evt */
429   RawAddress remote_bd_addr; /* The BD address of the remote */
430 
431 private:
432   tHCI_ROLE link_role_{HCI_ROLE_CENTRAL}; /* Central or peripheral */
433   uint16_t conn_interval_;
434 
435 public:
LinkRoletL2C_LCB436   tHCI_ROLE LinkRole() const { return link_role_; }
IsLinkRoleCentraltL2C_LCB437   bool IsLinkRoleCentral() const { return link_role_ == HCI_ROLE_CENTRAL; }
IsLinkRolePeripheraltL2C_LCB438   bool IsLinkRolePeripheral() const { return link_role_ == HCI_ROLE_PERIPHERAL; }
SetLinkRoleAsCentraltL2C_LCB439   void SetLinkRoleAsCentral() { link_role_ = HCI_ROLE_CENTRAL; }
SetLinkRoleAsPeripheraltL2C_LCB440   void SetLinkRoleAsPeripheral() { link_role_ = HCI_ROLE_PERIPHERAL; }
ConnIntervaltL2C_LCB441   uint16_t ConnInterval() const { return conn_interval_; }
SetConnIntervaltL2C_LCB442   void SetConnInterval(uint16_t conn_interval) { conn_interval_ = conn_interval; }
443 
444   uint8_t signal_id;     /* Signalling channel id */
445   uint8_t cur_echo_id;   /* Current id value for echo request */
446   uint16_t idle_timeout; /* Idle timeout */
447 
448 private:
449   bool is_bonding_{false}; /* True - link active only for bonding */
450 
451 public:
IsBondingtL2C_LCB452   bool IsBonding() const { return is_bonding_; }
SetBondingtL2C_LCB453   void SetBonding() { is_bonding_ = true; }
ResetBondingtL2C_LCB454   void ResetBonding() { is_bonding_ = false; }
455 
456   uint16_t link_xmit_quota; /* Num outstanding pkts allowed */
is_round_robin_schedulingtL2C_LCB457   bool is_round_robin_scheduling() const { return link_xmit_quota == 0; }
458 
459   uint16_t sent_not_acked; /* Num packets sent but not acked */
update_outstanding_packetstL2C_LCB460   void update_outstanding_packets(uint16_t packets_acked) {
461     if (sent_not_acked > packets_acked) {
462       sent_not_acked -= packets_acked;
463     } else {
464       sent_not_acked = 0;
465     }
466   }
467 
468   bool w4_info_rsp;         /* true when info request is active */
469   uint32_t peer_ext_fea;    /* Peer's extended features mask */
470   list_t* link_xmit_data_q; /* Link transmit data buffer queue */
471 
472   uint8_t peer_chnl_mask[L2CAP_FIXED_CHNL_ARRAY_SIZE];
473 
474   tL2CAP_PRIORITY acl_priority;
is_normal_prioritytL2C_LCB475   bool is_normal_priority() const { return acl_priority == L2CAP_PRIORITY_NORMAL; }
is_high_prioritytL2C_LCB476   bool is_high_priority() const { return acl_priority == L2CAP_PRIORITY_HIGH; }
set_prioritytL2C_LCB477   bool set_priority(tL2CAP_PRIORITY priority) {
478     if (acl_priority != priority) {
479       acl_priority = priority;
480       return true;
481     }
482     return false;
483   }
484 
485   bool use_latency_mode = false;
486   tL2CAP_LATENCY preset_acl_latency = L2CAP_LATENCY_NORMAL;
487   tL2CAP_LATENCY acl_latency = L2CAP_LATENCY_NORMAL;
is_normal_latencytL2C_LCB488   bool is_normal_latency() const { return acl_latency == L2CAP_LATENCY_NORMAL; }
is_low_latencytL2C_LCB489   bool is_low_latency() const { return acl_latency == L2CAP_LATENCY_LOW; }
set_latencytL2C_LCB490   bool set_latency(tL2CAP_LATENCY latency) {
491     if (acl_latency != latency) {
492       acl_latency = latency;
493       return true;
494     }
495     return false;
496   }
497 
498   tL2C_CCB* p_fixed_ccbs[L2CAP_NUM_FIXED_CHNLS];
499   std::vector<uint16_t> suspended;  // List of fixed channel CIDs which are suspended but not
500                                     //  removed
501 
502 private:
503   tHCI_REASON disc_reason_{HCI_ERR_UNDEFINED};
504 
505 public:
DisconnectReasontL2C_LCB506   tHCI_REASON DisconnectReason() const { return disc_reason_; }
SetDisconnectReasontL2C_LCB507   void SetDisconnectReason(tHCI_REASON disc_reason) { disc_reason_ = disc_reason; }
508 
509   tBT_TRANSPORT transport;
is_transport_br_edrtL2C_LCB510   bool is_transport_br_edr() const { return transport == BT_TRANSPORT_BR_EDR; }
is_transport_bletL2C_LCB511   bool is_transport_ble() const { return transport == BT_TRANSPORT_LE; }
512 
513   uint16_t tx_data_len;            /* tx data length used in data length extension */
514   fixed_queue_t* le_sec_pending_q;  // LE coc channels waiting for security check
515                                     //   completion
516   uint8_t sec_act;
517 
518   uint8_t conn_update_mask;
519 
520   bool conn_update_blocked_by_service_discovery;
521   bool conn_update_blocked_by_profile_connection;
522 
523   uint16_t min_interval; /* parameters as requested by peripheral */
524   uint16_t max_interval;
525   uint16_t latency;
526   uint16_t timeout;
527   uint16_t min_ce_len;
528   uint16_t max_ce_len;
529 
530 #define L2C_BLE_SUBRATE_REQ_DISABLE 0x1  // disable subrate req
531 #define L2C_BLE_NEW_SUBRATE_PARAM 0x2    // new subrate req parameter to be set
532 #define L2C_BLE_SUBRATE_REQ_PENDING 0x4  // waiting for subrate to be completed
533 
534   /* subrate req params */
535   uint16_t subrate_min;
536   uint16_t subrate_max;
537   uint16_t max_latency;
538   uint16_t cont_num;
539   uint16_t supervision_tout;
540 
541   uint8_t subrate_req_mask;
542 
543   /* each priority group is limited burst transmission */
544   /* round robin service for the same priority channels */
545   tL2C_RR_SERV rr_serv[L2CAP_NUM_CHNL_PRIORITY];
546   uint8_t rr_pri; /* current serving priority group */
547 
548   /* Pending ECOC reconfiguration data */
549   tL2CAP_LE_CFG_INFO pending_ecoc_reconfig_cfg;
550   uint8_t pending_ecoc_reconfig_cnt;
551 
552   /* This is to keep list of local cids use in the
553    * credit based connection response.
554    */
555   uint16_t pending_ecoc_connection_cids[L2CAP_CREDIT_BASED_MAX_CIDS];
556   uint8_t pending_ecoc_conn_cnt;
557 
558   uint16_t pending_lead_cid;
559   tL2CAP_CONN pending_l2cap_result;
560 
number_of_active_dynamic_channelstL2C_LCB561   unsigned number_of_active_dynamic_channels() const {
562     unsigned cnt = 0;
563     const tL2C_CCB* cur = ccb_queue.p_first_ccb;
564     while (cur != nullptr) {
565       cnt++;
566       cur = cur->p_next_ccb;
567     }
568     return cnt;
569   }
570 };
571 
572 /* Define the L2CAP control structure
573  */
574 struct tL2C_CB {
575   uint16_t controller_xmit_window; /* Total ACL window for all links */
576 
577   uint16_t round_robin_quota;   /* Round-robin link quota */
578   uint16_t round_robin_unacked; /* Round-robin unacked */
is_classic_round_robin_quota_availabletL2C_CB579   bool is_classic_round_robin_quota_available() const {
580     return round_robin_unacked < round_robin_quota;
581   }
update_outstanding_classic_packetstL2C_CB582   void update_outstanding_classic_packets(uint16_t num_packets_acked) {
583     if (round_robin_unacked > num_packets_acked) {
584       round_robin_unacked -= num_packets_acked;
585     } else {
586       round_robin_unacked = 0;
587     }
588   }
589 
590   bool check_round_robin; /* Do a round robin check */
591 
592   bool is_cong_cback_context;
593 
594   tL2C_LCB lcb_pool[MAX_L2CAP_LINKS];    /* Link Control Block pool */
595   tL2C_CCB ccb_pool[MAX_L2CAP_CHANNELS]; /* Channel Control Block pool */
596   tL2C_RCB rcb_pool[MAX_L2CAP_CLIENTS];  /* Registration info pool */
597 
598   tL2C_CCB* p_free_ccb_first; /* Pointer to first free CCB */
599   tL2C_CCB* p_free_ccb_last;  /* Pointer to last  free CCB */
600 
601   bool disallow_switch;     /* false, to allow switch at create conn */
602   uint16_t num_lm_acl_bufs; /* # of ACL buffers on controller */
603   uint16_t idle_timeout;    /* Idle timeout */
604 
605   tL2C_LCB* p_cur_hcit_lcb; /* Current HCI Transport buffer */
606   uint16_t num_used_lcbs;   /* Number of active link control blocks */
607 
608   uint16_t non_flushable_pbf;  // L2CAP_PKT_START_NON_FLUSHABLE if controller
609                                //   supports
610   /* Otherwise, L2CAP_PKT_START */
611 
612 #if (L2CAP_CONFORMANCE_TESTING == TRUE)
613   uint32_t test_info_resp; /* Conformance testing needs a dynamic response */
614 #endif
615 
616   tL2CAP_FIXED_CHNL_REG fixed_reg[L2CAP_NUM_FIXED_CHNLS]; /* Reg info for fixed channels */
617 
618   uint16_t num_ble_links_active;                       /* Number of LE links active */
619   uint16_t controller_le_xmit_window;                  /* Total ACL window for all links */
620   tL2C_BLE_FIXED_CHNLS_MASK l2c_ble_fixed_chnls_mask;  // LE fixed channels mask
621   uint16_t num_lm_ble_bufs;                            /* # of ACL buffers on controller */
622   uint16_t ble_round_robin_quota;                      /* Round-robin link quota */
623   uint16_t ble_round_robin_unacked;                    /* Round-robin unacked */
is_ble_round_robin_quota_availabletL2C_CB624   bool is_ble_round_robin_quota_available() const {
625     return ble_round_robin_unacked < ble_round_robin_quota;
626   }
update_outstanding_le_packetstL2C_CB627   void update_outstanding_le_packets(uint16_t num_packets_acked) {
628     if (ble_round_robin_unacked > num_packets_acked) {
629       ble_round_robin_unacked -= num_packets_acked;
630     } else {
631       ble_round_robin_unacked = 0;
632     }
633   }
634 
635   bool ble_check_round_robin;                   /* Do a round robin check */
636   tL2C_RCB ble_rcb_pool[BLE_MAX_L2CAP_CLIENTS]; /* Registration info pool */
637 
638   uint16_t le_dyn_psm;                            /* Next LE dynamic PSM value to try to assign */
639   bool le_dyn_psm_assigned[LE_DYNAMIC_PSM_RANGE]; /* Table of assigned LE PSM */
640 };
641 
642 /* Define a structure that contains the information about a connection.
643  * This structure is used to pass between functions, and not all the
644  * fields will always be filled in.
645  */
646 struct tL2C_CONN_INFO {
647   RawAddress bd_addr;          /* Remote BD address */
648   tHCI_STATUS hci_status;      /* Connection status */
649   uint16_t psm;                /* PSM of the connection */
650   tL2CAP_CONN l2cap_result;    /* L2CAP result */
651   uint16_t l2cap_status;       /* L2CAP status */
652   uint16_t remote_cid;         /* Remote CID */
653   std::vector<uint16_t> lcids; /* Used when credit based is used*/
654   uint16_t peer_mtu;           /* Peer MTU */
655 };
656 
657 struct tL2C_AVDT_CHANNEL_INFO {
658   bool is_active;     /* is channel active */
659   uint16_t local_cid; /* Remote CID */
660   tL2C_CCB* p_ccb;    /* CCB */
661 };
662 
663 typedef void(tL2C_FCR_MGMT_EVT_HDLR)(uint8_t, tL2C_CCB*);
664 
665 /* Necessary info for postponed TX completion callback
666  */
667 struct tL2C_TX_COMPLETE_CB_INFO {
668   uint16_t local_cid;
669   uint16_t num_sdu;
670   tL2CA_TX_COMPLETE_CB* cb;
671 };
672 
673 /* Number of ACL buffers to use for high priority channel
674  */
675 #define L2CAP_HIGH_PRI_MIN_XMIT_QUOTA_A (L2CAP_HIGH_PRI_MIN_XMIT_QUOTA)
676 
677 /* L2CAP global data
678  ***********************************
679  */
680 extern tL2C_CB l2cb;
681 
682 /* Functions provided by l2c_main.cc
683  ***********************************
684  */
685 
686 void l2c_receive_hold_timer_timeout(void* data);
687 void l2c_ccb_timer_timeout(void* data);
688 void l2c_lcb_timer_timeout(void* data);
689 void l2c_fcrb_ack_timer_timeout(void* data);
690 tL2CAP_DW_RESULT l2c_data_write(uint16_t cid, BT_HDR* p_data, uint16_t flag);
691 void l2c_acl_flush(uint16_t handle);
692 
693 tL2C_LCB* l2cu_allocate_lcb(const RawAddress& p_bd_addr, bool is_bonding, tBT_TRANSPORT transport);
694 void l2cu_release_lcb(tL2C_LCB* p_lcb);
695 tL2C_LCB* l2cu_find_lcb_by_bd_addr(const RawAddress& p_bd_addr, tBT_TRANSPORT transport);
696 tL2C_LCB* l2cu_find_lcb_by_handle(uint16_t handle);
697 
698 bool l2cu_set_acl_priority(const RawAddress& bd_addr, tL2CAP_PRIORITY priority,
699                            bool reset_after_rs);
700 bool l2cu_set_acl_latency(const RawAddress& bd_addr, tL2CAP_LATENCY latency);
701 
702 void l2cu_enqueue_ccb(tL2C_CCB* p_ccb);
703 void l2cu_dequeue_ccb(tL2C_CCB* p_ccb);
704 void l2cu_change_pri_ccb(tL2C_CCB* p_ccb, tL2CAP_CHNL_PRIORITY priority);
705 
706 tL2C_CCB* l2cu_allocate_ccb(tL2C_LCB* p_lcb, uint16_t cid, bool is_eatt = false);
707 void l2cu_release_ccb(tL2C_CCB* p_ccb);
708 void l2cu_fixed_channel_restore(tL2C_LCB* p_lcb, uint16_t fixed_cid);
709 bool l2cu_fixed_channel_suspended(tL2C_LCB* p_lcb, uint16_t fixed_cid);
710 void l2cu_fixed_channel_data_cb(tL2C_LCB* p_lcb, uint16_t fixed_cid, BT_HDR* p_buf);
711 tL2C_CCB* l2cu_find_ccb_by_cid(tL2C_LCB* p_lcb, uint16_t local_cid);
712 tL2C_CCB* l2cu_find_ccb_by_remote_cid(tL2C_LCB* p_lcb, uint16_t remote_cid);
713 bool l2c_is_cmd_rejected(uint8_t cmd_code, uint8_t id, tL2C_LCB* p_lcb);
714 
715 void l2cu_send_peer_cmd_reject(tL2C_LCB* p_lcb, uint16_t reason, uint8_t rem_id, uint16_t p1,
716                                uint16_t p2);
717 void l2cu_send_peer_connect_req(tL2C_CCB* p_ccb);
718 void l2cu_send_peer_connect_rsp(tL2C_CCB* p_ccb, tL2CAP_CONN result, uint16_t status);
719 void l2cu_send_peer_config_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg);
720 void l2cu_send_peer_config_rsp(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg);
721 void l2cu_send_peer_config_rej(tL2C_CCB* p_ccb, uint8_t* p_data, uint16_t data_len,
722                                uint16_t rej_len);
723 void l2cu_send_peer_disc_req(tL2C_CCB* p_ccb);
724 void l2cu_send_peer_disc_rsp(tL2C_LCB* p_lcb, uint8_t remote_id, uint16_t local_cid,
725                              uint16_t remote_cid);
726 void l2cu_send_peer_echo_rsp(tL2C_LCB* p_lcb, uint8_t id, uint8_t* p_data, uint16_t data_len);
727 void l2cu_send_peer_info_rsp(tL2C_LCB* p_lcb, uint8_t id, uint16_t info_type);
728 void l2cu_reject_connection(tL2C_LCB* p_lcb, uint16_t remote_cid, uint8_t rem_id,
729                             tL2CAP_CONN result);
730 void l2cu_send_peer_info_req(tL2C_LCB* p_lcb, uint16_t info_type);
731 void l2cu_set_acl_hci_header(BT_HDR* p_buf, tL2C_CCB* p_ccb);
732 void l2cu_check_channel_congestion(tL2C_CCB* p_ccb);
733 void l2cu_disconnect_chnl(tL2C_CCB* p_ccb);
734 
735 void l2cu_tx_complete(tL2C_TX_COMPLETE_CB_INFO* p_cbi);
736 
737 void l2cu_send_peer_ble_par_req(tL2C_LCB* p_lcb, uint16_t min_int, uint16_t max_int,
738                                 uint16_t latency, uint16_t timeout);
739 void l2cu_send_peer_ble_par_rsp(tL2C_LCB* p_lcb, tL2CAP_CFG_RESULT reason, uint8_t rem_id);
740 void l2cu_reject_ble_connection(tL2C_CCB* p_ccb, uint8_t rem_id, tL2CAP_LE_RESULT_CODE result);
741 void l2cu_reject_credit_based_conn_req(tL2C_LCB* p_lcb, uint8_t rem_id, uint8_t num_of_channels,
742                                        tL2CAP_LE_RESULT_CODE result);
743 void l2cu_reject_ble_coc_connection(tL2C_LCB* p_lcb, uint8_t rem_id, tL2CAP_LE_RESULT_CODE result);
744 void l2cu_send_peer_ble_credit_based_conn_res(tL2C_CCB* p_ccb, tL2CAP_LE_RESULT_CODE result);
745 void l2cu_send_peer_credit_based_conn_res(tL2C_CCB* p_ccb, std::vector<uint16_t>& accepted_lcids,
746                                           tL2CAP_LE_RESULT_CODE result);
747 
748 void l2cu_send_peer_ble_credit_based_conn_req(tL2C_CCB* p_ccb);
749 void l2cu_send_peer_credit_based_conn_req(tL2C_CCB* p_ccb);
750 
751 void l2cu_send_ble_reconfig_rsp(tL2C_LCB* p_lcb, uint8_t rem_id, tL2CAP_RECONFIG_RESULT result);
752 void l2cu_send_credit_based_reconfig_req(tL2C_CCB* p_ccb, tL2CAP_LE_CFG_INFO* p_data);
753 
754 void l2cu_send_peer_ble_flow_control_credit(tL2C_CCB* p_ccb, uint16_t credit_value);
755 void l2cu_send_peer_ble_credit_based_disconn_req(tL2C_CCB* p_ccb);
756 
757 bool l2cu_initialize_fixed_ccb(tL2C_LCB* p_lcb, uint16_t fixed_cid);
758 void l2cu_no_dynamic_ccbs(tL2C_LCB* p_lcb);
759 void l2cu_process_fixed_chnl_resp(tL2C_LCB* p_lcb);
760 bool l2cu_is_ccb_active(tL2C_CCB* p_ccb);
761 void l2cu_set_lcb_handle(tL2C_LCB& p_lcb, uint16_t handle);
762 tL2CAP_CONN le_result_to_l2c_conn(tL2CAP_LE_RESULT_CODE result);
763 
764 /* Functions provided for Broadcom Aware
765  ***************************************
766  */
767 
768 tL2C_RCB* l2cu_allocate_rcb(uint16_t psm);
769 tL2C_RCB* l2cu_find_rcb_by_psm(uint16_t psm);
770 void l2cu_release_rcb(tL2C_RCB* p_rcb);
771 void l2cu_release_ble_rcb(tL2C_RCB* p_rcb);
772 tL2C_RCB* l2cu_allocate_ble_rcb(uint16_t psm);
773 tL2C_RCB* l2cu_find_ble_rcb_by_psm(uint16_t psm);
774 
775 uint8_t l2cu_get_fcs_len(tL2C_CCB* p_ccb);
776 uint8_t l2cu_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg);
777 void l2cu_process_peer_cfg_rsp(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg);
778 void l2cu_process_our_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg);
779 void l2cu_process_our_cfg_rsp(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg);
780 
781 tL2C_LCB* l2cu_find_lcb_by_state(tL2C_LINK_STATE state);
782 bool l2cu_lcb_disconnecting(void);
783 
784 void l2cu_create_conn_br_edr(tL2C_LCB* p_lcb);
785 bool l2cu_create_conn_le(tL2C_LCB* p_lcb);
786 void l2cu_create_conn_after_switch(tL2C_LCB* p_lcb);
787 void l2cu_adjust_out_mps(tL2C_CCB* p_ccb);
788 
789 /* Functions provided by l2c_link.cc
790  ***********************************
791  */
792 
793 void l2c_link_timeout(tL2C_LCB* p_lcb);
794 void l2c_info_resp_timer_timeout(void* data);
795 void l2c_link_check_send_pkts(tL2C_LCB* p_lcb, uint16_t local_cid, BT_HDR* p_buf);
796 void l2c_link_adjust_allocation(void);
797 void l2c_link_hci_conn_comp(tHCI_STATUS status, uint16_t handle, const RawAddress& p_bda);
798 void l2c_link_sec_comp(RawAddress p_bda, tBT_TRANSPORT transport, void* p_ref_data,
799                        tBTM_STATUS status);
800 void l2c_link_adjust_chnl_allocation(void);
801 
802 #if (L2CAP_CONFORMANCE_TESTING == TRUE)
803 /* Used only for conformance testing */
804 void l2cu_set_info_rsp_mask(uint32_t mask);
805 #endif
806 
807 /* Functions provided by l2c_csm.cc
808  ***********************************
809  */
810 void l2c_csm_execute(tL2C_CCB* p_ccb, tL2CEVT event, void* p_data);
811 
812 void l2c_enqueue_peer_data(tL2C_CCB* p_ccb, BT_HDR* p_buf);
813 
814 /* Functions provided by l2c_fcr.cc
815  ***********************************
816  */
817 void l2c_fcr_cleanup(tL2C_CCB* p_ccb);
818 void l2c_fcr_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf);
819 void l2c_fcr_proc_tout(tL2C_CCB* p_ccb);
820 void l2c_fcr_proc_ack_tout(tL2C_CCB* p_ccb);
821 void l2c_fcr_send_S_frame(tL2C_CCB* p_ccb, uint16_t function_code, uint16_t pf_bit);
822 BT_HDR* l2c_fcr_clone_buf(BT_HDR* p_buf, uint16_t new_offset, uint16_t no_of_bytes);
823 bool l2c_fcr_is_flow_controlled(tL2C_CCB* p_ccb);
824 BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, uint16_t max_packet_length);
825 void l2c_fcr_start_timer(tL2C_CCB* p_ccb);
826 void l2c_lcc_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf);
827 BT_HDR* l2c_lcc_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, bool* last_piece_of_sdu);
828 
829 /* Configuration negotiation */
830 uint8_t l2c_fcr_chk_chan_modes(tL2C_CCB* p_ccb);
831 
832 void l2c_fcr_adj_our_rsp_options(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_peer_cfg);
833 bool l2c_fcr_renegotiate_chan(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg);
834 uint8_t l2c_fcr_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg);
835 void l2c_fcr_adj_monitor_retran_timeout(tL2C_CCB* p_ccb);
836 void l2c_fcr_stop_timer(tL2C_CCB* p_ccb);
837 
838 /* Functions provided by l2c_ble.cc
839  ***********************************
840  */
841 
842 bool l2cble_create_conn(tL2C_LCB* p_lcb);
843 void l2cble_process_sig_cmd(tL2C_LCB* p_lcb, uint8_t* p, uint16_t pkt_len);
844 void l2c_ble_link_adjust_allocation(void);
845 void l2cble_start_conn_update(tL2C_LCB* p_lcb);
846 void l2cble_credit_based_conn_req(tL2C_CCB* p_ccb);
847 void l2cble_credit_based_conn_res(tL2C_CCB* p_ccb, tL2CAP_LE_RESULT_CODE result);
848 void l2cble_send_peer_disc_req(tL2C_CCB* p_ccb);
849 void l2cble_send_flow_control_credit(tL2C_CCB* p_ccb, uint16_t credit_value);
850 tL2CAP_LE_RESULT_CODE l2ble_sec_access_req(const RawAddress& bd_addr, uint16_t psm,
851                                            bool is_originator, tBTM_SEC_CALLBACK* p_callback,
852                                            void* p_ref_data);
853 
854 void l2cble_update_data_length(tL2C_LCB* p_lcb);
855 
856 void l2cu_process_fixed_disc_cback(tL2C_LCB* p_lcb);
857 
858 void l2cble_process_subrate_change_evt(uint16_t handle, uint8_t status, uint16_t subrate_factor,
859                                        uint16_t peripheral_latency, uint16_t cont_num,
860                                        uint16_t timeout);
861 
862 namespace std {
863 template <>
864 struct formatter<tL2C_LINK_STATE> : enum_formatter<tL2C_LINK_STATE> {};
865 template <>
866 struct formatter<tL2CEVT> : enum_formatter<tL2CEVT> {};
867 template <>
868 struct formatter<tL2C_CHNL_STATE> : enum_formatter<tL2C_CHNL_STATE> {};
869 }  // namespace std
870