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