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