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