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