• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /******************************************************************************
2  *
3  *  Copyright 2004-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 1.2 Flow Control and retransmissions
22  *  functions
23  *
24  ******************************************************************************/
25 
26 #include <bluetooth/log.h>
27 #include <com_android_bluetooth_flags.h>
28 #include <stdlib.h>
29 #include <string.h>
30 
31 #include "internal_include/bt_target.h"
32 #include "osi/include/allocator.h"
33 #include "stack/include/bt_hdr.h"
34 #include "stack/include/bt_types.h"
35 #include "stack/include/l2cdefs.h"
36 #include "stack/l2cap/internal/l2c_api.h"
37 #include "stack/l2cap/l2c_int.h"
38 
39 /* Flag passed to retransmit_i_frames() when all packets should be retransmitted
40  */
41 #define L2C_FCR_RETX_ALL_PKTS 0xFF
42 
43 using namespace bluetooth;
44 
45 /* this is the minimal offset required by OBX to process incoming packets */
46 static const uint16_t OBX_BUF_MIN_OFFSET = 4;
47 
48 static const char* SAR_types[] = {"Unsegmented", "Start", "End", "Continuation"};
49 static const char* SUP_types[] = {"RR", "REJ", "RNR", "SREJ"};
50 
51 /* Look-up table for the CRC calculation */
52 static const uint16_t crctab[256] = {
53         0x0000, 0xc0c1, 0xc181, 0x0140, 0xc301, 0x03c0, 0x0280, 0xc241, 0xc601, 0x06c0, 0x0780,
54         0xc741, 0x0500, 0xc5c1, 0xc481, 0x0440, 0xcc01, 0x0cc0, 0x0d80, 0xcd41, 0x0f00, 0xcfc1,
55         0xce81, 0x0e40, 0x0a00, 0xcac1, 0xcb81, 0x0b40, 0xc901, 0x09c0, 0x0880, 0xc841, 0xd801,
56         0x18c0, 0x1980, 0xd941, 0x1b00, 0xdbc1, 0xda81, 0x1a40, 0x1e00, 0xdec1, 0xdf81, 0x1f40,
57         0xdd01, 0x1dc0, 0x1c80, 0xdc41, 0x1400, 0xd4c1, 0xd581, 0x1540, 0xd701, 0x17c0, 0x1680,
58         0xd641, 0xd201, 0x12c0, 0x1380, 0xd341, 0x1100, 0xd1c1, 0xd081, 0x1040, 0xf001, 0x30c0,
59         0x3180, 0xf141, 0x3300, 0xf3c1, 0xf281, 0x3240, 0x3600, 0xf6c1, 0xf781, 0x3740, 0xf501,
60         0x35c0, 0x3480, 0xf441, 0x3c00, 0xfcc1, 0xfd81, 0x3d40, 0xff01, 0x3fc0, 0x3e80, 0xfe41,
61         0xfa01, 0x3ac0, 0x3b80, 0xfb41, 0x3900, 0xf9c1, 0xf881, 0x3840, 0x2800, 0xe8c1, 0xe981,
62         0x2940, 0xeb01, 0x2bc0, 0x2a80, 0xea41, 0xee01, 0x2ec0, 0x2f80, 0xef41, 0x2d00, 0xedc1,
63         0xec81, 0x2c40, 0xe401, 0x24c0, 0x2580, 0xe541, 0x2700, 0xe7c1, 0xe681, 0x2640, 0x2200,
64         0xe2c1, 0xe381, 0x2340, 0xe101, 0x21c0, 0x2080, 0xe041, 0xa001, 0x60c0, 0x6180, 0xa141,
65         0x6300, 0xa3c1, 0xa281, 0x6240, 0x6600, 0xa6c1, 0xa781, 0x6740, 0xa501, 0x65c0, 0x6480,
66         0xa441, 0x6c00, 0xacc1, 0xad81, 0x6d40, 0xaf01, 0x6fc0, 0x6e80, 0xae41, 0xaa01, 0x6ac0,
67         0x6b80, 0xab41, 0x6900, 0xa9c1, 0xa881, 0x6840, 0x7800, 0xb8c1, 0xb981, 0x7940, 0xbb01,
68         0x7bc0, 0x7a80, 0xba41, 0xbe01, 0x7ec0, 0x7f80, 0xbf41, 0x7d00, 0xbdc1, 0xbc81, 0x7c40,
69         0xb401, 0x74c0, 0x7580, 0xb541, 0x7700, 0xb7c1, 0xb681, 0x7640, 0x7200, 0xb2c1, 0xb381,
70         0x7340, 0xb101, 0x71c0, 0x7080, 0xb041, 0x5000, 0x90c1, 0x9181, 0x5140, 0x9301, 0x53c0,
71         0x5280, 0x9241, 0x9601, 0x56c0, 0x5780, 0x9741, 0x5500, 0x95c1, 0x9481, 0x5440, 0x9c01,
72         0x5cc0, 0x5d80, 0x9d41, 0x5f00, 0x9fc1, 0x9e81, 0x5e40, 0x5a00, 0x9ac1, 0x9b81, 0x5b40,
73         0x9901, 0x59c0, 0x5880, 0x9841, 0x8801, 0x48c0, 0x4980, 0x8941, 0x4b00, 0x8bc1, 0x8a81,
74         0x4a40, 0x4e00, 0x8ec1, 0x8f81, 0x4f40, 0x8d01, 0x4dc0, 0x4c80, 0x8c41, 0x4400, 0x84c1,
75         0x8581, 0x4540, 0x8701, 0x47c0, 0x4680, 0x8641, 0x8201, 0x42c0, 0x4380, 0x8341, 0x4100,
76         0x81c1, 0x8081, 0x4040,
77 };
78 
79 /*******************************************************************************
80  *  Static local functions
81  */
82 static bool process_reqseq(tL2C_CCB* p_ccb, uint16_t ctrl_word);
83 static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word);
84 static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word, bool delay_ack);
85 static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq);
86 static void prepare_I_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, bool is_retransmission);
87 static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word);
88 
89 /*******************************************************************************
90  *
91  * Function         l2c_fcr_updcrc
92  *
93  * Description      This function computes the CRC using the look-up table.
94  *
95  * Returns          CRC
96  *
97  ******************************************************************************/
l2c_fcr_updcrc(uint16_t icrc,unsigned char * icp,int icnt)98 static uint16_t l2c_fcr_updcrc(uint16_t icrc, unsigned char* icp, int icnt) {
99   uint16_t crc = icrc;
100   unsigned char* cp = icp;
101   int cnt = icnt;
102 
103   while (cnt--) {
104     crc = ((crc >> 8) & 0xff) ^ crctab[(crc & 0xff) ^ *cp++];
105   }
106 
107   return crc;
108 }
109 
110 /*******************************************************************************
111  *
112  * Function         l2c_fcr_tx_get_fcs
113  *
114  * Description      This function computes the CRC for a frame to be TXed.
115  *
116  * Returns          CRC
117  *
118  ******************************************************************************/
l2c_fcr_tx_get_fcs(BT_HDR * p_buf)119 static uint16_t l2c_fcr_tx_get_fcs(BT_HDR* p_buf) {
120   uint8_t* p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
121 
122   return l2c_fcr_updcrc(L2CAP_FCR_INIT_CRC, p, p_buf->len);
123 }
124 
125 /*******************************************************************************
126  *
127  * Function         l2c_fcr_rx_get_fcs
128  *
129  * Description      This function computes the CRC for a received frame.
130  *
131  * Returns          CRC
132  *
133  ******************************************************************************/
l2c_fcr_rx_get_fcs(BT_HDR * p_buf)134 static uint16_t l2c_fcr_rx_get_fcs(BT_HDR* p_buf) {
135   uint8_t* p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
136 
137   /* offset points past the L2CAP header, but the CRC check includes it */
138   p -= L2CAP_PKT_OVERHEAD;
139 
140   return l2c_fcr_updcrc(L2CAP_FCR_INIT_CRC, p, p_buf->len + L2CAP_PKT_OVERHEAD);
141 }
142 
143 /*******************************************************************************
144  *
145  * Function         l2c_fcr_start_timer
146  *
147  * Description      This function starts the (monitor or retransmission) timer.
148  *
149  * Returns          -
150  *
151  ******************************************************************************/
l2c_fcr_start_timer(tL2C_CCB * p_ccb)152 void l2c_fcr_start_timer(tL2C_CCB* p_ccb) {
153   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
154   uint32_t tout;
155 
156   /* The timers which are in milliseconds */
157   if (p_ccb->fcrb.wait_ack) {
158     tout = (uint32_t)p_ccb->our_cfg.fcr.mon_tout;
159   } else {
160     tout = (uint32_t)p_ccb->our_cfg.fcr.rtrans_tout;
161   }
162 
163   /* Only start a timer that was not started */
164   if (!alarm_is_scheduled(p_ccb->fcrb.mon_retrans_timer)) {
165     alarm_set_on_mloop(p_ccb->fcrb.mon_retrans_timer, tout, l2c_ccb_timer_timeout, p_ccb);
166   }
167 }
168 
169 /*******************************************************************************
170  *
171  * Function         l2c_fcr_stop_timer
172  *
173  * Description      This function stops the (monitor or transmission) timer.
174  *
175  * Returns          -
176  *
177  ******************************************************************************/
l2c_fcr_stop_timer(tL2C_CCB * p_ccb)178 void l2c_fcr_stop_timer(tL2C_CCB* p_ccb) {
179   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
180   alarm_cancel(p_ccb->fcrb.mon_retrans_timer);
181 }
182 
183 /*******************************************************************************
184  *
185  * Function         l2c_fcr_cleanup
186  *
187  * Description      This function cleans up the variable used for
188  *                  flow-control/retrans.
189  *
190  * Returns          -
191  *
192  ******************************************************************************/
l2c_fcr_cleanup(tL2C_CCB * p_ccb)193 void l2c_fcr_cleanup(tL2C_CCB* p_ccb) {
194   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
195   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
196 
197   alarm_free(p_fcrb->mon_retrans_timer);
198   p_fcrb->mon_retrans_timer = NULL;
199   alarm_free(p_fcrb->ack_timer);
200   p_fcrb->ack_timer = NULL;
201 
202   osi_free_and_reset((void**)&p_fcrb->p_rx_sdu);
203 
204   fixed_queue_free(p_fcrb->waiting_for_ack_q, osi_free);
205   p_fcrb->waiting_for_ack_q = NULL;
206 
207   fixed_queue_free(p_fcrb->srej_rcv_hold_q, osi_free);
208   p_fcrb->srej_rcv_hold_q = NULL;
209 
210   fixed_queue_free(p_fcrb->retrans_q, osi_free);
211   p_fcrb->retrans_q = NULL;
212 
213   memset(p_fcrb, 0, sizeof(tL2C_FCRB));
214 }
215 
216 /*******************************************************************************
217  *
218  * Function         l2c_fcr_clone_buf
219  *
220  * Description      This function allocates and copies requested part of a
221  *                  buffer at a new-offset.
222  *
223  * Returns          pointer to new buffer
224  *
225  ******************************************************************************/
l2c_fcr_clone_buf(BT_HDR * p_buf,uint16_t new_offset,uint16_t no_of_bytes)226 BT_HDR* l2c_fcr_clone_buf(BT_HDR* p_buf, uint16_t new_offset, uint16_t no_of_bytes) {
227   log::assert_that(p_buf != NULL, "assert failed: p_buf != NULL");
228   /*
229    * NOTE: We allocate extra L2CAP_FCS_LEN octets, in case we need to put
230    * the FCS (Frame Check Sequence) at the end of the buffer.
231    */
232   uint16_t buf_size = no_of_bytes + sizeof(BT_HDR) + new_offset + L2CAP_FCS_LEN;
233   BT_HDR* p_buf2 = (BT_HDR*)osi_malloc(buf_size);
234 
235   p_buf2->offset = new_offset;
236   p_buf2->len = no_of_bytes;
237   memcpy(((uint8_t*)(p_buf2 + 1)) + p_buf2->offset, ((uint8_t*)(p_buf + 1)) + p_buf->offset,
238          no_of_bytes);
239 
240   return p_buf2;
241 }
242 
243 /*******************************************************************************
244  *
245  * Function         l2c_fcr_is_flow_controlled
246  *
247  * Description      This function checks if the CCB is flow controlled by peer.
248  *
249  * Returns          The control word
250  *
251  ******************************************************************************/
l2c_fcr_is_flow_controlled(tL2C_CCB * p_ccb)252 bool l2c_fcr_is_flow_controlled(tL2C_CCB* p_ccb) {
253   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
254   if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) {
255     /* Check if remote side flowed us off or the transmit window is full */
256     if ((p_ccb->fcrb.remote_busy) ||
257         (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q) >= p_ccb->peer_cfg.fcr.tx_win_sz)) {
258       return true;
259     }
260   }
261   return false;
262 }
263 
264 /*******************************************************************************
265  *
266  * Function         prepare_I_frame
267  *
268  * Description      This function sets the FCR variables in an I-frame that is
269  *                  about to be sent to HCI for transmission. This may be the
270  *                  first time the I-frame is sent, or a retransmission
271  *
272  * Returns          -
273  *
274  ******************************************************************************/
prepare_I_frame(tL2C_CCB * p_ccb,BT_HDR * p_buf,bool is_retransmission)275 static void prepare_I_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, bool is_retransmission) {
276   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
277   log::assert_that(p_buf != NULL, "assert failed: p_buf != NULL");
278   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
279   uint8_t* p;
280   uint16_t fcs;
281   uint16_t ctrl_word;
282   bool set_f_bit = p_fcrb->send_f_rsp;
283 
284   uint8_t fcs_len = l2cu_get_fcs_len(p_ccb);
285 
286   p_fcrb->send_f_rsp = false;
287 
288   if (is_retransmission) {
289     /* Get the old control word and clear out the old req_seq and F bits */
290     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
291 
292     STREAM_TO_UINT16(ctrl_word, p);
293 
294     ctrl_word &= ~(L2CAP_FCR_REQ_SEQ_BITS + L2CAP_FCR_F_BIT);
295   } else {
296     ctrl_word = p_buf->layer_specific & L2CAP_FCR_SEG_BITS;            /* SAR bits */
297     ctrl_word |= (p_fcrb->next_tx_seq << L2CAP_FCR_TX_SEQ_BITS_SHIFT); /* Tx Seq */
298 
299     p_fcrb->next_tx_seq = (p_fcrb->next_tx_seq + 1) & L2CAP_FCR_SEQ_MODULO;
300   }
301 
302   /* Set the F-bit and reqseq only if using re-transmission mode */
303   if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) {
304     if (set_f_bit) {
305       ctrl_word |= L2CAP_FCR_F_BIT;
306     }
307 
308     ctrl_word |= (p_fcrb->next_seq_expected) << L2CAP_FCR_REQ_SEQ_BITS_SHIFT;
309 
310     p_fcrb->last_ack_sent = p_ccb->fcrb.next_seq_expected;
311 
312     alarm_cancel(p_ccb->fcrb.ack_timer);
313   }
314 
315   /* Set the control word */
316   p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
317 
318   UINT16_TO_STREAM(p, ctrl_word);
319 
320   /* Compute the FCS and add to the end of the buffer if not bypassed */
321   /* length field in l2cap header has to include FCS length */
322   p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
323   UINT16_TO_STREAM(p, p_buf->len + fcs_len - L2CAP_PKT_OVERHEAD);
324 
325   if (fcs_len != 0) {
326     /* Calculate the FCS */
327     fcs = l2c_fcr_tx_get_fcs(p_buf);
328 
329     /* Point to the end of the buffer and put the FCS there */
330     /*
331      * NOTE: Here we assume the allocated buffer is large enough
332      * to include extra L2CAP_FCS_LEN octets at the end.
333      */
334     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len;
335 
336     UINT16_TO_STREAM(p, fcs);
337 
338     p_buf->len += fcs_len;
339   }
340 
341   if (is_retransmission) {
342     log::verbose(
343             "L2CAP eRTM ReTx I-frame  CID: 0x{:04x}  Len: {}  SAR: {}  TxSeq: {}  "
344             "ReqSeq: {}  F: {}",
345             p_ccb->local_cid, p_buf->len,
346             SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
347             (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
348             (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
349             (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
350   } else {
351     log::verbose(
352             "L2CAP eRTM Tx I-frame CID: 0x{:04x}  Len: {}  SAR: {:<12s}  TxSeq: {} "
353             " ReqSeq: {}  F: {}",
354             p_ccb->local_cid, p_buf->len,
355             SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
356             (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
357             (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
358             (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
359   }
360 
361   /* Start the retransmission timer if not already running */
362   if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) {
363     l2c_fcr_start_timer(p_ccb);
364   }
365 }
366 
367 /*******************************************************************************
368  *
369  * Function         l2c_fcr_send_S_frame
370  *
371  * Description      This function formats and sends an S-frame for transmission.
372  *
373  * Returns          -
374  *
375  ******************************************************************************/
l2c_fcr_send_S_frame(tL2C_CCB * p_ccb,uint16_t function_code,uint16_t pf_bit)376 void l2c_fcr_send_S_frame(tL2C_CCB* p_ccb, uint16_t function_code, uint16_t pf_bit) {
377   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
378   uint8_t* p;
379   uint16_t ctrl_word;
380   uint16_t fcs;
381 
382   if ((!p_ccb->in_use) || (p_ccb->chnl_state != CST_OPEN)) {
383     return;
384   }
385 
386   if (pf_bit == L2CAP_FCR_P_BIT) {
387     p_ccb->fcrb.wait_ack = true;
388 
389     l2c_fcr_stop_timer(p_ccb); /* Restart the monitor timer */
390     l2c_fcr_start_timer(p_ccb);
391   }
392 
393   /* Create the control word to use */
394   ctrl_word = (function_code << L2CAP_FCR_SUP_SHIFT) | L2CAP_FCR_S_FRAME_BIT;
395   ctrl_word |= (p_ccb->fcrb.next_seq_expected << L2CAP_FCR_REQ_SEQ_BITS_SHIFT);
396   ctrl_word |= pf_bit;
397 
398   BT_HDR* p_buf = (BT_HDR*)osi_malloc(L2CAP_CMD_BUF_SIZE);
399   p_buf->offset = HCI_DATA_PREAMBLE_SIZE;
400   p_buf->len = L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD;
401 
402   /* Set the pointer to the beginning of the data */
403   p = (uint8_t*)(p_buf + 1) + p_buf->offset;
404 
405   uint8_t fcs_len = l2cu_get_fcs_len(p_ccb);
406 
407   /* Put in the L2CAP header */
408   UINT16_TO_STREAM(p, L2CAP_FCR_OVERHEAD + fcs_len);
409   UINT16_TO_STREAM(p, p_ccb->remote_cid);
410   UINT16_TO_STREAM(p, ctrl_word);
411 
412   if (fcs_len != 0) {
413     /* Compute the FCS and add to the end of the buffer if not bypassed */
414     fcs = l2c_fcr_tx_get_fcs(p_buf);
415 
416     UINT16_TO_STREAM(p, fcs);
417     p_buf->len += fcs_len;
418   }
419 
420   /* Now, the HCI transport header */
421   p_buf->layer_specific = L2CAP_NON_FLUSHABLE_PKT;
422   l2cu_set_acl_hci_header(p_buf, p_ccb);
423 
424   if ((((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 1) ||
425       (((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 3)) {
426     log::warn(
427             "L2CAP eRTM Tx S-frame  CID: 0x{:04x}  ctrlword: 0x{:04x}  Type: {}  "
428             "ReqSeq: {}  P: {}  F: {}",
429             p_ccb->local_cid, ctrl_word,
430             SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
431             (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
432             (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
433             (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
434     log::warn("Buf Len: {}", p_buf->len);
435   } else {
436     log::verbose(
437             "L2CAP eRTM Tx S-frame  CID: 0x{:04x}  ctrlword: 0x{:04x}  Type: {}  "
438             "ReqSeq: {}  P: {}  F: {}",
439             p_ccb->local_cid, ctrl_word,
440             SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
441             (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
442             (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
443             (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
444     log::verbose("Buf Len: {}", p_buf->len);
445   }
446 
447   l2c_link_check_send_pkts(p_ccb->p_lcb, 0, p_buf);
448 
449   p_ccb->fcrb.last_ack_sent = p_ccb->fcrb.next_seq_expected;
450 
451   alarm_cancel(p_ccb->fcrb.ack_timer);
452 }
453 
454 /*******************************************************************************
455  *
456  * Function         l2c_fcr_proc_pdu
457  *
458  * Description      This function is the entry point for processing of a
459  *                  received PDU when in flow control and/or retransmission
460  *                  modes.
461  *
462  * Returns          -
463  *
464  ******************************************************************************/
l2c_fcr_proc_pdu(tL2C_CCB * p_ccb,BT_HDR * p_buf)465 void l2c_fcr_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) {
466   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
467   log::assert_that(p_buf != NULL, "assert failed: p_buf != NULL");
468   uint8_t* p;
469   uint16_t fcs;
470   uint16_t min_pdu_len;
471   uint16_t ctrl_word;
472 
473   /* Check the length */
474   uint8_t fcs_len = l2cu_get_fcs_len(p_ccb);
475 
476   min_pdu_len = (uint16_t)(fcs_len + L2CAP_FCR_OVERHEAD);
477 
478   if (p_buf->len < min_pdu_len) {
479     log::warn("Rx L2CAP PDU: CID: 0x{:04x}  Len too short: {}", p_ccb->local_cid, p_buf->len);
480     osi_free(p_buf);
481     return;
482   }
483 
484   /* Get the control word */
485   p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
486   STREAM_TO_UINT16(ctrl_word, p);
487 
488   if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) {
489     if ((((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 1) ||
490         (((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 3)) {
491       /* REJ or SREJ */
492       log::warn(
493               "L2CAP eRTM Rx S-frame: cid: 0x{:04x}  Len: {}  Type: {}  ReqSeq: {} "
494               " P: {}  F: {}",
495               p_ccb->local_cid, p_buf->len,
496               SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
497               (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
498               (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
499               (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
500     } else {
501       log::verbose(
502               "L2CAP eRTM Rx S-frame: cid: 0x{:04x}  Len: {}  Type: {}  ReqSeq: {} "
503               " P: {}  F: {}",
504               p_ccb->local_cid, p_buf->len,
505               SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
506               (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
507               (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
508               (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
509     }
510   } else {
511     log::verbose(
512             "L2CAP eRTM Rx I-frame: cid: 0x{:04x}  Len: {}  SAR: {:<12s}  TxSeq: "
513             "{}  ReqSeq: {}  F: {}",
514             p_ccb->local_cid, p_buf->len,
515             SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
516             (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
517             (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
518             (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
519   }
520 
521   log::verbose(
522           "eRTM Rx Nxt_tx_seq {}, Lst_rx_ack {}, Nxt_seq_exp {}, Lst_ack_snt {}, "
523           "wt_q.cnt {}, tries {}",
524           p_ccb->fcrb.next_tx_seq, p_ccb->fcrb.last_rx_ack, p_ccb->fcrb.next_seq_expected,
525           p_ccb->fcrb.last_ack_sent, fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q),
526           p_ccb->fcrb.num_tries);
527 
528   if (fcs_len != 0) {
529     /* Verify FCS if using */
530     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len - fcs_len;
531 
532     /* Extract and drop the FCS from the packet */
533     STREAM_TO_UINT16(fcs, p);
534     p_buf->len -= fcs_len;
535 
536     if (l2c_fcr_rx_get_fcs(p_buf) != fcs) {
537       log::warn("Rx L2CAP PDU: CID: 0x{:04x}  BAD FCS", p_ccb->local_cid);
538       osi_free(p_buf);
539       return;
540     }
541   }
542 
543   /* Get the control word */
544   p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
545 
546   STREAM_TO_UINT16(ctrl_word, p);
547 
548   p_buf->len -= L2CAP_FCR_OVERHEAD;
549   p_buf->offset += L2CAP_FCR_OVERHEAD;
550 
551   /* If we had a poll bit outstanding, check if we got a final response */
552   if (p_ccb->fcrb.wait_ack) {
553     /* If final bit not set, ignore the frame unless it is a polled S-frame */
554     if (!(ctrl_word & L2CAP_FCR_F_BIT)) {
555       if ((ctrl_word & L2CAP_FCR_P_BIT) && (ctrl_word & L2CAP_FCR_S_FRAME_BIT)) {
556         if (p_ccb->fcrb.srej_sent) {
557           l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_SREJ, L2CAP_FCR_F_BIT);
558         } else {
559           l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_F_BIT);
560         }
561 
562         /* Got a poll while in wait_ack state, so re-start our timer with
563          * 1-second */
564         /* This is a small optimization... the monitor timer is 12 secs, but we
565          * saw */
566         /* that if the other side sends us a poll when we are waiting for a
567          * final,  */
568         /* then it speeds up recovery significantly if we poll it back soon
569          * after its poll. */
570         alarm_set_on_mloop(p_ccb->fcrb.mon_retrans_timer, BT_1SEC_TIMEOUT_MS, l2c_ccb_timer_timeout,
571                            p_ccb);
572       }
573       osi_free(p_buf);
574       return;
575     }
576 
577     p_ccb->fcrb.wait_ack = false;
578 
579     /* P and F are mutually exclusive */
580     if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) {
581       ctrl_word &= ~L2CAP_FCR_P_BIT;
582     }
583 
584     if (fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q)) {
585       p_ccb->fcrb.num_tries = 0;
586     }
587 
588     l2c_fcr_stop_timer(p_ccb);
589   } else {
590     /* Otherwise, ensure the final bit is ignored */
591     ctrl_word &= ~L2CAP_FCR_F_BIT;
592   }
593 
594   /* Process receive sequence number */
595   if (!process_reqseq(p_ccb, ctrl_word)) {
596     osi_free(p_buf);
597     return;
598   }
599 
600   /* Process based on whether it is an S-frame or an I-frame */
601   if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) {
602     process_s_frame(p_ccb, p_buf, ctrl_word);
603   } else {
604     process_i_frame(p_ccb, p_buf, ctrl_word, false);
605   }
606 
607   /* Return if the channel got disconnected by a bad packet or max
608    * retransmissions */
609   if ((!p_ccb->in_use) || (p_ccb->chnl_state != CST_OPEN)) {
610     return;
611   }
612 
613   /* If we have some buffers held while doing SREJ, and SREJ has cleared,
614    * process them now */
615   if ((!p_ccb->fcrb.srej_sent) && (!fixed_queue_is_empty(p_ccb->fcrb.srej_rcv_hold_q))) {
616     fixed_queue_t* temp_q = p_ccb->fcrb.srej_rcv_hold_q;
617     p_ccb->fcrb.srej_rcv_hold_q = fixed_queue_new(SIZE_MAX);
618 
619     while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(temp_q)) != NULL) {
620       if (p_ccb->in_use && (p_ccb->chnl_state == CST_OPEN)) {
621         /* Get the control word */
622         p = ((uint8_t*)(p_buf + 1)) + p_buf->offset - L2CAP_FCR_OVERHEAD;
623 
624         STREAM_TO_UINT16(ctrl_word, p);
625 
626         log::verbose(
627                 "l2c_fcr_proc_pdu() CID: 0x{:04x}  Process Buffer from SREJ_Hold_Q "
628                 "  TxSeq: {}  Expected_Seq: {}",
629                 p_ccb->local_cid,
630                 (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
631                 p_ccb->fcrb.next_seq_expected);
632 
633         /* Process the SREJ held I-frame, but do not send an RR for each
634          * individual frame */
635         process_i_frame(p_ccb, p_buf, ctrl_word, true);
636       } else {
637         osi_free(p_buf);
638       }
639 
640       /* If more frames were lost during SREJ, send a REJ */
641       if (p_ccb->fcrb.rej_after_srej) {
642         p_ccb->fcrb.rej_after_srej = false;
643         p_ccb->fcrb.rej_sent = true;
644 
645         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_REJ, 0);
646       }
647     }
648     fixed_queue_free(temp_q, NULL);
649 
650     /* Now, if needed, send one RR for the whole held queue */
651     if ((!p_ccb->fcrb.rej_sent) && (!p_ccb->fcrb.srej_sent) &&
652         (p_ccb->fcrb.next_seq_expected != p_ccb->fcrb.last_ack_sent)) {
653       l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, 0);
654     } else {
655       log::verbose(
656               "l2c_fcr_proc_pdu() not sending RR CID: 0x{:04x}  local_busy:{} "
657               "rej_sent:{} srej_sent:{} Expected_Seq:{} Last_Ack:{}",
658               p_ccb->local_cid, 0, p_ccb->fcrb.rej_sent, p_ccb->fcrb.srej_sent,
659               p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent);
660     }
661   }
662 
663   /* If a window has opened, check if we can send any more packets */
664   if ((!fixed_queue_is_empty(p_ccb->fcrb.retrans_q) || !fixed_queue_is_empty(p_ccb->xmit_hold_q)) &&
665       (!p_ccb->fcrb.wait_ack) && (!l2c_fcr_is_flow_controlled(p_ccb))) {
666     l2c_link_check_send_pkts(p_ccb->p_lcb, 0, NULL);
667   }
668 }
669 
670 /*******************************************************************************
671  *
672  * Function         l2c_lcc_proc_pdu
673  *
674  * Description      This function is the entry point for processing of a
675  *                  received PDU when in LE Coc flow control modes.
676  *
677  * Returns          -
678  *
679  ******************************************************************************/
l2c_lcc_proc_pdu(tL2C_CCB * p_ccb,BT_HDR * p_buf)680 void l2c_lcc_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) {
681   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
682   log::assert_that(p_buf != NULL, "assert failed: p_buf != NULL");
683   uint8_t* p = (uint8_t*)(p_buf + 1) + p_buf->offset;
684   uint16_t sdu_length;
685   BT_HDR* p_data = NULL;
686 
687   uint16_t local_mps = p_ccb->local_conn_cfg.mps;
688   if (com::android::bluetooth::flags::fix_buf_len_check_for_first_k_frame()) {
689     if (p_ccb->is_first_seg) {
690       // for the first k-frame, donot consider sdu_length
691       // as part of the information payload
692       local_mps = p_ccb->local_conn_cfg.mps + sizeof(sdu_length);
693     }
694   }
695 
696   /* Buffer length should not exceed local mps */
697   if (p_buf->len > local_mps) {
698     log::error("buffer length={} exceeds local mps={}. Drop and disconnect.", p_buf->len,
699                local_mps);
700 
701     /* Discard the buffer and disconnect*/
702     osi_free(p_buf);
703     l2cu_disconnect_chnl(p_ccb);
704     return;
705   }
706 
707   if (p_ccb->is_first_seg) {
708     if (p_buf->len < sizeof(sdu_length)) {
709       log::error("buffer length={} too small. Need at least 2.", p_buf->len);
710       /* Discard the buffer */
711       osi_free(p_buf);
712       return;
713     }
714     STREAM_TO_UINT16(sdu_length, p);
715 
716     /* Check the SDU Length with local MTU size */
717     if (sdu_length > p_ccb->local_conn_cfg.mtu) {
718       log::error("sdu length={} exceeds local mtu={}. Drop and disconnect.", sdu_length,
719                  p_ccb->local_conn_cfg.mtu);
720       /* Discard the buffer and disconnect*/
721       osi_free(p_buf);
722       l2cu_disconnect_chnl(p_ccb);
723       return;
724     }
725 
726     p_buf->len -= sizeof(sdu_length);
727     p_buf->offset += sizeof(sdu_length);
728 
729     if (sdu_length < p_buf->len) {
730       log::error("Invalid sdu_length: {}", sdu_length);
731       /* Discard the buffer */
732       osi_free(p_buf);
733       return;
734     }
735 
736     p_data = (BT_HDR*)osi_malloc(BT_HDR_SIZE + sdu_length);
737     if (p_data == NULL) {
738       osi_free(p_buf);
739       return;
740     }
741 
742     p_ccb->ble_sdu = p_data;
743     p_data->len = 0;
744     p_ccb->ble_sdu_length = sdu_length;
745     log::verbose("SDU Length = {}", sdu_length);
746     p_data->offset = 0;
747 
748   } else {
749     p_data = p_ccb->ble_sdu;
750     if (p_data == NULL) {
751       osi_free(p_buf);
752       return;
753     }
754     if (p_buf->len > (p_ccb->ble_sdu_length - p_data->len)) {
755       log::error("buffer length={} too big. max={}. Dropped", p_data->len,
756                  p_ccb->ble_sdu_length - p_data->len);
757       osi_free(p_buf);
758 
759       /* Throw away all pending fragments and disconnects */
760       p_ccb->is_first_seg = true;
761       osi_free(p_ccb->ble_sdu);
762       p_ccb->ble_sdu = NULL;
763       p_ccb->ble_sdu_length = 0;
764       l2cu_disconnect_chnl(p_ccb);
765       return;
766     }
767   }
768 
769   memcpy((uint8_t*)(p_data + 1) + p_data->offset + p_data->len,
770          (uint8_t*)(p_buf + 1) + p_buf->offset, p_buf->len);
771   p_data->len += p_buf->len;
772   p = (uint8_t*)(p_data + 1) + p_data->offset;
773   if (p_data->len == p_ccb->ble_sdu_length) {
774     l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DATA, p_data);
775     p_ccb->is_first_seg = true;
776     p_ccb->ble_sdu = NULL;
777     p_ccb->ble_sdu_length = 0;
778   } else if (p_data->len < p_ccb->ble_sdu_length) {
779     p_ccb->is_first_seg = false;
780   }
781 
782   osi_free(p_buf);
783   return;
784 }
785 
786 /*******************************************************************************
787  *
788  * Function         l2c_fcr_proc_tout
789  *
790  * Description      Handle a timeout. We should be in error recovery state.
791  *
792  * Returns          -
793  *
794  ******************************************************************************/
l2c_fcr_proc_tout(tL2C_CCB * p_ccb)795 void l2c_fcr_proc_tout(tL2C_CCB* p_ccb) {
796   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
797   log::verbose(
798           "l2c_fcr_proc_tout:  CID: 0x{:04x}  num_tries: {} (max: {})  wait_ack: "
799           "{}  ack_q_count: {}",
800           p_ccb->local_cid, p_ccb->fcrb.num_tries, p_ccb->peer_cfg.fcr.max_transmit,
801           p_ccb->fcrb.wait_ack, fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
802 
803   if ((p_ccb->peer_cfg.fcr.max_transmit != 0) &&
804       (++p_ccb->fcrb.num_tries > p_ccb->peer_cfg.fcr.max_transmit)) {
805     l2cu_disconnect_chnl(p_ccb);
806   } else {
807     if (!p_ccb->fcrb.srej_sent && !p_ccb->fcrb.rej_sent) {
808       l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_P_BIT);
809     }
810   }
811 }
812 
813 /*******************************************************************************
814  *
815  * Function         l2c_fcr_proc_ack_tout
816  *
817  * Description      Send RR/RNR if we have not acked I frame
818  *
819  * Returns          -
820  *
821  ******************************************************************************/
l2c_fcr_proc_ack_tout(tL2C_CCB * p_ccb)822 void l2c_fcr_proc_ack_tout(tL2C_CCB* p_ccb) {
823   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
824   log::verbose(
825           "l2c_fcr_proc_ack_tout:  CID: 0x{:04x} State: {}  Wack:{}  Rq:{}  "
826           "Acked:{}",
827           p_ccb->local_cid, p_ccb->chnl_state, p_ccb->fcrb.wait_ack, p_ccb->fcrb.next_seq_expected,
828           p_ccb->fcrb.last_ack_sent);
829 
830   if ((p_ccb->chnl_state == CST_OPEN) && (!p_ccb->fcrb.wait_ack) &&
831       (p_ccb->fcrb.last_ack_sent != p_ccb->fcrb.next_seq_expected)) {
832     l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, 0);
833   }
834 }
835 
836 /*******************************************************************************
837  *
838  * Function         process_reqseq
839  *
840  * Description      Handle receive sequence number
841  *
842  * Returns          -
843  *
844  ******************************************************************************/
process_reqseq(tL2C_CCB * p_ccb,uint16_t ctrl_word)845 static bool process_reqseq(tL2C_CCB* p_ccb, uint16_t ctrl_word) {
846   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
847   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
848   uint8_t req_seq, num_bufs_acked, xx;
849   uint16_t ls;
850   uint16_t full_sdus_xmitted;
851 
852   /* Receive sequence number does not ack anything for SREJ with P-bit set to
853    * zero */
854   if ((ctrl_word & L2CAP_FCR_S_FRAME_BIT) &&
855       ((ctrl_word & L2CAP_FCR_SUP_BITS) == (L2CAP_FCR_SUP_SREJ << L2CAP_FCR_SUP_SHIFT)) &&
856       ((ctrl_word & L2CAP_FCR_P_BIT) == 0)) {
857     /* If anything still waiting for ack, restart the timer if it was stopped */
858     if (!fixed_queue_is_empty(p_fcrb->waiting_for_ack_q)) {
859       l2c_fcr_start_timer(p_ccb);
860     }
861 
862     return true;
863   }
864 
865   /* Extract the receive sequence number from the control word */
866   req_seq = (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT;
867 
868   num_bufs_acked = (req_seq - p_fcrb->last_rx_ack) & L2CAP_FCR_SEQ_MODULO;
869 
870   /* Verify the request sequence is in range before proceeding */
871   if (num_bufs_acked > fixed_queue_length(p_fcrb->waiting_for_ack_q)) {
872     /* The channel is closed if ReqSeq is not in range */
873     log::warn(
874             "L2CAP eRTM Frame BAD Req_Seq - ctrl_word: 0x{:04x}  req_seq 0x{:02x}  "
875             "last_rx_ack: 0x{:02x}  QCount: {}",
876             ctrl_word, req_seq, p_fcrb->last_rx_ack, fixed_queue_length(p_fcrb->waiting_for_ack_q));
877 
878     l2cu_disconnect_chnl(p_ccb);
879     return false;
880   }
881 
882   p_fcrb->last_rx_ack = req_seq;
883 
884   /* Now we can release all acknowledged frames, and restart the retransmission
885    * timer if needed */
886   if (num_bufs_acked != 0) {
887     p_fcrb->num_tries = 0;
888     full_sdus_xmitted = 0;
889 
890     for (xx = 0; xx < num_bufs_acked; xx++) {
891       BT_HDR* p_tmp = (BT_HDR*)fixed_queue_try_dequeue(p_fcrb->waiting_for_ack_q);
892       ls = p_tmp->layer_specific & L2CAP_FCR_SAR_BITS;
893 
894       if ((ls == L2CAP_FCR_UNSEG_SDU) || (ls == L2CAP_FCR_END_SDU)) {
895         full_sdus_xmitted++;
896       }
897 
898       osi_free(p_tmp);
899     }
900 
901     /* If we are still in a wait_ack state, do not mess with the timer */
902     if (!p_ccb->fcrb.wait_ack) {
903       l2c_fcr_stop_timer(p_ccb);
904     }
905 
906     /* Check if we need to call the "packet_sent" callback */
907     if ((p_ccb->p_rcb) && (p_ccb->p_rcb->api.pL2CA_TxComplete_Cb) && (full_sdus_xmitted)) {
908       /* Special case for eRTM, if all packets sent, send 0xFFFF */
909       if (fixed_queue_is_empty(p_fcrb->waiting_for_ack_q) &&
910           fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
911         full_sdus_xmitted = 0xFFFF;
912       }
913 
914       (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid, full_sdus_xmitted);
915     }
916   }
917 
918   /* If anything still waiting for ack, restart the timer if it was stopped */
919   if (!fixed_queue_is_empty(p_fcrb->waiting_for_ack_q)) {
920     l2c_fcr_start_timer(p_ccb);
921   }
922   return true;
923 }
924 
925 /*******************************************************************************
926  *
927  * Function         process_s_frame
928  *
929  * Description      Process an S frame
930  *
931  * Returns          -
932  *
933  ******************************************************************************/
process_s_frame(tL2C_CCB * p_ccb,BT_HDR * p_buf,uint16_t ctrl_word)934 static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word) {
935   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
936   log::assert_that(p_buf != NULL, "assert failed: p_buf != NULL");
937 
938   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
939   uint16_t s_frame_type = (ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT;
940   bool remote_was_busy;
941   bool all_ok = true;
942 
943   if (p_buf->len != 0) {
944     log::warn("Incorrect S-frame Length ({})", p_buf->len);
945   }
946 
947   log::verbose("process_s_frame ctrl_word 0x{:04x} fcrb_remote_busy:{}", ctrl_word,
948                p_fcrb->remote_busy);
949 
950   if (ctrl_word & L2CAP_FCR_P_BIT) {
951     p_fcrb->rej_sent = false;  /* After checkpoint, we can send another REJ */
952     p_fcrb->send_f_rsp = true; /* Set a flag in case an I-frame is pending */
953   }
954 
955   switch (s_frame_type) {
956     case L2CAP_FCR_SUP_RR:
957       remote_was_busy = p_fcrb->remote_busy;
958       p_fcrb->remote_busy = false;
959 
960       if ((ctrl_word & L2CAP_FCR_F_BIT) || (remote_was_busy)) {
961         all_ok = retransmit_i_frames(p_ccb, L2C_FCR_RETX_ALL_PKTS);
962       }
963       break;
964 
965     case L2CAP_FCR_SUP_REJ:
966       p_fcrb->remote_busy = false;
967       all_ok = retransmit_i_frames(p_ccb, L2C_FCR_RETX_ALL_PKTS);
968       break;
969 
970     case L2CAP_FCR_SUP_RNR:
971       p_fcrb->remote_busy = true;
972       l2c_fcr_stop_timer(p_ccb);
973       break;
974 
975     case L2CAP_FCR_SUP_SREJ:
976       p_fcrb->remote_busy = false;
977       all_ok = retransmit_i_frames(p_ccb, (uint8_t)((ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >>
978                                                     L2CAP_FCR_REQ_SEQ_BITS_SHIFT));
979       break;
980   }
981 
982   if (all_ok) {
983     /* If polled, we need to respond with F-bit. Note, we may have sent a
984      * I-frame with the F-bit */
985     if (p_fcrb->send_f_rsp) {
986       if (p_fcrb->srej_sent) {
987         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_SREJ, L2CAP_FCR_F_BIT);
988       } else {
989         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_F_BIT);
990       }
991 
992       p_fcrb->send_f_rsp = false;
993     }
994   } else {
995     log::verbose("process_s_frame hit_max_retries");
996   }
997 
998   osi_free(p_buf);
999 }
1000 
1001 /*******************************************************************************
1002  *
1003  * Function         process_i_frame
1004  *
1005  * Description      Process an I frame
1006  *
1007  * Returns          -
1008  *
1009  ******************************************************************************/
process_i_frame(tL2C_CCB * p_ccb,BT_HDR * p_buf,uint16_t ctrl_word,bool delay_ack)1010 static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word, bool delay_ack) {
1011   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
1012   log::assert_that(p_buf != NULL, "assert failed: p_buf != NULL");
1013 
1014   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
1015   uint8_t tx_seq, num_lost, num_to_ack, next_srej;
1016 
1017   /* If we were doing checkpoint recovery, first retransmit all unacked I-frames
1018    */
1019   if (ctrl_word & L2CAP_FCR_F_BIT) {
1020     if (!retransmit_i_frames(p_ccb, L2C_FCR_RETX_ALL_PKTS)) {
1021       osi_free(p_buf);
1022       return;
1023     }
1024   }
1025 
1026   /* Extract the sequence number */
1027   tx_seq = (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;
1028 
1029   /* Check if tx-sequence is the expected one */
1030   if (tx_seq != p_fcrb->next_seq_expected) {
1031     num_lost = (tx_seq - p_fcrb->next_seq_expected) & L2CAP_FCR_SEQ_MODULO;
1032 
1033     /* Is the frame a duplicate ? If so, just drop it */
1034     if (num_lost >= p_ccb->our_cfg.fcr.tx_win_sz) {
1035       /* Duplicate - simply drop it */
1036       log::warn(
1037               "process_i_frame() Dropping Duplicate Frame tx_seq:{}  ExpectedTxSeq "
1038               "{}",
1039               tx_seq, p_fcrb->next_seq_expected);
1040       osi_free(p_buf);
1041     } else {
1042       log::warn(
1043               "process_i_frame() CID: 0x{:04x}  Lost: {}  tx_seq:{}  ExpTxSeq {}  "
1044               "Rej: {}  SRej: {}",
1045               p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected, p_fcrb->rej_sent,
1046               p_fcrb->srej_sent);
1047 
1048       if (p_fcrb->srej_sent) {
1049         /* If SREJ sent, save the frame for later processing as long as it is in
1050          * sequence */
1051         next_srej = (((BT_HDR*)fixed_queue_try_peek_last(p_fcrb->srej_rcv_hold_q))->layer_specific +
1052                      1) &
1053                     L2CAP_FCR_SEQ_MODULO;
1054 
1055         if ((tx_seq == next_srej) &&
1056             (fixed_queue_length(p_fcrb->srej_rcv_hold_q) < p_ccb->our_cfg.fcr.tx_win_sz)) {
1057           log::verbose(
1058                   "process_i_frame() Lost: {}  tx_seq:{}  ExpTxSeq {}  Rej: {}  "
1059                   "SRej1",
1060                   num_lost, tx_seq, p_fcrb->next_seq_expected, p_fcrb->rej_sent);
1061 
1062           p_buf->layer_specific = tx_seq;
1063           fixed_queue_enqueue(p_fcrb->srej_rcv_hold_q, p_buf);
1064         } else {
1065           log::warn(
1066                   "process_i_frame() CID: 0x{:04x}  frame dropped in Srej Sent "
1067                   "next_srej:{}  hold_q.count:{}  win_sz:{}",
1068                   p_ccb->local_cid, next_srej, fixed_queue_length(p_fcrb->srej_rcv_hold_q),
1069                   p_ccb->our_cfg.fcr.tx_win_sz);
1070 
1071           p_fcrb->rej_after_srej = true;
1072           osi_free(p_buf);
1073         }
1074       } else if (p_fcrb->rej_sent) {
1075         log::warn(
1076                 "process_i_frame() CID: 0x{:04x}  Lost: {}  tx_seq:{}  ExpTxSeq {} "
1077                 " Rej: 1  SRej: {}",
1078                 p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected, p_fcrb->srej_sent);
1079 
1080         /* If REJ sent, just drop the frame */
1081         osi_free(p_buf);
1082       } else {
1083         log::verbose("process_i_frame() CID: 0x{:04x}  tx_seq:{}  ExpTxSeq {}  Rej: {}",
1084                      p_ccb->local_cid, tx_seq, p_fcrb->next_seq_expected, p_fcrb->rej_sent);
1085 
1086         /* If only one lost, we will send SREJ, otherwise we will send REJ */
1087         if (num_lost > 1) {
1088           osi_free(p_buf);
1089           p_fcrb->rej_sent = true;
1090           l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_REJ, 0);
1091         } else {
1092           if (!fixed_queue_is_empty(p_fcrb->srej_rcv_hold_q)) {
1093             log::error(
1094                     "process_i_frame() CID: 0x{:04x}  sending SREJ tx_seq:{} "
1095                     "hold_q.count:{}",
1096                     p_ccb->local_cid, tx_seq, fixed_queue_length(p_fcrb->srej_rcv_hold_q));
1097           }
1098           p_buf->layer_specific = tx_seq;
1099           fixed_queue_enqueue(p_fcrb->srej_rcv_hold_q, p_buf);
1100           p_fcrb->srej_sent = true;
1101           l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_SREJ, 0);
1102         }
1103         alarm_cancel(p_ccb->fcrb.ack_timer);
1104       }
1105     }
1106     return;
1107   }
1108 
1109   /* Seq number is the next expected. Clear possible reject exception in case it occurred */
1110   p_fcrb->rej_sent = p_fcrb->srej_sent = false;
1111 
1112   /* Adjust the next_seq, so that if the upper layer sends more data in the
1113      callback
1114      context, the received frame is acked by an I-frame. */
1115   p_fcrb->next_seq_expected = (tx_seq + 1) & L2CAP_FCR_SEQ_MODULO;
1116 
1117   /* If any SAR problem in eRTM mode, spec says disconnect. */
1118   if (!do_sar_reassembly(p_ccb, p_buf, ctrl_word)) {
1119     log::warn("process_i_frame() CID: 0x{:04x}  reassembly failed", p_ccb->local_cid);
1120     l2cu_disconnect_chnl(p_ccb);
1121     return;
1122   }
1123 
1124   /* RR optimization - if peer can still send us more, then start an ACK timer
1125    */
1126   num_to_ack = (p_fcrb->next_seq_expected - p_fcrb->last_ack_sent) & L2CAP_FCR_SEQ_MODULO;
1127 
1128   if (num_to_ack < p_ccb->fcrb.max_held_acks) {
1129     delay_ack = true;
1130   }
1131 
1132   /* We should neve never ack frame if we are not in OPEN state */
1133   if ((num_to_ack != 0) && p_ccb->in_use && (p_ccb->chnl_state == CST_OPEN)) {
1134     /* If no frames are awaiting transmission or are held, send an RR or RNR
1135      * S-frame for ack */
1136     if (delay_ack) {
1137       /* If it is the first I frame we did not ack, start ack timer */
1138       if (!alarm_is_scheduled(p_ccb->fcrb.ack_timer)) {
1139         alarm_set_on_mloop(p_ccb->fcrb.ack_timer, L2CAP_FCR_ACK_TIMEOUT_MS,
1140                            l2c_fcrb_ack_timer_timeout, p_ccb);
1141       }
1142     } else if ((fixed_queue_is_empty(p_ccb->xmit_hold_q) || l2c_fcr_is_flow_controlled(p_ccb)) &&
1143                fixed_queue_is_empty(p_ccb->fcrb.srej_rcv_hold_q)) {
1144       l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, 0);
1145     }
1146   }
1147 }
1148 
1149 /*******************************************************************************
1150  *
1151  * Function         do_sar_reassembly
1152  *
1153  * Description      Process SAR bits and re-assemble frame
1154  *
1155  * Returns          true if all OK, else false
1156  *
1157  ******************************************************************************/
do_sar_reassembly(tL2C_CCB * p_ccb,BT_HDR * p_buf,uint16_t ctrl_word)1158 static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word) {
1159   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
1160   log::assert_that(p_buf != NULL, "assert failed: p_buf != NULL");
1161 
1162   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
1163   uint16_t sar_type = ctrl_word & L2CAP_FCR_SEG_BITS;
1164   bool packet_ok = true;
1165   uint8_t* p;
1166 
1167   /* Check if the SAR state is correct */
1168   if ((sar_type == L2CAP_FCR_UNSEG_SDU) || (sar_type == L2CAP_FCR_START_SDU)) {
1169     if (p_fcrb->p_rx_sdu != NULL) {
1170       log::warn(
1171               "SAR - got unexpected unsegmented or start SDU  Expected len: {}  "
1172               "Got so far: {}",
1173               p_fcrb->rx_sdu_len, p_fcrb->p_rx_sdu->len);
1174 
1175       packet_ok = false;
1176     }
1177     /* Check the length of the packet */
1178     if ((sar_type == L2CAP_FCR_START_SDU) && (p_buf->len < L2CAP_SDU_LEN_OVERHEAD)) {
1179       log::warn("SAR start packet too short: {}", p_buf->len);
1180       packet_ok = false;
1181     }
1182   } else {
1183     if (p_fcrb->p_rx_sdu == NULL) {
1184       log::warn("SAR - got unexpected cont or end SDU");
1185       packet_ok = false;
1186     }
1187   }
1188 
1189   if ((packet_ok) && (sar_type != L2CAP_FCR_UNSEG_SDU)) {
1190     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
1191 
1192     /* For start SDU packet, extract the SDU length */
1193     if (sar_type == L2CAP_FCR_START_SDU) {
1194       /* Get the SDU length */
1195       STREAM_TO_UINT16(p_fcrb->rx_sdu_len, p);
1196       p_buf->offset += 2;
1197       p_buf->len -= 2;
1198 
1199       if (p_fcrb->rx_sdu_len > p_ccb->max_rx_mtu) {
1200         log::warn("SAR - SDU len: {}  larger than MTU: {}", p_fcrb->rx_sdu_len, p_ccb->max_rx_mtu);
1201         packet_ok = false;
1202       } else {
1203         p_fcrb->p_rx_sdu =
1204                 (BT_HDR*)osi_malloc(BT_HDR_SIZE + OBX_BUF_MIN_OFFSET + p_fcrb->rx_sdu_len);
1205         p_fcrb->p_rx_sdu->offset = OBX_BUF_MIN_OFFSET;
1206         p_fcrb->p_rx_sdu->len = 0;
1207       }
1208     }
1209 
1210     if (packet_ok) {
1211       if ((p_fcrb->p_rx_sdu->len + p_buf->len) > p_fcrb->rx_sdu_len) {
1212         log::error("SAR - SDU len exceeded  Type: {}   Lengths: {} {} {}", sar_type,
1213                    p_fcrb->p_rx_sdu->len, p_buf->len, p_fcrb->rx_sdu_len);
1214         packet_ok = false;
1215       } else if ((sar_type == L2CAP_FCR_END_SDU) &&
1216                  ((p_fcrb->p_rx_sdu->len + p_buf->len) != p_fcrb->rx_sdu_len)) {
1217         log::warn("SAR - SDU end rcvd but SDU incomplete: {} {} {}", p_fcrb->p_rx_sdu->len,
1218                   p_buf->len, p_fcrb->rx_sdu_len);
1219         packet_ok = false;
1220       } else {
1221         memcpy(((uint8_t*)(p_fcrb->p_rx_sdu + 1)) + p_fcrb->p_rx_sdu->offset +
1222                        p_fcrb->p_rx_sdu->len,
1223                p, p_buf->len);
1224 
1225         p_fcrb->p_rx_sdu->len += p_buf->len;
1226 
1227         osi_free(p_buf);
1228         p_buf = NULL;
1229 
1230         if (sar_type == L2CAP_FCR_END_SDU) {
1231           p_buf = p_fcrb->p_rx_sdu;
1232           p_fcrb->p_rx_sdu = NULL;
1233         }
1234       }
1235     }
1236   }
1237 
1238   if (!packet_ok) {
1239     osi_free(p_buf);
1240   } else if (p_buf != NULL) {
1241     if (p_ccb->local_cid < L2CAP_BASE_APPL_CID &&
1242         (p_ccb->local_cid >= L2CAP_FIRST_FIXED_CHNL && p_ccb->local_cid <= L2CAP_LAST_FIXED_CHNL)) {
1243       if (l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL].pL2CA_FixedData_Cb) {
1244         l2cu_fixed_channel_data_cb(p_ccb->p_lcb, p_ccb->local_cid, p_buf);
1245       }
1246     } else {
1247       l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DATA, p_buf);
1248     }
1249   }
1250 
1251   return packet_ok;
1252 }
1253 
1254 /*******************************************************************************
1255  *
1256  * Function         retransmit_i_frames
1257  *
1258  * Description      This function retransmits i-frames awaiting acks.
1259  *
1260  * Returns          bool    - true if retransmitted
1261  *
1262  ******************************************************************************/
retransmit_i_frames(tL2C_CCB * p_ccb,uint8_t tx_seq)1263 static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq) {
1264   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
1265 
1266   BT_HDR* p_buf = NULL;
1267   uint8_t* p;
1268   uint8_t buf_seq;
1269   uint16_t ctrl_word;
1270 
1271   if ((!fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q)) &&
1272       (p_ccb->peer_cfg.fcr.max_transmit != 0) &&
1273       (p_ccb->fcrb.num_tries >= p_ccb->peer_cfg.fcr.max_transmit)) {
1274     log::verbose(
1275             "Max Tries Exceeded:  (last_acq: {}  CID: 0x{:04x}  num_tries: {} "
1276             "(max: {}) ack_q_count: {}",
1277             p_ccb->fcrb.last_rx_ack, p_ccb->local_cid, p_ccb->fcrb.num_tries,
1278             p_ccb->peer_cfg.fcr.max_transmit, fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
1279 
1280     l2cu_disconnect_chnl(p_ccb);
1281     return false;
1282   }
1283 
1284   /* tx_seq indicates whether to retransmit a specific sequence or all (if ==
1285    * L2C_FCR_RETX_ALL_PKTS) */
1286   list_t* list_ack = NULL;
1287   const list_node_t* node_ack = NULL;
1288   if (!fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q)) {
1289     list_ack = fixed_queue_get_list(p_ccb->fcrb.waiting_for_ack_q);
1290     node_ack = list_begin(list_ack);
1291   }
1292   if (tx_seq != L2C_FCR_RETX_ALL_PKTS) {
1293     /* If sending only one, the sequence number tells us which one. Look for it.
1294      */
1295     if (list_ack != NULL) {
1296       for (; node_ack != list_end(list_ack); node_ack = list_next(node_ack)) {
1297         p_buf = (BT_HDR*)list_node(node_ack);
1298         /* Get the old control word */
1299         p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
1300 
1301         STREAM_TO_UINT16(ctrl_word, p);
1302 
1303         buf_seq = (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;
1304 
1305         log::verbose("retransmit_i_frames()   cur seq: {}  looking for: {}", buf_seq, tx_seq);
1306 
1307         if (tx_seq == buf_seq) {
1308           break;
1309         }
1310       }
1311     }
1312 
1313     if (!p_buf) {
1314       log::error("retransmit_i_frames() UNKNOWN seq: {}  q_count: {}", tx_seq,
1315                  fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
1316       return true;
1317     }
1318   } else {
1319     // Iterate though list and flush the amount requested from
1320     // the transmit data queue that satisfy the layer and event conditions.
1321     for (list_node_t* node_tmp = list_begin(p_ccb->p_lcb->link_xmit_data_q);
1322          node_tmp != list_end(p_ccb->p_lcb->link_xmit_data_q);) {
1323       BT_HDR* p_tmp = (BT_HDR*)list_node(node_tmp);
1324       node_tmp = list_next(node_tmp);
1325 
1326       /* Do not flush other CIDs or partial segments */
1327       if ((p_tmp->layer_specific == 0) && (p_tmp->event == p_ccb->local_cid)) {
1328         list_remove(p_ccb->p_lcb->link_xmit_data_q, p_tmp);
1329         osi_free(p_tmp);
1330       }
1331     }
1332 
1333     /* Also flush our retransmission queue */
1334     while (!fixed_queue_is_empty(p_ccb->fcrb.retrans_q)) {
1335       osi_free(fixed_queue_try_dequeue(p_ccb->fcrb.retrans_q));
1336     }
1337 
1338     if (list_ack != NULL) {
1339       node_ack = list_begin(list_ack);
1340     }
1341   }
1342 
1343   if (list_ack != NULL) {
1344     while (node_ack != list_end(list_ack)) {
1345       p_buf = (BT_HDR*)list_node(node_ack);
1346       node_ack = list_next(node_ack);
1347 
1348       BT_HDR* p_buf2 = l2c_fcr_clone_buf(p_buf, p_buf->offset, p_buf->len);
1349       if (p_buf2) {
1350         p_buf2->layer_specific = p_buf->layer_specific;
1351 
1352         fixed_queue_enqueue(p_ccb->fcrb.retrans_q, p_buf2);
1353       }
1354 
1355       if ((tx_seq != L2C_FCR_RETX_ALL_PKTS) || (p_buf2 == NULL)) {
1356         break;
1357       }
1358     }
1359   }
1360 
1361   l2c_link_check_send_pkts(p_ccb->p_lcb, 0, NULL);
1362 
1363   if (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q)) {
1364     p_ccb->fcrb.num_tries++;
1365     l2c_fcr_start_timer(p_ccb);
1366   }
1367 
1368   return true;
1369 }
1370 
1371 /*******************************************************************************
1372  *
1373  * Function         l2c_fcr_get_next_xmit_sdu_seg
1374  *
1375  * Description      Get the next SDU segment to transmit.
1376  *
1377  * Returns          pointer to buffer with segment or NULL
1378  *
1379  ******************************************************************************/
l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB * p_ccb,uint16_t max_packet_length)1380 BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, uint16_t max_packet_length) {
1381   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
1382 
1383   bool first_seg = false,   /* The segment is the first part of data  */
1384           mid_seg = false,  /* The segment is the middle part of data */
1385           last_seg = false; /* The segment is the last part of data   */
1386   uint16_t sdu_len = 0;
1387   BT_HDR *p_buf, *p_xmit;
1388   uint8_t* p;
1389   uint16_t max_pdu = p_ccb->tx_mps /* Needed? - L2CAP_MAX_HEADER_FCS*/;
1390 
1391   /* If there is anything in the retransmit queue, that goes first
1392    */
1393   p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->fcrb.retrans_q);
1394   if (p_buf != NULL) {
1395     /* Update Rx Seq and FCS if we acked some packets while this one was queued
1396      */
1397     prepare_I_frame(p_ccb, p_buf, true);
1398 
1399     p_buf->event = p_ccb->local_cid;
1400 
1401     return p_buf;
1402   }
1403 
1404   /* For BD/EDR controller, max_packet_length is set to 0             */
1405   /* For AMP controller, max_packet_length is set by available blocks */
1406   if ((max_packet_length > L2CAP_MAX_HEADER_FCS) &&
1407       (max_pdu + L2CAP_MAX_HEADER_FCS > max_packet_length)) {
1408     max_pdu = max_packet_length - L2CAP_MAX_HEADER_FCS;
1409   }
1410 
1411   p_buf = (BT_HDR*)fixed_queue_try_peek_first(p_ccb->xmit_hold_q);
1412 
1413   /* If there is more data than the MPS, it requires segmentation */
1414   if (p_buf->len > max_pdu) {
1415     /* We are using the "event" field to tell is if we already started
1416      * segmentation */
1417     if (p_buf->event == 0) {
1418       first_seg = true;
1419       sdu_len = p_buf->len;
1420     } else {
1421       mid_seg = true;
1422     }
1423 
1424     /* Get a new buffer and copy the data that can be sent in a PDU */
1425     p_xmit = l2c_fcr_clone_buf(p_buf, L2CAP_MIN_OFFSET + L2CAP_SDU_LEN_OFFSET, max_pdu);
1426 
1427     if (p_xmit != NULL) {
1428       p_buf->event = p_ccb->local_cid;
1429       p_xmit->event = p_ccb->local_cid;
1430 
1431       p_buf->len -= max_pdu;
1432       p_buf->offset += max_pdu;
1433 
1434       /* copy PBF setting */
1435       p_xmit->layer_specific = p_buf->layer_specific;
1436     } else {
1437       /* Should never happen if the application has configured buffers correctly */
1438       log::error("L2CAP - cannot get buffer for segmentation, max_pdu: {}", max_pdu);
1439       return NULL;
1440     }
1441   } else {
1442     /* Use the original buffer if no segmentation, or the last segment */
1443     p_xmit = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
1444 
1445     if (p_xmit->event != 0) {
1446       last_seg = true;
1447     }
1448 
1449     p_xmit->event = p_ccb->local_cid;
1450   }
1451 
1452   /* Step back to add the L2CAP headers */
1453   p_xmit->offset -= (L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD);
1454   p_xmit->len += L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD;
1455 
1456   if (first_seg) {
1457     p_xmit->offset -= L2CAP_SDU_LEN_OVERHEAD;
1458     p_xmit->len += L2CAP_SDU_LEN_OVERHEAD;
1459   }
1460 
1461   /* Set the pointer to the beginning of the data */
1462   p = (uint8_t*)(p_xmit + 1) + p_xmit->offset;
1463 
1464   /* Now the L2CAP header */
1465 
1466   /* Note: if FCS has to be included then the length is recalculated later */
1467   UINT16_TO_STREAM(p, p_xmit->len - L2CAP_PKT_OVERHEAD);
1468 
1469   UINT16_TO_STREAM(p, p_ccb->remote_cid);
1470 
1471   if (first_seg) {
1472     /* Skip control word and add SDU length */
1473     p += 2;
1474     UINT16_TO_STREAM(p, sdu_len);
1475 
1476     /* We will store the SAR type in layer-specific */
1477     /* layer_specific is shared with flushable flag(bits 0-1), don't clear it */
1478     p_xmit->layer_specific |= L2CAP_FCR_START_SDU;
1479 
1480     first_seg = false;
1481   } else if (mid_seg) {
1482     p_xmit->layer_specific |= L2CAP_FCR_CONT_SDU;
1483   } else if (last_seg) {
1484     p_xmit->layer_specific |= L2CAP_FCR_END_SDU;
1485   } else {
1486     p_xmit->layer_specific |= L2CAP_FCR_UNSEG_SDU;
1487   }
1488 
1489   prepare_I_frame(p_ccb, p_xmit, false);
1490   uint8_t fcs_len = l2cu_get_fcs_len(p_ccb);
1491 
1492   if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) {
1493     BT_HDR* p_wack = l2c_fcr_clone_buf(p_xmit, HCI_DATA_PREAMBLE_SIZE, p_xmit->len);
1494 
1495     if (!p_wack) {
1496       log::error("L2CAP - no buffer for xmit cloning, CID: 0x{:04x}  Length: {}", p_ccb->local_cid,
1497                  p_xmit->len);
1498 
1499       /* We will not save the FCS in case we reconfigure and change options */
1500       p_xmit->len -= fcs_len;
1501 
1502       /* Pretend we sent it and it got lost */
1503       fixed_queue_enqueue(p_ccb->fcrb.waiting_for_ack_q, p_xmit);
1504       return NULL;
1505     } else {
1506       /* We will not save the FCS in case we reconfigure and change options */
1507       p_wack->len -= fcs_len;
1508 
1509       p_wack->layer_specific = p_xmit->layer_specific;
1510       fixed_queue_enqueue(p_ccb->fcrb.waiting_for_ack_q, p_wack);
1511     }
1512   }
1513 
1514   return p_xmit;
1515 }
1516 
1517 /** Get the next PDU to transmit for LE connection oriented channel. Returns
1518  * pointer to buffer with PDU. |last_piece_of_sdu| will be set to true, if
1519  * returned PDU is last piece from this SDU.*/
l2c_lcc_get_next_xmit_sdu_seg(tL2C_CCB * p_ccb,bool * last_piece_of_sdu)1520 BT_HDR* l2c_lcc_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb, bool* last_piece_of_sdu) {
1521   uint16_t max_pdu = p_ccb->peer_conn_cfg.mps - 4 /* Length and CID */;
1522 
1523   BT_HDR* p_buf = (BT_HDR*)fixed_queue_try_peek_first(p_ccb->xmit_hold_q);
1524   bool first_pdu = (p_buf->event == 0) ? true : false;
1525 
1526   uint16_t no_of_bytes_to_send =
1527           std::min(p_buf->len, (uint16_t)(first_pdu ? (max_pdu - L2CAP_LCC_SDU_LENGTH) : max_pdu));
1528   bool last_pdu = (no_of_bytes_to_send == p_buf->len);
1529 
1530   /* Get a new buffer and copy the data that can be sent in a PDU */
1531   BT_HDR* p_xmit = l2c_fcr_clone_buf(p_buf, first_pdu ? L2CAP_LCC_OFFSET : L2CAP_MIN_OFFSET,
1532                                      no_of_bytes_to_send);
1533 
1534   p_buf->event = p_ccb->local_cid;
1535   p_xmit->event = p_ccb->local_cid;
1536 
1537   if (first_pdu) {
1538     p_xmit->offset -= L2CAP_LCC_SDU_LENGTH; /* for writing the SDU length. */
1539     uint8_t* p = (uint8_t*)(p_xmit + 1) + p_xmit->offset;
1540     UINT16_TO_STREAM(p, p_buf->len);
1541     p_xmit->len += L2CAP_LCC_SDU_LENGTH;
1542   }
1543 
1544   p_buf->len -= no_of_bytes_to_send;
1545   p_buf->offset += no_of_bytes_to_send;
1546 
1547   /* copy PBF setting */
1548   p_xmit->layer_specific = p_buf->layer_specific;
1549 
1550   if (last_piece_of_sdu) {
1551     *last_piece_of_sdu = last_pdu;
1552   }
1553 
1554   if (last_pdu) {
1555     p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
1556     osi_free(p_buf);
1557   }
1558 
1559   /* Step back to add the L2CAP headers */
1560   p_xmit->offset -= L2CAP_PKT_OVERHEAD;
1561   p_xmit->len += L2CAP_PKT_OVERHEAD;
1562 
1563   /* Set the pointer to the beginning of the data */
1564   uint8_t* p = (uint8_t*)(p_xmit + 1) + p_xmit->offset;
1565 
1566   /* Note: if FCS has to be included then the length is recalculated later */
1567   UINT16_TO_STREAM(p, p_xmit->len - L2CAP_PKT_OVERHEAD);
1568   UINT16_TO_STREAM(p, p_ccb->remote_cid);
1569   return p_xmit;
1570 }
1571 
1572 /*******************************************************************************
1573  * Configuration negotiation functions
1574  *
1575  * The following functions are used in negotiating channel modes during
1576  * configuration
1577  ******************************************************************************/
1578 
1579 /*******************************************************************************
1580  *
1581  * Function         l2c_fcr_chk_chan_modes
1582  *
1583  * Description      Validates and adjusts if necessary, the FCR options
1584  *                  based on remote EXT features.
1585  *
1586  *                  Note: This assumes peer EXT Features have been received.
1587  *                      Basic mode is used if FCR Options have not been received
1588  *
1589  * Returns          uint8_t - nonzero if can continue, '0' if no compatible
1590  *                            channels
1591  *
1592  ******************************************************************************/
l2c_fcr_chk_chan_modes(tL2C_CCB * p_ccb)1593 uint8_t l2c_fcr_chk_chan_modes(tL2C_CCB* p_ccb) {
1594   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
1595 
1596   /* Remove nonbasic options that the peer does not support */
1597   if (!(p_ccb->p_lcb->peer_ext_fea & L2CAP_EXTFEA_ENH_RETRANS) &&
1598       p_ccb->p_rcb->ertm_info.preferred_mode == L2CAP_FCR_ERTM_MODE) {
1599     log::warn("L2CAP - Peer does not support our desired channel types");
1600     p_ccb->p_rcb->ertm_info.preferred_mode = 0;
1601     return false;
1602   }
1603   return true;
1604 }
1605 
1606 /*******************************************************************************
1607  *
1608  * Function         l2c_fcr_adj_monitor_retran_timeout
1609  *
1610  * Description      Overrides monitor/retrans timer value based on controller
1611  *
1612  * Returns          None
1613  *
1614  ******************************************************************************/
l2c_fcr_adj_monitor_retran_timeout(tL2C_CCB * p_ccb)1615 void l2c_fcr_adj_monitor_retran_timeout(tL2C_CCB* p_ccb) {
1616   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
1617 
1618   /* adjust our monitor/retran timeout */
1619   if (p_ccb->out_cfg_fcr_present) {
1620     /*
1621     ** if we requestd ERTM or accepted ERTM
1622     ** We may accept ERTM even if we didn't request ERTM, in case of requesting
1623     *STREAM
1624     */
1625     if ((p_ccb->our_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) ||
1626         (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)) {
1627       /* upper layer setting is ignored */
1628       p_ccb->our_cfg.fcr.mon_tout = L2CAP_MIN_MONITOR_TOUT;
1629       p_ccb->our_cfg.fcr.rtrans_tout = L2CAP_MIN_RETRANS_TOUT;
1630     } else {
1631       p_ccb->our_cfg.fcr.mon_tout = 0;
1632       p_ccb->our_cfg.fcr.rtrans_tout = 0;
1633     }
1634 
1635     log::verbose("l2c_fcr_adj_monitor_retran_timeout: mon_tout:{}, rtrans_tout:{}",
1636                  p_ccb->our_cfg.fcr.mon_tout, p_ccb->our_cfg.fcr.rtrans_tout);
1637   }
1638 }
1639 /*******************************************************************************
1640  *
1641  * Function         l2c_fcr_adj_our_rsp_options
1642  *
1643  * Description      Overrides any neccesary FCR options passed in from
1644  *                  L2CA_ConfigRsp based on our FCR options.
1645  *                  Only makes adjustments if channel is in ERTM mode.
1646  *
1647  * Returns          None
1648  *
1649  ******************************************************************************/
l2c_fcr_adj_our_rsp_options(tL2C_CCB * p_ccb,tL2CAP_CFG_INFO * p_cfg)1650 void l2c_fcr_adj_our_rsp_options(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
1651   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
1652   log::assert_that(p_cfg != NULL, "assert failed: p_cfg != NULL");
1653 
1654   /* adjust our monitor/retran timeout */
1655   l2c_fcr_adj_monitor_retran_timeout(p_ccb);
1656 
1657   p_cfg->fcr_present = p_ccb->out_cfg_fcr_present;
1658 
1659   if (p_cfg->fcr_present) {
1660     /* Temporary - until a better algorithm is implemented */
1661     /* If peer's tx_wnd_sz requires too many buffers for us to support, then
1662      * adjust it. For now, respond with our own tx_wnd_sz. */
1663     /* Note: peer is not guaranteed to obey our adjustment */
1664     if (p_ccb->peer_cfg.fcr.tx_win_sz > p_ccb->our_cfg.fcr.tx_win_sz) {
1665       log::verbose("adjusting requested tx_win_sz from {} to {}", p_ccb->peer_cfg.fcr.tx_win_sz,
1666                    p_ccb->our_cfg.fcr.tx_win_sz);
1667       p_ccb->peer_cfg.fcr.tx_win_sz = p_ccb->our_cfg.fcr.tx_win_sz;
1668     }
1669 
1670     p_cfg->fcr.mode = p_ccb->peer_cfg.fcr.mode;
1671     p_cfg->fcr.tx_win_sz = p_ccb->peer_cfg.fcr.tx_win_sz;
1672     p_cfg->fcr.max_transmit = p_ccb->peer_cfg.fcr.max_transmit;
1673     p_cfg->fcr.mps = p_ccb->peer_cfg.fcr.mps;
1674     p_cfg->fcr.rtrans_tout = p_ccb->our_cfg.fcr.rtrans_tout;
1675     p_cfg->fcr.mon_tout = p_ccb->our_cfg.fcr.mon_tout;
1676   }
1677 }
1678 
1679 /*******************************************************************************
1680  *
1681  * Function         l2c_fcr_renegotiate_chan
1682  *
1683  * Description      Called upon unsuccessful peer response to config request.
1684  *                  If the error is because of the channel mode, it will try
1685  *                  to resend using another supported optional channel.
1686  *
1687  * Returns          true if resent configuration, False if channel matches or
1688  *                  cannot match.
1689  *
1690  ******************************************************************************/
l2c_fcr_renegotiate_chan(tL2C_CCB * p_ccb,tL2CAP_CFG_INFO * p_cfg)1691 bool l2c_fcr_renegotiate_chan(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
1692   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
1693   log::assert_that(p_cfg != NULL, "assert failed: p_cfg != NULL");
1694 
1695   uint8_t peer_mode = p_ccb->our_cfg.fcr.mode;
1696   bool can_renegotiate;
1697 
1698   /* Skip if this is a reconfiguration from OPEN STATE or if FCR is not returned
1699    */
1700   if (!p_cfg->fcr_present || (p_ccb->config_done & RECONFIG_FLAG)) {
1701     return false;
1702   }
1703 
1704   /* Only retry if there are more channel options to try */
1705   if (p_cfg->result == tL2CAP_CFG_RESULT::L2CAP_CFG_UNACCEPTABLE_PARAMS) {
1706     peer_mode = (p_cfg->fcr_present) ? p_cfg->fcr.mode : L2CAP_FCR_BASIC_MODE;
1707 
1708     if (p_ccb->our_cfg.fcr.mode != peer_mode) {
1709       if ((--p_ccb->fcr_cfg_tries) == 0) {
1710         p_cfg->result = tL2CAP_CFG_RESULT::L2CAP_CFG_FAILED_NO_REASON;
1711         log::warn("l2c_fcr_renegotiate_chan (Max retries exceeded)");
1712       }
1713 
1714       can_renegotiate = false;
1715 
1716       /* Try another supported mode if available based on our last attempted
1717        * channel */
1718       switch (p_ccb->our_cfg.fcr.mode) {
1719         case L2CAP_FCR_ERTM_MODE:
1720           /* We can try basic for any other peer mode because it's always
1721            * supported */
1722           log::verbose("(Trying Basic)");
1723           can_renegotiate = true;
1724           p_ccb->our_cfg.fcr.mode = L2CAP_FCR_BASIC_MODE;
1725           break;
1726 
1727         default:
1728           /* All other scenarios cannot be renegotiated */
1729           break;
1730       }
1731 
1732       if (can_renegotiate) {
1733         p_ccb->our_cfg.fcr_present = true;
1734 
1735         if (p_ccb->our_cfg.fcr.mode == L2CAP_FCR_BASIC_MODE) {
1736           p_ccb->our_cfg.fcs_present = false;
1737           p_ccb->our_cfg.ext_flow_spec_present = false;
1738 
1739           /* Basic Mode uses ACL Data Pool, make sure the MTU fits */
1740           if ((p_cfg->mtu_present) && (p_cfg->mtu > L2CAP_MTU_SIZE)) {
1741             log::warn("L2CAP - adjust MTU: {} too large", p_cfg->mtu);
1742             p_cfg->mtu = L2CAP_MTU_SIZE;
1743           }
1744         }
1745 
1746         l2cu_process_our_cfg_req(p_ccb, &p_ccb->our_cfg);
1747         l2cu_send_peer_config_req(p_ccb, &p_ccb->our_cfg);
1748         alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS, l2c_ccb_timer_timeout,
1749                            p_ccb);
1750         return true;
1751       }
1752     }
1753   }
1754 
1755   /* Disconnect if the channels do not match */
1756   if (p_ccb->our_cfg.fcr.mode != peer_mode) {
1757     log::warn("L2C CFG:  Channels incompatible (local {}, peer {})", p_ccb->our_cfg.fcr.mode,
1758               peer_mode);
1759     l2cu_disconnect_chnl(p_ccb);
1760   }
1761 
1762   return false;
1763 }
1764 
1765 /*******************************************************************************
1766  *
1767  * Function         l2c_fcr_process_peer_cfg_req
1768  *
1769  * Description      This function is called to process the FCR options passed
1770  *                  in the peer's configuration request.
1771  *
1772  * Returns          uint8_t - L2CAP_PEER_CFG_OK, L2CAP_PEER_CFG_UNACCEPTABLE,
1773  *                          or L2CAP_PEER_CFG_DISCONNECT.
1774  *
1775  ******************************************************************************/
l2c_fcr_process_peer_cfg_req(tL2C_CCB * p_ccb,tL2CAP_CFG_INFO * p_cfg)1776 uint8_t l2c_fcr_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
1777   log::assert_that(p_ccb != NULL, "assert failed: p_ccb != NULL");
1778   log::assert_that(p_cfg != NULL, "assert failed: p_cfg != NULL");
1779 
1780   uint16_t max_retrans_size;
1781   uint8_t fcr_ok = L2CAP_PEER_CFG_OK;
1782 
1783   p_ccb->p_lcb->w4_info_rsp = false; /* Handles T61x SonyEricsson Bug in Info Request */
1784 
1785   log::verbose(
1786           "l2c_fcr_process_peer_cfg_req() CFG fcr_present:{} fcr.mode:{} CCB FCR "
1787           "mode:{} preferred: {}",
1788           p_cfg->fcr_present, p_cfg->fcr.mode, p_ccb->our_cfg.fcr.mode,
1789           p_ccb->p_rcb->ertm_info.preferred_mode);
1790 
1791   /* Need to negotiate if our modes are not the same */
1792   if (p_cfg->fcr.mode != p_ccb->p_rcb->ertm_info.preferred_mode) {
1793     /* If peer wants a mode that we don't support then retry our mode (ex.
1794      *rtx/flc), OR
1795      ** If we want ERTM and they want non-basic mode, retry our mode.
1796      ** Note: If we have already determined they support our mode previously
1797      **       from their EXF mask.
1798      */
1799     if ((((1 << p_cfg->fcr.mode) & L2CAP_FCR_CHAN_OPT_ALL_MASK) == 0) ||
1800         ((p_ccb->p_rcb->ertm_info.preferred_mode == L2CAP_FCR_ERTM_MODE) &&
1801          (p_cfg->fcr.mode != L2CAP_FCR_BASIC_MODE))) {
1802       p_cfg->fcr.mode = p_ccb->our_cfg.fcr.mode;
1803       p_cfg->fcr.tx_win_sz = p_ccb->our_cfg.fcr.tx_win_sz;
1804       p_cfg->fcr.max_transmit = p_ccb->our_cfg.fcr.max_transmit;
1805       fcr_ok = L2CAP_PEER_CFG_UNACCEPTABLE;
1806     } else if (p_ccb->p_rcb->ertm_info.preferred_mode == L2CAP_FCR_BASIC_MODE) {
1807       /* If we wanted basic, then try to renegotiate it */
1808       p_cfg->fcr.mode = L2CAP_FCR_BASIC_MODE;
1809       p_cfg->fcr.max_transmit = p_cfg->fcr.tx_win_sz = 0;
1810       p_cfg->fcr.rtrans_tout = p_cfg->fcr.mon_tout = p_cfg->fcr.mps = 0;
1811       p_ccb->our_cfg.fcr.rtrans_tout = p_ccb->our_cfg.fcr.mon_tout = p_ccb->our_cfg.fcr.mps = 0;
1812       fcr_ok = L2CAP_PEER_CFG_UNACCEPTABLE;
1813     }
1814   }
1815 
1816   uint8_t fcs_len = l2cu_get_fcs_len(p_ccb);
1817 
1818   /* Configuration for FCR channels so make any adjustments and fwd to upper
1819    * layer */
1820   if (fcr_ok == L2CAP_PEER_CFG_OK) {
1821     /* by default don't need to send params in the response */
1822     p_ccb->out_cfg_fcr_present = false;
1823 
1824     /* Make any needed adjustments for the response to the peer */
1825     if (p_cfg->fcr_present && p_cfg->fcr.mode != L2CAP_FCR_BASIC_MODE) {
1826       /* Peer desires to bypass FCS check, and streaming or ERTM mode */
1827       if (p_cfg->fcs_present) {
1828         p_ccb->peer_cfg.fcs = p_cfg->fcs;
1829       }
1830 
1831       max_retrans_size = BT_DEFAULT_BUFFER_SIZE - sizeof(BT_HDR) - L2CAP_MIN_OFFSET -
1832                          L2CAP_SDU_LEN_OFFSET - fcs_len;
1833 
1834       /* Ensure the MPS is not bigger than the MTU */
1835       if ((p_cfg->fcr.mps == 0) || (p_cfg->fcr.mps > p_ccb->peer_cfg.mtu)) {
1836         p_cfg->fcr.mps = p_ccb->peer_cfg.mtu;
1837         p_ccb->out_cfg_fcr_present = true;
1838       }
1839 
1840       /* Ensure the MPS is not bigger than our retransmission buffer */
1841       if (p_cfg->fcr.mps > max_retrans_size) {
1842         log::verbose("CFG: Overriding MPS to {} (orig {})", max_retrans_size, p_cfg->fcr.mps);
1843 
1844         p_cfg->fcr.mps = max_retrans_size;
1845         p_ccb->out_cfg_fcr_present = true;
1846       }
1847 
1848       if (p_cfg->fcr.mode == L2CAP_FCR_ERTM_MODE) {
1849         /* Always respond with FCR ERTM parameters */
1850         p_ccb->out_cfg_fcr_present = true;
1851       }
1852     }
1853 
1854     /* Everything ok, so save the peer's adjusted fcr options */
1855     p_ccb->peer_cfg.fcr = p_cfg->fcr;
1856 
1857   } else if (fcr_ok == L2CAP_PEER_CFG_UNACCEPTABLE) {
1858     /* Allow peer only one retry for mode */
1859     if (p_ccb->peer_cfg_already_rejected) {
1860       fcr_ok = L2CAP_PEER_CFG_DISCONNECT;
1861     } else {
1862       p_ccb->peer_cfg_already_rejected = true;
1863     }
1864   }
1865 
1866   return fcr_ok;
1867 }
1868