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