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