• Home
  • History
  • Annotate
  • 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 the L2CAP API code
22  *
23  ******************************************************************************/
24 
25 #define LOG_TAG "bt_l2cap"
26 
27 #include <base/logging.h>
28 #include <base/strings/stringprintf.h>
29 #include <cstdint>
30 #include <string>
31 
32 #include "btm_sec.h"
33 #include "device/include/controller.h"  // TODO Remove
34 #include "main/shim/l2c_api.h"
35 #include "main/shim/shim.h"
36 #include "osi/include/log.h"
37 #include "stack/include/l2c_api.h"
38 #include "stack/l2cap/l2c_int.h"
39 
40 void btsnd_hcic_enhanced_flush(uint16_t handle,
41                                uint8_t packet_type);  // TODO Remove
42 
43 using base::StringPrintf;
44 
45 tBT_TRANSPORT l2c_get_transport_from_fixed_cid(uint16_t fixed_cid) {
46   if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID)
47     return BT_TRANSPORT_LE;
48   return BT_TRANSPORT_BR_EDR;
49 }
50 
51 uint16_t L2CA_Register2(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info,
52                         bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info,
53                         uint16_t my_mtu, uint16_t required_remote_mtu,
54                         uint16_t sec_level) {
55   auto ret = L2CA_Register(psm, p_cb_info, enable_snoop, p_ertm_info, my_mtu,
56                            required_remote_mtu, sec_level);
57   BTM_SetSecurityLevel(false, "", 0, sec_level, psm, 0, 0);
58   return ret;
59 }
60 
61 /*******************************************************************************
62  *
63  * Function         L2CA_Register
64  *
65  * Description      Other layers call this function to register for L2CAP
66  *                  services.
67  *
68  * Returns          PSM to use or zero if error. Typically, the PSM returned
69  *                  is the same as was passed in, but for an outgoing-only
70  *                  connection to a dynamic PSM, a "virtual" PSM is returned
71  *                  and should be used in the calls to L2CA_ConnectReq(),
72  *                  L2CA_ErtmConnectReq() and L2CA_Deregister()
73  *
74  ******************************************************************************/
75 uint16_t L2CA_Register(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info,
76                        bool enable_snoop, tL2CAP_ERTM_INFO* p_ertm_info,
77                        uint16_t my_mtu, uint16_t required_remote_mtu,
78                        uint16_t sec_level) {
79   if (bluetooth::shim::is_gd_l2cap_enabled()) {
80     return bluetooth::shim::L2CA_Register(psm, p_cb_info, enable_snoop,
81                                           p_ertm_info, my_mtu,
82                                           required_remote_mtu, sec_level);
83   }
84 
85   const bool config_cfm_cb = (p_cb_info.pL2CA_ConfigCfm_Cb != nullptr);
86   const bool config_ind_cb = (p_cb_info.pL2CA_ConfigInd_Cb != nullptr);
87   const bool data_ind_cb = (p_cb_info.pL2CA_DataInd_Cb != nullptr);
88   const bool disconnect_ind_cb = (p_cb_info.pL2CA_DisconnectInd_Cb != nullptr);
89 
90   tL2C_RCB* p_rcb;
91   uint16_t vpsm = psm;
92 
93   /* Verify that the required callback info has been filled in
94   **      Note:  Connection callbacks are required but not checked
95   **             for here because it is possible to be only a client
96   **             or only a server.
97   */
98   if (!config_cfm_cb || !data_ind_cb || !disconnect_ind_cb) {
99     LOG_ERROR(
100         "L2CAP - no cb registering PSM: 0x%04x cfg_cfm:%u cfg_ind:%u"
101         " data_ind:%u discon_int:%u",
102         psm, config_cfm_cb, config_ind_cb, data_ind_cb, disconnect_ind_cb);
103     return (0);
104   }
105 
106   /* Verify PSM is valid */
107   if (L2C_INVALID_PSM(psm)) {
108     LOG_ERROR("L2CAP - invalid PSM value, PSM: 0x%04x", psm);
109     return (0);
110   }
111 
112   /* Check if this is a registration for an outgoing-only connection to */
113   /* a dynamic PSM. If so, allocate a "virtual" PSM for the app to use. */
114   if ((psm >= 0x1001) && (p_cb_info.pL2CA_ConnectInd_Cb == NULL)) {
115     for (vpsm = 0x1002; vpsm < 0x8000; vpsm += 2) {
116       p_rcb = l2cu_find_rcb_by_psm(vpsm);
117       if (p_rcb == NULL) break;
118     }
119 
120     LOG_DEBUG("L2CAP - Real PSM: 0x%04x  Virtual PSM: 0x%04x", psm, vpsm);
121   }
122 
123   /* If registration block already there, just overwrite it */
124   p_rcb = l2cu_find_rcb_by_psm(vpsm);
125   if (p_rcb == NULL) {
126     p_rcb = l2cu_allocate_rcb(vpsm);
127     if (p_rcb == NULL) {
128       LOG_WARN("L2CAP - no RCB available, PSM: 0x%04x  vPSM: 0x%04x", psm,
129                vpsm);
130       return (0);
131     }
132   }
133 
134   LOG_INFO("L2CAP Registered service classic PSM: 0x%04x", psm);
135   p_rcb->log_packets = enable_snoop;
136   p_rcb->api = p_cb_info;
137   p_rcb->real_psm = psm;
138   p_rcb->ertm_info = p_ertm_info == nullptr
139                          ? tL2CAP_ERTM_INFO{L2CAP_FCR_BASIC_MODE}
140                          : *p_ertm_info;
141   p_rcb->my_mtu = my_mtu;
142   p_rcb->required_remote_mtu =
143       std::max<uint16_t>(required_remote_mtu, L2CAP_MIN_MTU);
144 
145   return (vpsm);
146 }
147 
148 /*******************************************************************************
149  *
150  * Function         L2CA_Deregister
151  *
152  * Description      Other layers call this function to de-register for L2CAP
153  *                  services.
154  *
155  * Returns          void
156  *
157  ******************************************************************************/
158 void L2CA_Deregister(uint16_t psm) {
159   if (bluetooth::shim::is_gd_l2cap_enabled()) {
160     return bluetooth::shim::L2CA_Deregister(psm);
161   }
162 
163   tL2C_RCB* p_rcb;
164   tL2C_CCB* p_ccb;
165   tL2C_LCB* p_lcb;
166   int ii;
167 
168   L2CAP_TRACE_API("L2CAP - L2CA_Deregister() called for PSM: 0x%04x", psm);
169 
170   p_rcb = l2cu_find_rcb_by_psm(psm);
171   if (p_rcb != NULL) {
172     p_lcb = &l2cb.lcb_pool[0];
173     for (ii = 0; ii < MAX_L2CAP_LINKS; ii++, p_lcb++) {
174       if (p_lcb->in_use) {
175         p_ccb = p_lcb->ccb_queue.p_first_ccb;
176         if ((p_ccb == NULL) || (p_lcb->link_state == LST_DISCONNECTING)) {
177           continue;
178         }
179 
180         if ((p_ccb->in_use) &&
181             ((p_ccb->chnl_state == CST_W4_L2CAP_DISCONNECT_RSP) ||
182              (p_ccb->chnl_state == CST_W4_L2CA_DISCONNECT_RSP))) {
183           continue;
184         }
185 
186         if (p_ccb->p_rcb == p_rcb) {
187           l2c_csm_execute(p_ccb, L2CEVT_L2CA_DISCONNECT_REQ, NULL);
188         }
189       }
190     }
191     l2cu_release_rcb(p_rcb);
192   } else {
193     L2CAP_TRACE_WARNING("L2CAP - PSM: 0x%04x not found for deregistration",
194                         psm);
195   }
196 }
197 
198 /*******************************************************************************
199  *
200  * Function         L2CA_AllocateLePSM
201  *
202  * Description      To find an unused LE PSM for L2CAP services.
203  *
204  * Returns          LE_PSM to use if success. Otherwise returns 0.
205  *
206  ******************************************************************************/
207 uint16_t L2CA_AllocateLePSM(void) {
208   if (bluetooth::shim::is_gd_l2cap_enabled()) {
209     return bluetooth::shim::L2CA_AllocateLePSM();
210   }
211 
212   bool done = false;
213   uint16_t psm = l2cb.le_dyn_psm;
214   uint16_t count = 0;
215 
216   L2CAP_TRACE_API("%s: last psm=%d", __func__, psm);
217   while (!done) {
218     count++;
219     if (count > LE_DYNAMIC_PSM_RANGE) {
220       L2CAP_TRACE_ERROR("%s: Out of free BLE PSM", __func__);
221       return 0;
222     }
223 
224     psm++;
225     if (psm > LE_DYNAMIC_PSM_END) {
226       psm = LE_DYNAMIC_PSM_START;
227     }
228 
229     if (!l2cb.le_dyn_psm_assigned[psm - LE_DYNAMIC_PSM_START]) {
230       /* make sure the newly allocated psm is not used right now */
231       if (l2cu_find_ble_rcb_by_psm(psm)) {
232         L2CAP_TRACE_WARNING("%s: supposedly-free PSM=%d have allocated rcb!",
233                             __func__, psm);
234         continue;
235       }
236 
237       l2cb.le_dyn_psm_assigned[psm - LE_DYNAMIC_PSM_START] = true;
238       L2CAP_TRACE_DEBUG("%s: assigned PSM=%d", __func__, psm);
239       done = true;
240       break;
241     }
242   }
243   l2cb.le_dyn_psm = psm;
244 
245   return (psm);
246 }
247 
248 /*******************************************************************************
249  *
250  * Function         L2CA_FreeLePSM
251  *
252  * Description      Free an assigned LE PSM.
253  *
254  * Returns          void
255  *
256  ******************************************************************************/
257 void L2CA_FreeLePSM(uint16_t psm) {
258   if (bluetooth::shim::is_gd_l2cap_enabled()) {
259     return bluetooth::shim::L2CA_FreeLePSM(psm);
260   }
261 
262   L2CAP_TRACE_API("%s: to free psm=%d", __func__, psm);
263 
264   if ((psm < LE_DYNAMIC_PSM_START) || (psm > LE_DYNAMIC_PSM_END)) {
265     L2CAP_TRACE_ERROR("%s: Invalid PSM=%d value!", __func__, psm);
266     return;
267   }
268 
269   if (!l2cb.le_dyn_psm_assigned[psm - LE_DYNAMIC_PSM_START]) {
270     L2CAP_TRACE_WARNING("%s: PSM=%d was not allocated!", __func__, psm);
271   }
272   l2cb.le_dyn_psm_assigned[psm - LE_DYNAMIC_PSM_START] = false;
273 }
274 
275 uint16_t L2CA_ConnectReq2(uint16_t psm, const RawAddress& p_bd_addr,
276                           uint16_t sec_level) {
277   BTM_SetSecurityLevel(true, "", 0, sec_level, psm, 0, 0);
278   return L2CA_ConnectReq(psm, p_bd_addr);
279 }
280 
281 /*******************************************************************************
282  *
283  * Function         L2CA_ConnectReq
284  *
285  * Description      Higher layers call this function to create an L2CAP
286  *                  connection.
287  *                  Note that the connection is not established at this time,
288  *                  but connection establishment gets started. The callback
289  *                  will be invoked when connection establishes or fails.
290  *
291  * Returns          the CID of the connection, or 0 if it failed to start
292  *
293  ******************************************************************************/
294 uint16_t L2CA_ConnectReq(uint16_t psm, const RawAddress& p_bd_addr) {
295   if (bluetooth::shim::is_gd_l2cap_enabled()) {
296     return bluetooth::shim::L2CA_ConnectReq(psm, p_bd_addr);
297   }
298 
299   VLOG(1) << __func__ << "BDA " << p_bd_addr
300           << StringPrintf(" PSM: 0x%04x", psm);
301 
302   /* Fail if we have not established communications with the controller */
303   if (!BTM_IsDeviceUp()) {
304     LOG(WARNING) << __func__ << ": BTU not ready";
305     return 0;
306   }
307   /* Fail if the PSM is not registered */
308   tL2C_RCB* p_rcb = l2cu_find_rcb_by_psm(psm);
309   if (p_rcb == nullptr) {
310     LOG(WARNING) << __func__ << ": no RCB, PSM=" << loghex(psm);
311     return 0;
312   }
313 
314   /* First, see if we already have a link to the remote */
315   /* assume all ERTM l2cap connection is going over BR/EDR for now */
316   tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(p_bd_addr, BT_TRANSPORT_BR_EDR);
317   if (p_lcb == nullptr) {
318     /* No link. Get an LCB and start link establishment */
319     p_lcb = l2cu_allocate_lcb(p_bd_addr, false, BT_TRANSPORT_BR_EDR);
320     /* currently use BR/EDR for ERTM mode l2cap connection */
321     if (p_lcb == nullptr) {
322       LOG(WARNING) << __func__
323                    << ": connection not started for PSM=" << loghex(psm)
324                    << ", p_lcb=" << p_lcb;
325       return 0;
326     }
327     l2cu_create_conn_br_edr(p_lcb);
328   }
329 
330   /* Allocate a channel control block */
331   tL2C_CCB* p_ccb = l2cu_allocate_ccb(p_lcb, 0);
332   if (p_ccb == nullptr) {
333     LOG(WARNING) << __func__ << ": no CCB, PSM=" << loghex(psm);
334     return 0;
335   }
336 
337   /* Save registration info */
338   p_ccb->p_rcb = p_rcb;
339 
340   p_ccb->connection_initiator = L2CAP_INITIATOR_LOCAL;
341 
342   /* If link is up, start the L2CAP connection */
343   if (p_lcb->link_state == LST_CONNECTED) {
344     l2c_csm_execute(p_ccb, L2CEVT_L2CA_CONNECT_REQ, nullptr);
345   } else if (p_lcb->link_state == LST_DISCONNECTING) {
346     /* If link is disconnecting, save link info to retry after disconnect
347      * Possible Race condition when a reconnect occurs
348      * on the channel during a disconnect of link. This
349      * ccb will be automatically retried after link disconnect
350      * arrives
351      */
352     L2CAP_TRACE_DEBUG("L2CAP API - link disconnecting: RETRY LATER");
353 
354     /* Save ccb so it can be started after disconnect is finished */
355     p_lcb->p_pending_ccb = p_ccb;
356   }
357 
358   L2CAP_TRACE_API("L2CAP - L2CA_conn_req(psm: 0x%04x) returned CID: 0x%04x",
359                   psm, p_ccb->local_cid);
360 
361   /* Return the local CID as our handle */
362   return p_ccb->local_cid;
363 }
364 
365 /*******************************************************************************
366  *
367  * Function         L2CA_RegisterLECoc
368  *
369  * Description      Other layers call this function to register for L2CAP
370  *                  Connection Oriented Channel.
371  *
372  * Returns          PSM to use or zero if error. Typically, the PSM returned
373  *                  is the same as was passed in, but for an outgoing-only
374  *                  connection to a dynamic PSM, a "virtual" PSM is returned
375  *                  and should be used in the calls to L2CA_ConnectLECocReq()
376  *                  and L2CA_DeregisterLECoc()
377  *
378  ******************************************************************************/
379 uint16_t L2CA_RegisterLECoc(uint16_t psm, const tL2CAP_APPL_INFO& p_cb_info,
380                             uint16_t sec_level, tL2CAP_LE_CFG_INFO cfg) {
381   if (bluetooth::shim::is_gd_l2cap_enabled()) {
382     return bluetooth::shim::L2CA_RegisterLECoc(psm, p_cb_info, sec_level, cfg);
383   }
384 
385   if (p_cb_info.pL2CA_ConnectInd_Cb != nullptr || psm < LE_DYNAMIC_PSM_START) {
386     //  If we register LE COC for outgoing connection only, don't register with
387     //  BTM_Sec, because it's handled by L2CA_ConnectLECocReq.
388     BTM_SetSecurityLevel(false, "", 0, sec_level, psm, 0, 0);
389   }
390 
391   /* Verify that the required callback info has been filled in
392   **      Note:  Connection callbacks are required but not checked
393   **             for here because it is possible to be only a client
394   **             or only a server.
395   */
396   if ((!p_cb_info.pL2CA_DataInd_Cb) || (!p_cb_info.pL2CA_DisconnectInd_Cb)) {
397     LOG_ERROR("No cb registering BLE PSM: 0x%04x", psm);
398     return 0;
399   }
400 
401   /* Verify PSM is valid */
402   if (!L2C_IS_VALID_LE_PSM(psm)) {
403     LOG_ERROR("Invalid BLE PSM value, PSM: 0x%04x", psm);
404     return 0;
405   }
406 
407   tL2C_RCB* p_rcb;
408   uint16_t vpsm = psm;
409 
410   /* Check if this is a registration for an outgoing-only connection to */
411   /* a dynamic PSM. If so, allocate a "virtual" PSM for the app to use. */
412   if ((psm >= LE_DYNAMIC_PSM_START) &&
413       (p_cb_info.pL2CA_ConnectInd_Cb == NULL)) {
414     vpsm = L2CA_AllocateLePSM();
415     if (vpsm == 0) {
416       LOG_ERROR("Out of free BLE PSM");
417       return 0;
418     }
419 
420     LOG_DEBUG("Real PSM: 0x%04x  Virtual PSM: 0x%04x", psm, vpsm);
421   }
422 
423   /* If registration block already there, just overwrite it */
424   p_rcb = l2cu_find_ble_rcb_by_psm(vpsm);
425   if (p_rcb == NULL) {
426     LOG_DEBUG("Allocate rcp for Virtual PSM: 0x%04x", vpsm);
427     p_rcb = l2cu_allocate_ble_rcb(vpsm);
428     if (p_rcb == NULL) {
429       LOG_WARN("No BLE RCB available, PSM: 0x%04x  vPSM: 0x%04x", psm, vpsm);
430       return 0;
431     }
432   }
433 
434   LOG_INFO("Registered service LE COC PSM: 0x%04x", psm);
435   p_rcb->api = p_cb_info;
436   p_rcb->real_psm = psm;
437   p_rcb->coc_cfg = cfg;
438 
439   return vpsm;
440 }
441 
442 /*******************************************************************************
443  *
444  * Function         L2CA_DeregisterLECoc
445  *
446  * Description      Other layers call this function to de-register for L2CAP
447  *                  Connection Oriented Channel.
448  *
449  * Returns          void
450  *
451  ******************************************************************************/
452 void L2CA_DeregisterLECoc(uint16_t psm) {
453   if (bluetooth::shim::is_gd_l2cap_enabled()) {
454     return bluetooth::shim::L2CA_DeregisterLECoc(psm);
455   }
456 
457   L2CAP_TRACE_API("%s called for PSM: 0x%04x", __func__, psm);
458 
459   tL2C_RCB* p_rcb = l2cu_find_ble_rcb_by_psm(psm);
460   if (p_rcb == NULL) {
461     L2CAP_TRACE_WARNING("%s PSM: 0x%04x not found for deregistration", __func__,
462                         psm);
463     return;
464   }
465 
466   tL2C_LCB* p_lcb = &l2cb.lcb_pool[0];
467   for (int i = 0; i < MAX_L2CAP_LINKS; i++, p_lcb++) {
468     if (!p_lcb->in_use || p_lcb->transport != BT_TRANSPORT_LE) continue;
469 
470     tL2C_CCB* p_ccb = p_lcb->ccb_queue.p_first_ccb;
471     if ((p_ccb == NULL) || (p_lcb->link_state == LST_DISCONNECTING)) continue;
472 
473     if (p_ccb->in_use && (p_ccb->chnl_state == CST_W4_L2CAP_DISCONNECT_RSP ||
474                           p_ccb->chnl_state == CST_W4_L2CA_DISCONNECT_RSP))
475       continue;
476 
477     if (p_ccb->p_rcb == p_rcb)
478       l2c_csm_execute(p_ccb, L2CEVT_L2CA_DISCONNECT_REQ, NULL);
479   }
480 
481   l2cu_release_ble_rcb(p_rcb);
482 }
483 
484 /*******************************************************************************
485  *
486  * Function         L2CA_ConnectLECocReq
487  *
488  * Description      Higher layers call this function to create an L2CAP
489  *                  connection. Note that the connection is not established at
490  *                  this time, but connection establishment gets started. The
491  *                  callback function will be invoked when connection
492  *                  establishes or fails.
493  *
494  *  Parameters:     PSM: L2CAP PSM for the connection
495  *                  BD address of the peer
496  *                  Local Coc configurations
497 
498  * Returns          the CID of the connection, or 0 if it failed to start
499  *
500  ******************************************************************************/
501 uint16_t L2CA_ConnectLECocReq(uint16_t psm, const RawAddress& p_bd_addr,
502                               tL2CAP_LE_CFG_INFO* p_cfg, uint16_t sec_level) {
503   if (bluetooth::shim::is_gd_l2cap_enabled()) {
504     return bluetooth::shim::L2CA_ConnectLECocReq(psm, p_bd_addr, p_cfg);
505   }
506 
507   BTM_SetSecurityLevel(true, "", 0, sec_level, psm, 0, 0);
508 
509   VLOG(1) << __func__ << " BDA: " << p_bd_addr
510           << StringPrintf(" PSM: 0x%04x", psm);
511 
512   /* Fail if we have not established communications with the controller */
513   if (!BTM_IsDeviceUp()) {
514     L2CAP_TRACE_WARNING("%s BTU not ready", __func__);
515     return 0;
516   }
517 
518   /* Fail if the PSM is not registered */
519   tL2C_RCB* p_rcb = l2cu_find_ble_rcb_by_psm(psm);
520   if (p_rcb == NULL) {
521     L2CAP_TRACE_WARNING("%s No BLE RCB, PSM: 0x%04x", __func__, psm);
522     return 0;
523   }
524 
525   /* First, see if we already have a le link to the remote */
526   tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(p_bd_addr, BT_TRANSPORT_LE);
527   if (p_lcb == NULL) {
528     /* No link. Get an LCB and start link establishment */
529     p_lcb = l2cu_allocate_lcb(p_bd_addr, false, BT_TRANSPORT_LE);
530     if ((p_lcb == NULL)
531         /* currently use BR/EDR for ERTM mode l2cap connection */
532         || (!l2cu_create_conn_le(p_lcb))) {
533       L2CAP_TRACE_WARNING("%s conn not started for PSM: 0x%04x  p_lcb: 0x%08x",
534                           __func__, psm, p_lcb);
535       return 0;
536     }
537   }
538 
539   /* Allocate a channel control block */
540   tL2C_CCB* p_ccb = l2cu_allocate_ccb(p_lcb, 0);
541   if (p_ccb == NULL) {
542     L2CAP_TRACE_WARNING("%s no CCB, PSM: 0x%04x", __func__, psm);
543     return 0;
544   }
545 
546   /* Save registration info */
547   p_ccb->p_rcb = p_rcb;
548 
549   p_ccb->connection_initiator = L2CAP_INITIATOR_LOCAL;
550 
551   /* Save the configuration */
552   if (p_cfg) {
553     p_ccb->local_conn_cfg = *p_cfg;
554     p_ccb->remote_credit_count = p_cfg->credits;
555   }
556 
557   /* If link is up, start the L2CAP connection */
558   if (p_lcb->link_state == LST_CONNECTED) {
559     if (p_ccb->p_lcb->transport == BT_TRANSPORT_LE) {
560       L2CAP_TRACE_DEBUG("%s LE Link is up", __func__);
561       l2c_csm_execute(p_ccb, L2CEVT_L2CA_CONNECT_REQ, NULL);
562     }
563   }
564 
565   /* If link is disconnecting, save link info to retry after disconnect
566    * Possible Race condition when a reconnect occurs
567    * on the channel during a disconnect of link. This
568    * ccb will be automatically retried after link disconnect
569    * arrives
570    */
571   else if (p_lcb->link_state == LST_DISCONNECTING) {
572     L2CAP_TRACE_DEBUG("%s link disconnecting: RETRY LATER", __func__);
573 
574     /* Save ccb so it can be started after disconnect is finished */
575     p_lcb->p_pending_ccb = p_ccb;
576   }
577 
578   L2CAP_TRACE_API("%s(psm: 0x%04x) returned CID: 0x%04x", __func__, psm,
579                   p_ccb->local_cid);
580 
581   /* Return the local CID as our handle */
582   return p_ccb->local_cid;
583 }
584 
585 /*******************************************************************************
586  *
587  *  Function         L2CA_GetPeerLECocConfig
588  *
589  *  Description      Get a peers configuration for LE Connection Oriented
590  *                   Channel.
591  *
592  *  Parameters:      local channel id
593  *                   Pointers to peers configuration storage area
594  *
595  *  Return value:    true if peer is connected
596  *
597  ******************************************************************************/
598 bool L2CA_GetPeerLECocConfig(uint16_t lcid, tL2CAP_LE_CFG_INFO* peer_cfg) {
599   if (bluetooth::shim::is_gd_l2cap_enabled()) {
600     return bluetooth::shim::L2CA_GetPeerLECocConfig(lcid, peer_cfg);
601   }
602 
603   L2CAP_TRACE_API("%s CID: 0x%04x", __func__, lcid);
604 
605   tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(NULL, lcid);
606   if (p_ccb == NULL) {
607     L2CAP_TRACE_ERROR("%s No CCB for CID:0x%04x", __func__, lcid);
608     return false;
609   }
610 
611   if (peer_cfg != NULL)
612     memcpy(peer_cfg, &p_ccb->peer_conn_cfg, sizeof(tL2CAP_LE_CFG_INFO));
613 
614   return true;
615 }
616 
617 /*******************************************************************************
618  *
619  * Function         L2CA_ConnectCreditBasedRsp
620  *
621  * Description      Response for the pL2CA_CreditBasedConnectInd_Cb which is the
622  *                  indication for peer requesting credit based connection.
623  *
624  * Parameters:      BD address of the peer
625  *                  Identifier of the transaction
626  *                  Vector of accepted lcids by upper layer
627  *                  L2CAP result
628  *                  Local channel configuration
629  *
630  * Returns          true for success, false for failure
631  *
632  ******************************************************************************/
633 bool L2CA_ConnectCreditBasedRsp(const RawAddress& p_bd_addr, uint8_t id,
634                                 std::vector<uint16_t>& accepted_lcids,
635                                 uint16_t result, tL2CAP_LE_CFG_INFO* p_cfg) {
636   if (bluetooth::shim::is_gd_l2cap_enabled()) {
637     return bluetooth::shim::L2CA_ConnectCreditBasedRsp(
638         p_bd_addr, id, accepted_lcids, result, p_cfg);
639   }
640 
641   VLOG(1) << __func__ << " BDA: " << p_bd_addr
642           << StringPrintf(" num of cids: %d Result: %d",
643                           int(accepted_lcids.size()), +result);
644 
645   /* First, find the link control block */
646   tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(p_bd_addr, BT_TRANSPORT_LE);
647   if (p_lcb == NULL) {
648     /* No link. Get an LCB and start link establishment */
649     L2CAP_TRACE_WARNING("%s no LCB", __func__);
650     return false;
651   }
652 
653   /* Now, find the channel control block. We kept lead cid.
654    */
655   tL2C_CCB* p_ccb = l2cu_find_ccb_by_cid(p_lcb, p_lcb->pending_lead_cid);
656 
657   for (uint16_t cid : accepted_lcids) {
658     tL2C_CCB* temp_p_ccb = l2cu_find_ccb_by_cid(p_lcb, cid);
659     if (temp_p_ccb == NULL) {
660       L2CAP_TRACE_WARNING("%s no CCB", __func__);
661       return false;
662     }
663 
664     if (p_cfg) {
665       temp_p_ccb->local_conn_cfg = *p_cfg;
666       temp_p_ccb->remote_credit_count = p_cfg->credits;
667     }
668   }
669 
670   /* The IDs must match */
671   if (p_ccb->remote_id != id) {
672     L2CAP_TRACE_WARNING("%s bad id. Expected: %d  Got: %d", __func__,
673                         p_ccb->remote_id, id);
674     return false;
675   }
676 
677   tL2C_CONN_INFO conn_info;
678   conn_info.lcids = accepted_lcids;
679   conn_info.bd_addr = p_bd_addr;
680   conn_info.l2cap_result = result;
681 
682   if (accepted_lcids.size() > 0) {
683     l2c_csm_execute(p_ccb, L2CEVT_L2CA_CREDIT_BASED_CONNECT_RSP, &conn_info);
684   } else {
685     l2c_csm_execute(p_ccb, L2CEVT_L2CA_CREDIT_BASED_CONNECT_RSP_NEG,
686                     &conn_info);
687   }
688 
689   return true;
690 }
691 /*******************************************************************************
692  *
693  *  Function         L2CA_ConnectCreditBasedReq
694  *
695  *  Description      Initiate Create Credit Based connections.
696  *
697  *  Parameters:      PSM for the L2CAP channel
698  *                   BD address of the peer
699  *                   Local channel configuration
700  *
701  *  Return value:    Vector of allocated local cids.
702  *
703  ******************************************************************************/
704 
705 std::vector<uint16_t> L2CA_ConnectCreditBasedReq(uint16_t psm,
706                                                  const RawAddress& p_bd_addr,
707                                                  tL2CAP_LE_CFG_INFO* p_cfg) {
708   if (bluetooth::shim::is_gd_l2cap_enabled()) {
709     return bluetooth::shim::L2CA_ConnectCreditBasedReq(psm, p_bd_addr, p_cfg);
710   }
711 
712   VLOG(1) << __func__ << " BDA: " << p_bd_addr
713           << StringPrintf(" PSM: 0x%04x", psm);
714 
715   std::vector<uint16_t> allocated_cids;
716 
717   /* Fail if we have not established communications with the controller */
718   if (!BTM_IsDeviceUp()) {
719     L2CAP_TRACE_WARNING("%s BTU not ready", __func__);
720     return allocated_cids;
721   }
722 
723   if (!p_cfg) {
724     L2CAP_TRACE_WARNING("%s p_cfg is NULL", __func__);
725     return allocated_cids;
726   }
727 
728   /* Fail if the PSM is not registered */
729   tL2C_RCB* p_rcb = l2cu_find_ble_rcb_by_psm(psm);
730   if (p_rcb == NULL) {
731     L2CAP_TRACE_WARNING("%s No BLE RCB, PSM: 0x%04x", __func__, psm);
732     return allocated_cids;
733   }
734 
735   /* First, see if we already have a le link to the remote */
736   tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(p_bd_addr, BT_TRANSPORT_LE);
737   if (p_lcb == NULL) {
738     L2CAP_TRACE_WARNING("%s No link available", __func__);
739     return allocated_cids;
740   }
741 
742   if (p_lcb->link_state != LST_CONNECTED) {
743     L2CAP_TRACE_WARNING("%s incorrect link state: %d", __func__,
744                         p_lcb->link_state);
745     return allocated_cids;
746   }
747 
748   L2CAP_TRACE_DEBUG("%s LE Link is up", __func__);
749 
750   tL2C_CCB* p_ccb_primary;
751 
752   for (int i = 0; i < 5; i++) {
753     /* Allocate a channel control block */
754     tL2C_CCB* p_ccb = l2cu_allocate_ccb(p_lcb, 0);
755     if (p_ccb == NULL) {
756       if (i == 0) {
757         L2CAP_TRACE_WARNING("%s no CCB, PSM: 0x%04x", __func__, psm);
758         return allocated_cids;
759       } else {
760         break;
761       }
762     }
763 
764     p_ccb->ecoc = true;
765     p_ccb->local_conn_cfg = *p_cfg;
766     p_ccb->remote_credit_count = p_cfg->credits;
767     /* Save registration info */
768     p_ccb->p_rcb = p_rcb;
769     if (i == 0) {
770       p_ccb_primary = p_ccb;
771     } else {
772       /* Only primary channel we keep in closed state, as in that
773        * context we will run state machine where security is checked etc.
774        * Others we can directly put into waiting for connect
775        * response, so those are not confused by system as incomming connections
776        */
777       p_ccb->chnl_state = CST_W4_L2CAP_CONNECT_RSP;
778     }
779 
780     allocated_cids.push_back(p_ccb->local_cid);
781   }
782 
783   for (int i = 0; i < (int)(allocated_cids.size()); i++)
784     p_lcb->pending_ecoc_connection_cids[i] = allocated_cids[i];
785 
786   p_lcb->pending_ecoc_conn_cnt = (uint16_t)(allocated_cids.size());
787   l2c_csm_execute(p_ccb_primary, L2CEVT_L2CA_CREDIT_BASED_CONNECT_REQ, NULL);
788 
789   L2CAP_TRACE_API("%s(psm: 0x%04x) returned CID: 0x%04x", __func__, psm,
790                   p_ccb_primary->local_cid);
791 
792   return allocated_cids;
793 }
794 
795 /*******************************************************************************
796  *
797  *  Function         L2CA_ReconfigCreditBasedConnsReq
798  *
799  *  Description      Start reconfigure procedure on Connection Oriented Channel.
800  *
801  *  Parameters:      Vector of channels for which configuration should be changed
802  *                   New local channel configuration
803  *
804  *  Return value:    true if peer is connected
805  *
806  ******************************************************************************/
807 
808 bool L2CA_ReconfigCreditBasedConnsReq(const RawAddress& bda,
809                                       std::vector<uint16_t>& lcids,
810                                       tL2CAP_LE_CFG_INFO* p_cfg) {
811   if (bluetooth::shim::is_gd_l2cap_enabled()) {
812     return bluetooth::shim::L2CA_ReconfigCreditBasedConnsReq(bda, lcids, p_cfg);
813   }
814 
815   tL2C_CCB* p_ccb;
816 
817   L2CAP_TRACE_API("L2CA_ReconfigCreditBasedConnsReq() ");
818 
819   if (lcids.empty()) {
820     L2CAP_TRACE_WARNING("L2CAP - no lcids given to %s", __func__);
821     return (false);
822   }
823 
824   for (uint16_t cid : lcids) {
825     p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
826 
827     if (!p_ccb) {
828       L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_cfg_req, CID: %d", cid);
829       return (false);
830     }
831 
832     if ((p_ccb->local_conn_cfg.mtu > p_cfg->mtu) ||
833         (p_ccb->local_conn_cfg.mps > p_cfg->mps)) {
834       L2CAP_TRACE_WARNING("L2CAP - MPS or MTU reduction, CID: %d", cid);
835       return (false);
836     }
837   }
838 
839   if (p_cfg->mtu > L2CAP_MTU_SIZE) {
840     L2CAP_TRACE_WARNING("L2CAP - adjust MTU: %u too large", p_cfg->mtu);
841     p_cfg->mtu = L2CAP_MTU_SIZE;
842   }
843 
844   /* Mark all the p_ccbs which going to be reconfigured */
845   for (uint16_t cid : lcids) {
846     L2CAP_TRACE_API(" cid: %d", cid);
847     p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
848     if (!p_ccb) {
849       LOG(ERROR) << __func__ << "Missing cid? " << int(cid);
850       return (false);
851     }
852     p_ccb->reconfig_started = true;
853   }
854 
855   tL2C_LCB* p_lcb = p_ccb->p_lcb;
856 
857   /* Hack warning - the whole reconfig we are doing in the context of the first
858    * p_ccb. In the p_lcp we store configuration and cid in which context we are
859    * doing reconfiguration.
860    */
861   for (p_ccb = p_lcb->ccb_queue.p_first_ccb; p_ccb; p_ccb = p_ccb->p_next_ccb)
862     if ((p_ccb->in_use) && (p_ccb->ecoc) && (p_ccb->reconfig_started)) {
863       p_ccb->p_lcb->pending_ecoc_reconfig_cfg = *p_cfg;
864       p_ccb->p_lcb->pending_ecoc_reconfig_cnt = lcids.size();
865       break;
866     }
867 
868   l2c_csm_execute(p_ccb, L2CEVT_L2CA_CREDIT_BASED_RECONFIG_REQ, p_cfg);
869 
870   return (true);
871 }
872 
873 /*******************************************************************************
874  *
875  * Function         L2CA_DisconnectReq
876  *
877  * Description      Higher layers call this function to disconnect a channel.
878  *
879  * Returns          true if disconnect sent, else false
880  *
881  ******************************************************************************/
882 bool L2CA_DisconnectReq(uint16_t cid) {
883   if (bluetooth::shim::is_gd_l2cap_enabled()) {
884     return bluetooth::shim::L2CA_DisconnectReq(cid);
885   }
886 
887   tL2C_CCB* p_ccb;
888 
889   /* Find the channel control block. We don't know the link it is on. */
890   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
891   if (p_ccb == NULL) {
892     LOG_WARN("L2CAP - no CCB for L2CA_disc_req, CID: %d", cid);
893     return (false);
894   }
895 
896   LOG_DEBUG("L2CAP Local disconnect request CID: 0x%04x", cid);
897 
898   l2c_csm_execute(p_ccb, L2CEVT_L2CA_DISCONNECT_REQ, NULL);
899 
900   return (true);
901 }
902 
903 bool L2CA_DisconnectLECocReq(uint16_t cid) {
904   if (bluetooth::shim::is_gd_l2cap_enabled()) {
905     return bluetooth::shim::L2CA_DisconnectLECocReq(cid);
906   }
907   return L2CA_DisconnectReq(cid);
908 }
909 
910 bool L2CA_GetRemoteCid(uint16_t lcid, uint16_t* rcid) {
911   if (bluetooth::shim::is_gd_l2cap_enabled()) {
912     return bluetooth::shim::L2CA_GetRemoteCid(lcid, rcid);
913   }
914 
915   tL2C_CCB* control_block = l2cu_find_ccb_by_cid(NULL, lcid);
916   if (!control_block) return false;
917 
918   if (rcid) *rcid = control_block->remote_cid;
919 
920   return true;
921 }
922 
923 /*******************************************************************************
924  *
925  * Function         L2CA_SetIdleTimeoutByBdAddr
926  *
927  * Description      Higher layers call this function to set the idle timeout for
928  *                  a connection. The "idle timeout" is the amount of time that
929  *                  a connection can remain up with no L2CAP channels on it.
930  *                  A timeout of zero means that the connection will be torn
931  *                  down immediately when the last channel is removed.
932  *                  A timeout of 0xFFFF means no timeout. Values are in seconds.
933  *                  A bd_addr is the remote BD address. If bd_addr =
934  *                  RawAddress::kAny, then the idle timeouts for all active
935  *                  l2cap links will be changed.
936  *
937  * Returns          true if command succeeded, false if failed
938  *
939  * NOTE             This timeout applies to all logical channels active on the
940  *                  ACL link.
941  ******************************************************************************/
942 bool L2CA_SetIdleTimeoutByBdAddr(const RawAddress& bd_addr, uint16_t timeout,
943                                  tBT_TRANSPORT transport) {
944   if (bluetooth::shim::is_gd_l2cap_enabled()) {
945     return bluetooth::shim::L2CA_SetIdleTimeoutByBdAddr(bd_addr, timeout,
946                                                         transport);
947   }
948 
949   tL2C_LCB* p_lcb;
950 
951   if (RawAddress::kAny != bd_addr) {
952     p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, transport);
953     if ((p_lcb) && (p_lcb->in_use) && (p_lcb->link_state == LST_CONNECTED)) {
954       p_lcb->idle_timeout = timeout;
955 
956       if (!p_lcb->ccb_queue.p_first_ccb) l2cu_no_dynamic_ccbs(p_lcb);
957     } else
958       return false;
959   } else {
960     int xx;
961     tL2C_LCB* p_lcb = &l2cb.lcb_pool[0];
962 
963     for (xx = 0; xx < MAX_L2CAP_LINKS; xx++, p_lcb++) {
964       if ((p_lcb->in_use) && (p_lcb->link_state == LST_CONNECTED)) {
965         p_lcb->idle_timeout = timeout;
966 
967         if (!p_lcb->ccb_queue.p_first_ccb) l2cu_no_dynamic_ccbs(p_lcb);
968       }
969     }
970   }
971 
972   return true;
973 }
974 
975 /*******************************************************************************
976  *
977  * Function         L2CA_SetTraceLevel
978  *
979  * Description      This function sets the trace level for L2CAP. If called with
980  *                  a value of 0xFF, it simply reads the current trace level.
981  *
982  * Returns          the new (current) trace level
983  *
984  ******************************************************************************/
985 uint8_t L2CA_SetTraceLevel(uint8_t new_level) {
986   if (new_level != 0xFF) l2cb.l2cap_trace_level = new_level;
987 
988   return (l2cb.l2cap_trace_level);
989 }
990 
991 /*******************************************************************************
992  *
993  * Function         L2CA_SetAclPriority
994  *
995  * Description      Sets the transmission priority for a channel.
996  *                  (For initial implementation only two values are valid.
997  *                  L2CAP_PRIORITY_NORMAL and L2CAP_PRIORITY_HIGH).
998  *
999  * Returns          true if a valid channel, else false
1000  *
1001  ******************************************************************************/
1002 bool L2CA_SetAclPriority(const RawAddress& bd_addr, tL2CAP_PRIORITY priority) {
1003   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1004     return bluetooth::shim::L2CA_SetAclPriority(bd_addr, priority);
1005   }
1006 
1007   VLOG(1) << __func__ << " BDA: " << bd_addr
1008           << ", priority: " << std::to_string(priority);
1009   return (l2cu_set_acl_priority(bd_addr, priority, false));
1010 }
1011 
1012 /*******************************************************************************
1013  *
1014  * Function         L2CA_SetTxPriority
1015  *
1016  * Description      Sets the transmission priority for a channel.
1017  *
1018  * Returns          true if a valid channel, else false
1019  *
1020  ******************************************************************************/
1021 bool L2CA_SetTxPriority(uint16_t cid, tL2CAP_CHNL_PRIORITY priority) {
1022   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1023     return bluetooth::shim::L2CA_SetTxPriority(cid, priority);
1024   }
1025 
1026   tL2C_CCB* p_ccb;
1027 
1028   L2CAP_TRACE_API("L2CA_SetTxPriority()  CID: 0x%04x, priority:%d", cid,
1029                   priority);
1030 
1031   /* Find the channel control block. We don't know the link it is on. */
1032   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
1033   if (p_ccb == NULL) {
1034     L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_SetTxPriority, CID: %d", cid);
1035     return (false);
1036   }
1037 
1038   /* it will update the order of CCB in LCB by priority and update round robin
1039    * service variables */
1040   l2cu_change_pri_ccb(p_ccb, priority);
1041 
1042   return (true);
1043 }
1044 
1045 /*******************************************************************************
1046  *
1047  *  Function         L2CA_GetPeerFeatures
1048  *
1049  *  Description      Get a peers features and fixed channel map
1050  *
1051  *  Parameters:      BD address of the peer
1052  *                   Pointers to features and channel mask storage area
1053  *
1054  *  Return value:    true if peer is connected
1055  *
1056  ******************************************************************************/
1057 bool L2CA_GetPeerFeatures(const RawAddress& bd_addr, uint32_t* p_ext_feat,
1058                           uint8_t* p_chnl_mask) {
1059   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1060     return bluetooth::shim::L2CA_GetPeerFeatures(bd_addr, p_ext_feat,
1061                                                  p_chnl_mask);
1062   }
1063 
1064   tL2C_LCB* p_lcb;
1065 
1066   /* We must already have a link to the remote */
1067   p_lcb = l2cu_find_lcb_by_bd_addr(bd_addr, BT_TRANSPORT_BR_EDR);
1068   if (p_lcb == NULL) {
1069     LOG(WARNING) << __func__ << " No BDA: " << bd_addr;
1070     return false;
1071   }
1072 
1073   VLOG(1) << __func__ << " BDA: " << bd_addr
1074           << StringPrintf(" ExtFea: 0x%08x Chnl_Mask[0]: 0x%02x",
1075                           p_lcb->peer_ext_fea, p_lcb->peer_chnl_mask[0]);
1076 
1077   *p_ext_feat = p_lcb->peer_ext_fea;
1078 
1079   memcpy(p_chnl_mask, p_lcb->peer_chnl_mask, L2CAP_FIXED_CHNL_ARRAY_SIZE);
1080 
1081   return true;
1082 }
1083 
1084 /*******************************************************************************
1085  *
1086  *  Function        L2CA_RegisterFixedChannel
1087  *
1088  *  Description     Register a fixed channel.
1089  *
1090  *  Parameters:     Fixed Channel #
1091  *                  Channel Callbacks and config
1092  *
1093  *  Return value:   -
1094  *
1095  ******************************************************************************/
1096 static std::string fixed_channel_text(const uint16_t& fixed_cid) {
1097   switch (fixed_cid) {
1098     case L2CAP_SIGNALLING_CID:
1099       return std::string("br_edr signalling");
1100     case L2CAP_CONNECTIONLESS_CID:
1101       return std::string("connectionless");
1102     case L2CAP_AMP_CID:
1103       return std::string("amp");
1104     case L2CAP_ATT_CID:
1105       return std::string("att");
1106     case L2CAP_BLE_SIGNALLING_CID:
1107       return std::string("ble signalling");
1108     case L2CAP_SMP_CID:
1109       return std::string("smp");
1110     case L2CAP_SMP_BR_CID:
1111       return std::string("br_edr smp");
1112     default:
1113       return std::string("unknown");
1114   }
1115 }
1116 
1117 bool L2CA_RegisterFixedChannel(uint16_t fixed_cid,
1118                                tL2CAP_FIXED_CHNL_REG* p_freg) {
1119   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1120     return bluetooth::shim::L2CA_RegisterFixedChannel(fixed_cid, p_freg);
1121   }
1122 
1123   if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) ||
1124       (fixed_cid > L2CAP_LAST_FIXED_CHNL)) {
1125     LOG_ERROR("Invalid fixed CID: 0x%04x", fixed_cid);
1126     return false;
1127   }
1128 
1129   l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL] = *p_freg;
1130   LOG_DEBUG("Registered fixed channel:%s",
1131             fixed_channel_text(fixed_cid).c_str());
1132   return true;
1133 }
1134 
1135 /*******************************************************************************
1136  *
1137  *  Function        L2CA_ConnectFixedChnl
1138  *
1139  *  Description     Connect an fixed signalling channel to a remote device.
1140  *
1141  *  Parameters:     Fixed CID
1142  *                  BD Address of remote
1143  *
1144  *  Return value:   true if connection started
1145  *
1146  ******************************************************************************/
1147 bool L2CA_ConnectFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda) {
1148   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1149     return bluetooth::shim::L2CA_ConnectFixedChnl(fixed_cid, rem_bda);
1150   }
1151 
1152   tL2C_LCB* p_lcb;
1153   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
1154 
1155   LOG_DEBUG(" fixed_cid:0x%04x", fixed_cid);
1156 
1157   // Check CID is valid and registered
1158   if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) ||
1159       (fixed_cid > L2CAP_LAST_FIXED_CHNL) ||
1160       (l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb ==
1161        NULL)) {
1162     LOG_ERROR("Invalid fixed_cid:0x%04x", fixed_cid);
1163     return (false);
1164   }
1165 
1166   // Fail if BT is not yet up
1167   if (!BTM_IsDeviceUp()) {
1168     LOG_WARN("Bt controller is not ready fixed_cid:0x%04x", fixed_cid);
1169     return (false);
1170   }
1171 
1172   if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID)
1173     transport = BT_TRANSPORT_LE;
1174 
1175   tL2C_BLE_FIXED_CHNLS_MASK peer_channel_mask;
1176 
1177   // If we already have a link to the remote, check if it supports that CID
1178   p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, transport);
1179   if (p_lcb != NULL) {
1180     // Fixed channels are mandatory on LE transports so ignore the received
1181     // channel mask and use the locally cached LE channel mask.
1182 
1183     if (transport == BT_TRANSPORT_LE)
1184       peer_channel_mask = l2cb.l2c_ble_fixed_chnls_mask;
1185     else
1186       peer_channel_mask = p_lcb->peer_chnl_mask[0];
1187 
1188     // Check for supported channel
1189     if (!(peer_channel_mask & (1 << fixed_cid))) {
1190       LOG_INFO("Peer device does not support fixed_cid:0x%04x", fixed_cid);
1191       return false;
1192     }
1193 
1194     // Get a CCB and link the lcb to it
1195     if (!l2cu_initialize_fixed_ccb(p_lcb, fixed_cid)) {
1196       LOG_WARN("Unable to allocate fixed channel resource fixed_cid:0x%04x",
1197                fixed_cid);
1198       return false;
1199     }
1200 
1201     // racing with disconnecting, queue the connection request
1202     if (p_lcb->link_state == LST_DISCONNECTING) {
1203       LOG_DEBUG(
1204           "Link is disconnecting so deferring connection fixed_cid:0x%04x",
1205           fixed_cid);
1206       /* Save ccb so it can be started after disconnect is finished */
1207       p_lcb->p_pending_ccb =
1208           p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL];
1209       return true;
1210     }
1211 
1212     (*l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedConn_Cb)(
1213         fixed_cid, p_lcb->remote_bd_addr, true, 0, p_lcb->transport);
1214     return true;
1215   }
1216 
1217   // No link. Get an LCB and start link establishment
1218   p_lcb = l2cu_allocate_lcb(rem_bda, false, transport);
1219   if (p_lcb == NULL) {
1220     LOG_WARN("Unable to allocate link resource for connection fixed_cid:0x%04x",
1221              fixed_cid);
1222     return false;
1223   }
1224 
1225   // Get a CCB and link the lcb to it
1226   if (!l2cu_initialize_fixed_ccb(p_lcb, fixed_cid)) {
1227     LOG_WARN("Unable to allocate fixed channel resource fixed_cid:0x%04x",
1228              fixed_cid);
1229     l2cu_release_lcb(p_lcb);
1230     return false;
1231   }
1232 
1233   if (transport == BT_TRANSPORT_LE) {
1234     bool ret = l2cu_create_conn_le(p_lcb);
1235     if (!ret) {
1236       LOG_WARN("Unable to create fixed channel le connection fixed_cid:0x%04x",
1237                fixed_cid);
1238       l2cu_release_lcb(p_lcb);
1239       return false;
1240     }
1241   } else {
1242     l2cu_create_conn_br_edr(p_lcb);
1243   }
1244   return true;
1245 }
1246 
1247 /*******************************************************************************
1248  *
1249  *  Function        L2CA_SendFixedChnlData
1250  *
1251  *  Description     Write data on a fixed channel.
1252  *
1253  *  Parameters:     Fixed CID
1254  *                  BD Address of remote
1255  *                  Pointer to buffer of type BT_HDR
1256  *
1257  * Return value     L2CAP_DW_SUCCESS, if data accepted
1258  *                  L2CAP_DW_FAILED,  if error
1259  *
1260  ******************************************************************************/
1261 uint16_t L2CA_SendFixedChnlData(uint16_t fixed_cid, const RawAddress& rem_bda,
1262                                 BT_HDR* p_buf) {
1263   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1264     return bluetooth::shim::L2CA_SendFixedChnlData(fixed_cid, rem_bda, p_buf);
1265   }
1266 
1267   tL2C_LCB* p_lcb;
1268   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
1269 
1270   if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID)
1271     transport = BT_TRANSPORT_LE;
1272 
1273   if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) ||
1274       (fixed_cid > L2CAP_LAST_FIXED_CHNL) ||
1275       (l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb ==
1276        NULL)) {
1277     LOG_WARN("No service registered or invalid CID: 0x%04x", fixed_cid);
1278     osi_free(p_buf);
1279     return (L2CAP_DW_FAILED);
1280   }
1281 
1282   if (!BTM_IsDeviceUp()) {
1283     LOG_WARN("Controller is not ready CID: 0x%04x", fixed_cid);
1284     osi_free(p_buf);
1285     return (L2CAP_DW_FAILED);
1286   }
1287 
1288   p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, transport);
1289   if (p_lcb == NULL || p_lcb->link_state == LST_DISCONNECTING) {
1290     /* if link is disconnecting, also report data sending failure */
1291     LOG_WARN("Link is disconnecting or does not exist CID: 0x%04x", fixed_cid);
1292     osi_free(p_buf);
1293     return (L2CAP_DW_FAILED);
1294   }
1295 
1296   tL2C_BLE_FIXED_CHNLS_MASK peer_channel_mask;
1297 
1298   // Select peer channels mask to use depending on transport
1299   if (transport == BT_TRANSPORT_LE)
1300     peer_channel_mask = l2cb.l2c_ble_fixed_chnls_mask;
1301   else
1302     peer_channel_mask = p_lcb->peer_chnl_mask[0];
1303 
1304   if ((peer_channel_mask & (1 << fixed_cid)) == 0) {
1305     LOG_WARN("Peer does not support fixed channel CID: 0x%04x", fixed_cid);
1306     osi_free(p_buf);
1307     return (L2CAP_DW_FAILED);
1308   }
1309 
1310   p_buf->event = 0;
1311   p_buf->layer_specific = L2CAP_FLUSHABLE_CH_BASED;
1312 
1313   if (!p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]) {
1314     if (!l2cu_initialize_fixed_ccb(p_lcb, fixed_cid)) {
1315       LOG_WARN("No channel control block found for CID: 0x%4x", fixed_cid);
1316       osi_free(p_buf);
1317       return (L2CAP_DW_FAILED);
1318     }
1319   }
1320 
1321   if (p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->cong_sent) {
1322     LOG_WARN(
1323         "Unable to send data due to congestion CID: 0x%04x xmit_hold_q.count: "
1324         "%zu buff_quota: %u",
1325         fixed_cid,
1326         fixed_queue_length(
1327             p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]
1328                 ->xmit_hold_q),
1329         p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->buff_quota);
1330     osi_free(p_buf);
1331     return (L2CAP_DW_FAILED);
1332   }
1333 
1334   LOG_DEBUG("Enqueued data for CID: 0x%04x len:%hu", fixed_cid, p_buf->len);
1335   l2c_enqueue_peer_data(p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL],
1336                         p_buf);
1337 
1338   l2c_link_check_send_pkts(p_lcb, 0, NULL);
1339 
1340   // If there is no dynamic CCB on the link, restart the idle timer each time
1341   // something is sent
1342   if (p_lcb->in_use && p_lcb->link_state == LST_CONNECTED &&
1343       !p_lcb->ccb_queue.p_first_ccb) {
1344     l2cu_no_dynamic_ccbs(p_lcb);
1345   }
1346 
1347   if (p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL]->cong_sent) {
1348     LOG_DEBUG("Link congested for CID: 0x%04x", fixed_cid);
1349     return (L2CAP_DW_CONGESTED);
1350   }
1351 
1352   return (L2CAP_DW_SUCCESS);
1353 }
1354 
1355 /*******************************************************************************
1356  *
1357  *  Function        L2CA_RemoveFixedChnl
1358  *
1359  *  Description     Remove a fixed channel to a remote device.
1360  *
1361  *  Parameters:     Fixed CID
1362  *                  BD Address of remote
1363  *                  Idle timeout to use (or 0xFFFF if don't care)
1364  *
1365  *  Return value:   true if channel removed
1366  *
1367  ******************************************************************************/
1368 bool L2CA_RemoveFixedChnl(uint16_t fixed_cid, const RawAddress& rem_bda) {
1369   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1370     return bluetooth::shim::L2CA_RemoveFixedChnl(fixed_cid, rem_bda);
1371   }
1372 
1373   tL2C_LCB* p_lcb;
1374   tL2C_CCB* p_ccb;
1375   tBT_TRANSPORT transport = BT_TRANSPORT_BR_EDR;
1376 
1377   /* Check CID is valid and registered */
1378   if ((fixed_cid < L2CAP_FIRST_FIXED_CHNL) ||
1379       (fixed_cid > L2CAP_LAST_FIXED_CHNL) ||
1380       (l2cb.fixed_reg[fixed_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb ==
1381        NULL)) {
1382     L2CAP_TRACE_ERROR("L2CA_RemoveFixedChnl()  Invalid CID: 0x%04x", fixed_cid);
1383     return (false);
1384   }
1385 
1386   if (fixed_cid >= L2CAP_ATT_CID && fixed_cid <= L2CAP_SMP_CID)
1387     transport = BT_TRANSPORT_LE;
1388 
1389   /* Is a fixed channel connected to the remote BDA ?*/
1390   p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, transport);
1391 
1392   if (((p_lcb) == NULL) ||
1393       (!p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL])) {
1394     LOG(WARNING) << __func__ << " BDA: " << rem_bda
1395                  << StringPrintf(" CID: 0x%04x not connected", fixed_cid);
1396     return (false);
1397   }
1398 
1399   VLOG(2) << __func__ << " BDA: " << rem_bda
1400           << StringPrintf(" CID: 0x%04x", fixed_cid);
1401 
1402   /* Release the CCB, starting an inactivity timeout on the LCB if no other CCBs
1403    * exist */
1404   p_ccb = p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL];
1405 
1406   p_lcb->p_fixed_ccbs[fixed_cid - L2CAP_FIRST_FIXED_CHNL] = NULL;
1407   p_lcb->SetDisconnectReason(HCI_ERR_CONN_CAUSE_LOCAL_HOST);
1408 
1409   // Retain the link for a few more seconds after SMP pairing is done, since
1410   // the Android platform always does service discovery after pairing is
1411   // complete. This will avoid the link down (pairing is complete) and an
1412   // immediate re-connection for service discovery.
1413   // Some devices do not do auto advertising when link is dropped, thus fail
1414   // the second connection and service discovery.
1415   if ((fixed_cid == L2CAP_ATT_CID) && !p_lcb->ccb_queue.p_first_ccb)
1416     p_lcb->idle_timeout = 0;
1417 
1418   l2cu_release_ccb(p_ccb);
1419 
1420   return (true);
1421 }
1422 
1423 /*******************************************************************************
1424  *
1425  * Function         L2CA_SetLeGattTimeout
1426  *
1427  * Description      Higher layers call this function to set the idle timeout for
1428  *                  a fixed channel. The "idle timeout" is the amount of time
1429  *                  that a connection can remain up with no L2CAP channels on
1430  *                  it. A timeout of zero means that the connection will be torn
1431  *                  down immediately when the last channel is removed.
1432  *                  A timeout of 0xFFFF means no timeout. Values are in seconds.
1433  *                  A bd_addr is the remote BD address.
1434  *
1435  * Returns          true if command succeeded, false if failed
1436  *
1437  ******************************************************************************/
1438 bool L2CA_SetLeGattTimeout(const RawAddress& rem_bda, uint16_t idle_tout) {
1439   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1440     return bluetooth::shim::L2CA_SetLeGattTimeout(rem_bda, idle_tout);
1441   }
1442 
1443   constexpr uint16_t kAttCid = 4;
1444 
1445   /* Is a fixed channel connected to the remote BDA ?*/
1446   tL2C_LCB* p_lcb = l2cu_find_lcb_by_bd_addr(rem_bda, BT_TRANSPORT_LE);
1447   if (((p_lcb) == NULL) ||
1448       (!p_lcb->p_fixed_ccbs[kAttCid - L2CAP_FIRST_FIXED_CHNL])) {
1449     LOG(WARNING) << __func__ << " BDA: " << rem_bda
1450                  << StringPrintf(" CID: 0x%04x not connected", kAttCid);
1451     return (false);
1452   }
1453 
1454   p_lcb->p_fixed_ccbs[kAttCid - L2CAP_FIRST_FIXED_CHNL]->fixed_chnl_idle_tout =
1455       idle_tout;
1456 
1457   if (p_lcb->in_use && p_lcb->link_state == LST_CONNECTED &&
1458       !p_lcb->ccb_queue.p_first_ccb) {
1459     /* If there are no dynamic CCBs, (re)start the idle timer in case we changed
1460      * it */
1461     l2cu_no_dynamic_ccbs(p_lcb);
1462   }
1463 
1464   return true;
1465 }
1466 
1467 /*******************************************************************************
1468  *
1469  * Function         L2CA_DataWrite
1470  *
1471  * Description      Higher layers call this function to write data.
1472  *
1473  * Returns          L2CAP_DW_SUCCESS, if data accepted, else false
1474  *                  L2CAP_DW_CONGESTED, if data accepted and the channel is
1475  *                                      congested
1476  *                  L2CAP_DW_FAILED, if error
1477  *
1478  ******************************************************************************/
1479 uint8_t L2CA_DataWrite(uint16_t cid, BT_HDR* p_data) {
1480   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1481     return bluetooth::shim::L2CA_DataWrite(cid, p_data);
1482   }
1483 
1484   L2CAP_TRACE_API("L2CA_DataWrite()  CID: 0x%04x  Len: %d", cid, p_data->len);
1485   return l2c_data_write(cid, p_data, L2CAP_FLUSHABLE_CH_BASED);
1486 }
1487 
1488 uint8_t L2CA_LECocDataWrite(uint16_t cid, BT_HDR* p_data) {
1489   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1490     return bluetooth::shim::L2CA_LECocDataWrite(cid, p_data);
1491   }
1492 
1493   return L2CA_DataWrite(cid, p_data);
1494 }
1495 
1496 /*******************************************************************************
1497  *
1498  * Function         L2CA_SetChnlFlushability
1499  *
1500  * Description      Higher layers call this function to set a channels
1501  *                  flushability flags
1502  *
1503  * Returns          true if CID found, else false
1504  *
1505  ******************************************************************************/
1506 bool L2CA_SetChnlFlushability(uint16_t cid, bool is_flushable) {
1507   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1508     return bluetooth::shim::L2CA_SetChnlFlushability(cid, is_flushable);
1509   }
1510 
1511   tL2C_CCB* p_ccb;
1512 
1513   /* Find the channel control block. We don't know the link it is on. */
1514   p_ccb = l2cu_find_ccb_by_cid(NULL, cid);
1515   if (p_ccb == NULL) {
1516     L2CAP_TRACE_WARNING("L2CAP - no CCB for L2CA_SetChnlFlushability, CID: %d",
1517                         cid);
1518     return (false);
1519   }
1520 
1521   p_ccb->is_flushable = is_flushable;
1522 
1523   L2CAP_TRACE_API("L2CA_SetChnlFlushability()  CID: 0x%04x  is_flushable: %d",
1524                   cid, is_flushable);
1525 
1526   return (true);
1527 }
1528 
1529 /*******************************************************************************
1530  *
1531  * Function     L2CA_FlushChannel
1532  *
1533  * Description  This function flushes none, some or all buffers queued up
1534  *              for xmission for a particular CID. If called with
1535  *              L2CAP_FLUSH_CHANS_GET (0), it simply returns the number
1536  *              of buffers queued for that CID L2CAP_FLUSH_CHANS_ALL (0xffff)
1537  *              flushes all buffers.  All other values specifies the maximum
1538  *              buffers to flush.
1539  *
1540  * Returns      Number of buffers left queued for that CID
1541  *
1542  ******************************************************************************/
1543 uint16_t L2CA_FlushChannel(uint16_t lcid, uint16_t num_to_flush) {
1544   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1545     return bluetooth::shim::L2CA_FlushChannel(lcid, num_to_flush);
1546   }
1547 
1548   tL2C_CCB* p_ccb;
1549   tL2C_LCB* p_lcb;
1550   uint16_t num_left = 0, num_flushed1 = 0, num_flushed2 = 0;
1551 
1552   p_ccb = l2cu_find_ccb_by_cid(NULL, lcid);
1553 
1554   if (!p_ccb || (p_ccb->p_lcb == NULL)) {
1555     L2CAP_TRACE_WARNING(
1556         "L2CA_FlushChannel()  abnormally returning 0  CID: 0x%04x", lcid);
1557     return (0);
1558   }
1559   p_lcb = p_ccb->p_lcb;
1560 
1561   if (num_to_flush != L2CAP_FLUSH_CHANS_GET) {
1562     L2CAP_TRACE_API(
1563         "L2CA_FlushChannel (FLUSH)  CID: 0x%04x  NumToFlush: %d  QC: %u  "
1564         "pFirst: 0x%08x",
1565         lcid, num_to_flush, fixed_queue_length(p_ccb->xmit_hold_q),
1566         fixed_queue_try_peek_first(p_ccb->xmit_hold_q));
1567   } else {
1568     L2CAP_TRACE_API("L2CA_FlushChannel (QUERY)  CID: 0x%04x", lcid);
1569   }
1570 
1571   /* Cannot flush eRTM buffers once they have a sequence number */
1572   if (p_ccb->peer_cfg.fcr.mode != L2CAP_FCR_ERTM_MODE) {
1573     const controller_t* controller = controller_get_interface();
1574     if (num_to_flush != L2CAP_FLUSH_CHANS_GET) {
1575       /* If the controller supports enhanced flush, flush the data queued at the
1576        * controller */
1577       if (controller->supports_non_flushable_pb() &&
1578           (BTM_GetNumScoLinks() == 0)) {
1579         /* The only packet type defined - 0 - Automatically-Flushable Only */
1580         btsnd_hcic_enhanced_flush(p_lcb->Handle(), 0);
1581       }
1582     }
1583 
1584     // Iterate though list and flush the amount requested from
1585     // the transmit data queue that satisfy the layer and event conditions.
1586     for (const list_node_t* node = list_begin(p_lcb->link_xmit_data_q);
1587          (num_to_flush > 0) && node != list_end(p_lcb->link_xmit_data_q);) {
1588       BT_HDR* p_buf = (BT_HDR*)list_node(node);
1589       node = list_next(node);
1590       if ((p_buf->layer_specific == 0) && (p_buf->event == lcid)) {
1591         num_to_flush--;
1592         num_flushed1++;
1593 
1594         list_remove(p_lcb->link_xmit_data_q, p_buf);
1595         osi_free(p_buf);
1596       }
1597     }
1598   }
1599 
1600   /* If needed, flush buffers in the CCB xmit hold queue */
1601   while ((num_to_flush != 0) && (!fixed_queue_is_empty(p_ccb->xmit_hold_q))) {
1602     BT_HDR* p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
1603     osi_free(p_buf);
1604     num_to_flush--;
1605     num_flushed2++;
1606   }
1607 
1608   /* If app needs to track all packets, call it */
1609   if ((p_ccb->p_rcb) && (p_ccb->p_rcb->api.pL2CA_TxComplete_Cb) &&
1610       (num_flushed2))
1611     (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid, num_flushed2);
1612 
1613   /* Now count how many are left */
1614   for (const list_node_t* node = list_begin(p_lcb->link_xmit_data_q);
1615        node != list_end(p_lcb->link_xmit_data_q); node = list_next(node)) {
1616     BT_HDR* p_buf = (BT_HDR*)list_node(node);
1617     if (p_buf->event == lcid) num_left++;
1618   }
1619 
1620   /* Add in the number in the CCB xmit queue */
1621   num_left += fixed_queue_length(p_ccb->xmit_hold_q);
1622 
1623   /* Return the local number of buffers left for the CID */
1624   L2CAP_TRACE_DEBUG("L2CA_FlushChannel()  flushed: %u + %u,  num_left: %u",
1625                     num_flushed1, num_flushed2, num_left);
1626 
1627   /* If we were congested, and now we are not, tell the app */
1628   l2cu_check_channel_congestion(p_ccb);
1629 
1630   return (num_left);
1631 }
1632 
1633 bool L2CA_IsLinkEstablished(const RawAddress& bd_addr,
1634                             tBT_TRANSPORT transport) {
1635   if (bluetooth::shim::is_gd_l2cap_enabled()) {
1636     return bluetooth::shim::L2CA_IsLinkEstablished(bd_addr, transport);
1637   }
1638 
1639   return l2cu_find_lcb_by_bd_addr(bd_addr, transport) != nullptr;
1640 }
1641