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 <log/log.h>
28 #include <stdio.h>
29 #include <stdlib.h>
30 #include <string.h>
31 
32 #include "bt_common.h"
33 #include "bt_types.h"
34 #include "btm_api.h"
35 #include "btm_int.h"
36 #include "btu.h"
37 #include "hcimsgs.h"
38 #include "l2c_api.h"
39 #include "l2c_int.h"
40 #include "l2cdefs.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 void process_stream_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf);
97 static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf,
98                               uint16_t ctrl_word);
99 
100 #if (L2CAP_ERTM_STATS == TRUE)
101 static void l2c_fcr_collect_ack_delay(tL2C_CCB* p_ccb, uint8_t num_bufs_acked);
102 #endif
103 
104 /*******************************************************************************
105  *
106  * Function         l2c_fcr_updcrc
107  *
108  * Description      This function computes the CRC using the look-up table.
109  *
110  * Returns          CRC
111  *
112  ******************************************************************************/
l2c_fcr_updcrc(unsigned short icrc,unsigned char * icp,int icnt)113 static unsigned short l2c_fcr_updcrc(unsigned short icrc, unsigned char* icp,
114                                      int icnt) {
115   unsigned short crc = icrc;
116   unsigned char* cp = icp;
117   int cnt = icnt;
118 
119   while (cnt--) {
120     crc = ((crc >> 8) & 0xff) ^ crctab[(crc & 0xff) ^ *cp++];
121   }
122 
123   return (crc);
124 }
125 
126 /*******************************************************************************
127  *
128  * Function         l2c_fcr_tx_get_fcs
129  *
130  * Description      This function computes the CRC for a frame to be TXed.
131  *
132  * Returns          CRC
133  *
134  ******************************************************************************/
l2c_fcr_tx_get_fcs(BT_HDR * p_buf)135 static uint16_t l2c_fcr_tx_get_fcs(BT_HDR* p_buf) {
136   uint8_t* p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
137 
138   return (l2c_fcr_updcrc(L2CAP_FCR_INIT_CRC, p, p_buf->len));
139 }
140 
141 /*******************************************************************************
142  *
143  * Function         l2c_fcr_rx_get_fcs
144  *
145  * Description      This function computes the CRC for a received frame.
146  *
147  * Returns          CRC
148  *
149  ******************************************************************************/
l2c_fcr_rx_get_fcs(BT_HDR * p_buf)150 static uint16_t l2c_fcr_rx_get_fcs(BT_HDR* p_buf) {
151   uint8_t* p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
152 
153   /* offset points past the L2CAP header, but the CRC check includes it */
154   p -= L2CAP_PKT_OVERHEAD;
155 
156   return (
157       l2c_fcr_updcrc(L2CAP_FCR_INIT_CRC, p, p_buf->len + L2CAP_PKT_OVERHEAD));
158 }
159 
160 /*******************************************************************************
161  *
162  * Function         l2c_fcr_start_timer
163  *
164  * Description      This function starts the (monitor or retransmission) timer.
165  *
166  * Returns          -
167  *
168  ******************************************************************************/
l2c_fcr_start_timer(tL2C_CCB * p_ccb)169 void l2c_fcr_start_timer(tL2C_CCB* p_ccb) {
170   CHECK(p_ccb != NULL);
171   uint32_t tout;
172 
173   /* The timers which are in milliseconds */
174   if (p_ccb->fcrb.wait_ack) {
175     tout = (uint32_t)p_ccb->our_cfg.fcr.mon_tout;
176   } else {
177     tout = (uint32_t)p_ccb->our_cfg.fcr.rtrans_tout;
178   }
179 
180   /* Only start a timer that was not started */
181   if (!alarm_is_scheduled(p_ccb->fcrb.mon_retrans_timer)) {
182     alarm_set_on_mloop(p_ccb->fcrb.mon_retrans_timer, tout,
183                        l2c_ccb_timer_timeout, p_ccb);
184   }
185 }
186 
187 /*******************************************************************************
188  *
189  * Function         l2c_fcr_stop_timer
190  *
191  * Description      This function stops the (monitor or transmission) timer.
192  *
193  * Returns          -
194  *
195  ******************************************************************************/
l2c_fcr_stop_timer(tL2C_CCB * p_ccb)196 void l2c_fcr_stop_timer(tL2C_CCB* p_ccb) {
197   CHECK(p_ccb != NULL);
198   alarm_cancel(p_ccb->fcrb.mon_retrans_timer);
199 }
200 
201 /*******************************************************************************
202  *
203  * Function         l2c_fcr_cleanup
204  *
205  * Description      This function cleans up the variable used for
206  *                  flow-control/retrans.
207  *
208  * Returns          -
209  *
210  ******************************************************************************/
l2c_fcr_cleanup(tL2C_CCB * p_ccb)211 void l2c_fcr_cleanup(tL2C_CCB* p_ccb) {
212   CHECK(p_ccb != NULL);
213   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
214 
215   alarm_free(p_fcrb->mon_retrans_timer);
216   p_fcrb->mon_retrans_timer = NULL;
217   alarm_free(p_fcrb->ack_timer);
218   p_fcrb->ack_timer = NULL;
219 
220   osi_free_and_reset((void**)&p_fcrb->p_rx_sdu);
221 
222   fixed_queue_free(p_fcrb->waiting_for_ack_q, osi_free);
223   p_fcrb->waiting_for_ack_q = NULL;
224 
225   fixed_queue_free(p_fcrb->srej_rcv_hold_q, osi_free);
226   p_fcrb->srej_rcv_hold_q = NULL;
227 
228   fixed_queue_free(p_fcrb->retrans_q, osi_free);
229   p_fcrb->retrans_q = NULL;
230 
231 #if (L2CAP_ERTM_STATS == TRUE)
232   if ((p_ccb->local_cid >= L2CAP_BASE_APPL_CID) &&
233       (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)) {
234     uint32_t dur = time_get_os_boottime_ms() - p_ccb->fcrb.connect_tick_count;
235     size_t p_str_size = 120;
236     char* p_str = (char*)osi_malloc(p_str_size);
237     uint16_t i;
238     uint32_t throughput_avg, ack_delay_avg, ack_q_count_avg;
239 
240     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
241              TRACE_TYPE_GENERIC,
242              "---  L2CAP ERTM  Stats for CID: 0x%04x   Duration: %08ums",
243              p_ccb->local_cid, dur);
244     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
245              TRACE_TYPE_GENERIC,
246              "Retransmissions:%08u Times Flow Controlled:%08u Retrans "
247              "Touts:%08u Ack Touts:%08u",
248              p_ccb->fcrb.pkts_retransmitted, p_ccb->fcrb.xmit_window_closed,
249              p_ccb->fcrb.retrans_touts, p_ccb->fcrb.xmit_ack_touts);
250     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
251              TRACE_TYPE_GENERIC,
252              "Times there is less than 2 packets in controller when flow "
253              "controlled:%08u",
254              p_ccb->fcrb.controller_idle);
255     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
256              TRACE_TYPE_GENERIC,
257              "max_held_acks:%08u, in_cfg.fcr.tx_win_sz:%08u",
258              p_ccb->fcrb.max_held_acks, p_ccb->peer_cfg.fcr.tx_win_sz);
259 
260     snprintf(
261         p_str, p_str_size,
262         "Sent Pkts:%08u Bytes:%10u(%06u/sec) RR:%08u REJ:%08u RNR:%08u "
263         "SREJ:%08u",
264         p_ccb->fcrb.ertm_pkt_counts[0], p_ccb->fcrb.ertm_byte_counts[0],
265         (dur >= 10 ? (p_ccb->fcrb.ertm_byte_counts[0] * 100) / (dur / 10) : 0),
266         p_ccb->fcrb.s_frames_sent[0], p_ccb->fcrb.s_frames_sent[1],
267         p_ccb->fcrb.s_frames_sent[2], p_ccb->fcrb.s_frames_sent[3]);
268 
269     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
270              TRACE_TYPE_GENERIC, "%s", p_str);
271 
272     snprintf(
273         p_str, p_str_size,
274         "Rcvd Pkts:%08u Bytes:%10u(%06u/sec) RR:%08u REJ:%08u RNR:%08u "
275         "SREJ:%08u",
276         p_ccb->fcrb.ertm_pkt_counts[1], p_ccb->fcrb.ertm_byte_counts[1],
277         (dur >= 10 ? (p_ccb->fcrb.ertm_byte_counts[1] * 100) / (dur / 10) : 0),
278         p_ccb->fcrb.s_frames_rcvd[0], p_ccb->fcrb.s_frames_rcvd[1],
279         p_ccb->fcrb.s_frames_rcvd[2], p_ccb->fcrb.s_frames_rcvd[3]);
280 
281     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
282              TRACE_TYPE_GENERIC, "%s", p_str);
283 
284     throughput_avg = 0;
285     ack_delay_avg = 0;
286     ack_q_count_avg = 0;
287 
288     for (i = 0; i < L2CAP_ERTM_STATS_NUM_AVG; i++) {
289       if (i == p_ccb->fcrb.ack_delay_avg_index) {
290         BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
291                  TRACE_TYPE_GENERIC, "[%02u] collecting data ...", i);
292         continue;
293       }
294 
295       snprintf(p_str, p_str_size,
296                "[%02u] throughput: %5u, ack_delay avg:%3u, min:%3u, max:%3u, "
297                "ack_q_count avg:%3u, min:%3u, max:%3u",
298                i, p_ccb->fcrb.throughput[i], p_ccb->fcrb.ack_delay_avg[i],
299                p_ccb->fcrb.ack_delay_min[i], p_ccb->fcrb.ack_delay_max[i],
300                p_ccb->fcrb.ack_q_count_avg[i], p_ccb->fcrb.ack_q_count_min[i],
301                p_ccb->fcrb.ack_q_count_max[i]);
302 
303       BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
304                TRACE_TYPE_GENERIC, "%s", p_str);
305 
306       throughput_avg += p_ccb->fcrb.throughput[i];
307       ack_delay_avg += p_ccb->fcrb.ack_delay_avg[i];
308       ack_q_count_avg += p_ccb->fcrb.ack_q_count_avg[i];
309     }
310 
311     throughput_avg /= (L2CAP_ERTM_STATS_NUM_AVG - 1);
312     ack_delay_avg /= (L2CAP_ERTM_STATS_NUM_AVG - 1);
313     ack_q_count_avg /= (L2CAP_ERTM_STATS_NUM_AVG - 1);
314 
315     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
316              TRACE_TYPE_GENERIC,
317              "throughput_avg: %8u (kbytes/sec), ack_delay_avg: %8u ms, "
318              "ack_q_count_avg: %8u",
319              throughput_avg, ack_delay_avg, ack_q_count_avg);
320 
321     osi_free(p_str);
322 
323     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
324              TRACE_TYPE_GENERIC, "---");
325   }
326 #endif
327 
328   memset(p_fcrb, 0, sizeof(tL2C_FCRB));
329 }
330 
331 /*******************************************************************************
332  *
333  * Function         l2c_fcr_clone_buf
334  *
335  * Description      This function allocates and copies requested part of a
336  *                  buffer at a new-offset.
337  *
338  * Returns          pointer to new buffer
339  *
340  ******************************************************************************/
l2c_fcr_clone_buf(BT_HDR * p_buf,uint16_t new_offset,uint16_t no_of_bytes)341 BT_HDR* l2c_fcr_clone_buf(BT_HDR* p_buf, uint16_t new_offset,
342                           uint16_t no_of_bytes) {
343   CHECK(p_buf != NULL);
344   /*
345    * NOTE: We allocate extra L2CAP_FCS_LEN octets, in case we need to put
346    * the FCS (Frame Check Sequence) at the end of the buffer.
347    */
348   uint16_t buf_size = no_of_bytes + sizeof(BT_HDR) + new_offset + L2CAP_FCS_LEN;
349 #if (L2CAP_ERTM_STATS == TRUE)
350   /*
351    * NOTE: If L2CAP_ERTM_STATS is enabled, we need 4 extra octets at the
352    * end for a timestamp at the end of an I-frame.
353    */
354   buf_size += sizeof(uint32_t);
355 #endif
356   BT_HDR* p_buf2 = (BT_HDR*)osi_malloc(buf_size);
357 
358   p_buf2->offset = new_offset;
359   p_buf2->len = no_of_bytes;
360   memcpy(((uint8_t*)(p_buf2 + 1)) + p_buf2->offset,
361          ((uint8_t*)(p_buf + 1)) + p_buf->offset, no_of_bytes);
362 
363   return (p_buf2);
364 }
365 
366 /*******************************************************************************
367  *
368  * Function         l2c_fcr_is_flow_controlled
369  *
370  * Description      This function checks if the CCB is flow controlled by peer.
371  *
372  * Returns          The control word
373  *
374  ******************************************************************************/
l2c_fcr_is_flow_controlled(tL2C_CCB * p_ccb)375 bool l2c_fcr_is_flow_controlled(tL2C_CCB* p_ccb) {
376   CHECK(p_ccb != NULL);
377   if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) {
378     /* Check if remote side flowed us off or the transmit window is full */
379     if ((p_ccb->fcrb.remote_busy) ||
380         (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q) >=
381          p_ccb->peer_cfg.fcr.tx_win_sz)) {
382 #if (L2CAP_ERTM_STATS == TRUE)
383       if (!fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
384         p_ccb->fcrb.xmit_window_closed++;
385 
386         if ((p_ccb->p_lcb->sent_not_acked < 2) &&
387             (l2cb.controller_xmit_window > 0))
388           p_ccb->fcrb.controller_idle++;
389       }
390 #endif
391       return (true);
392     }
393   }
394   return (false);
395 }
396 
397 /*******************************************************************************
398  *
399  * Function         prepare_I_frame
400  *
401  * Description      This function sets the FCR variables in an I-frame that is
402  *                  about to be sent to HCI for transmission. This may be the
403  *                  first time the I-frame is sent, or a retransmission
404  *
405  * Returns          -
406  *
407  ******************************************************************************/
prepare_I_frame(tL2C_CCB * p_ccb,BT_HDR * p_buf,bool is_retransmission)408 static void prepare_I_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf,
409                             bool is_retransmission) {
410   CHECK(p_ccb != NULL);
411   CHECK(p_buf != NULL);
412   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
413   uint8_t* p;
414   uint16_t fcs;
415   uint16_t ctrl_word;
416   bool set_f_bit = p_fcrb->send_f_rsp;
417 
418   p_fcrb->send_f_rsp = false;
419 
420   if (is_retransmission) {
421     /* Get the old control word and clear out the old req_seq and F bits */
422     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
423 
424     STREAM_TO_UINT16(ctrl_word, p);
425 
426     ctrl_word &= ~(L2CAP_FCR_REQ_SEQ_BITS + L2CAP_FCR_F_BIT);
427   } else {
428     ctrl_word = p_buf->layer_specific & L2CAP_FCR_SEG_BITS; /* SAR bits */
429     ctrl_word |=
430         (p_fcrb->next_tx_seq << L2CAP_FCR_TX_SEQ_BITS_SHIFT); /* Tx Seq */
431 
432     p_fcrb->next_tx_seq = (p_fcrb->next_tx_seq + 1) & L2CAP_FCR_SEQ_MODULO;
433   }
434 
435   /* Set the F-bit and reqseq only if using re-transmission mode */
436   if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) {
437     if (set_f_bit) ctrl_word |= L2CAP_FCR_F_BIT;
438 
439     ctrl_word |= (p_fcrb->next_seq_expected) << L2CAP_FCR_REQ_SEQ_BITS_SHIFT;
440 
441     p_fcrb->last_ack_sent = p_ccb->fcrb.next_seq_expected;
442 
443     alarm_cancel(p_ccb->fcrb.ack_timer);
444   }
445 
446   /* Set the control word */
447   p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
448 
449   UINT16_TO_STREAM(p, ctrl_word);
450 
451   /* Compute the FCS and add to the end of the buffer if not bypassed */
452   if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
453     /* length field in l2cap header has to include FCS length */
454     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
455     UINT16_TO_STREAM(p, p_buf->len + L2CAP_FCS_LEN - L2CAP_PKT_OVERHEAD);
456 
457     /* Calculate the FCS */
458     fcs = l2c_fcr_tx_get_fcs(p_buf);
459 
460     /* Point to the end of the buffer and put the FCS there */
461     /*
462      * NOTE: Here we assume the allocated buffer is large enough
463      * to include extra L2CAP_FCS_LEN octets at the end.
464      */
465     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len;
466 
467     UINT16_TO_STREAM(p, fcs);
468 
469     p_buf->len += L2CAP_FCS_LEN;
470   }
471 
472   if (is_retransmission) {
473     L2CAP_TRACE_EVENT(
474         "L2CAP eRTM ReTx I-frame  CID: 0x%04x  Len: %u  SAR: %s  TxSeq: %u  "
475         "ReqSeq: %u  F: %u",
476         p_ccb->local_cid, p_buf->len,
477         SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
478         (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
479         (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
480         (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
481   } else {
482     L2CAP_TRACE_EVENT(
483         "L2CAP eRTM Tx I-frame CID: 0x%04x  Len: %u  SAR: %-12s  TxSeq: %u  "
484         "ReqSeq: %u  F: %u",
485         p_ccb->local_cid, p_buf->len,
486         SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
487         (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
488         (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
489         (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
490   }
491 
492   /* Start the retransmission timer if not already running */
493   if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)
494     l2c_fcr_start_timer(p_ccb);
495 }
496 
497 /*******************************************************************************
498  *
499  * Function         l2c_fcr_send_S_frame
500  *
501  * Description      This function formats and sends an S-frame for transmission.
502  *
503  * Returns          -
504  *
505  ******************************************************************************/
l2c_fcr_send_S_frame(tL2C_CCB * p_ccb,uint16_t function_code,uint16_t pf_bit)506 void l2c_fcr_send_S_frame(tL2C_CCB* p_ccb, uint16_t function_code,
507                           uint16_t pf_bit) {
508   CHECK(p_ccb != NULL);
509   uint8_t* p;
510   uint16_t ctrl_word;
511   uint16_t fcs;
512 
513   if ((!p_ccb->in_use) || (p_ccb->chnl_state != CST_OPEN)) return;
514 
515 #if (L2CAP_ERTM_STATS == TRUE)
516   p_ccb->fcrb.s_frames_sent[function_code]++;
517 #endif
518 
519   if (pf_bit == L2CAP_FCR_P_BIT) {
520     p_ccb->fcrb.wait_ack = true;
521 
522     l2c_fcr_stop_timer(p_ccb); /* Restart the monitor timer */
523     l2c_fcr_start_timer(p_ccb);
524   }
525 
526   /* Create the control word to use */
527   ctrl_word = (function_code << L2CAP_FCR_SUP_SHIFT) | L2CAP_FCR_S_FRAME_BIT;
528   ctrl_word |= (p_ccb->fcrb.next_seq_expected << L2CAP_FCR_REQ_SEQ_BITS_SHIFT);
529   ctrl_word |= pf_bit;
530 
531   BT_HDR* p_buf = (BT_HDR*)osi_malloc(L2CAP_CMD_BUF_SIZE);
532   p_buf->offset = HCI_DATA_PREAMBLE_SIZE;
533   p_buf->len = L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD;
534 
535   /* Set the pointer to the beginning of the data */
536   p = (uint8_t*)(p_buf + 1) + p_buf->offset;
537 
538   /* Put in the L2CAP header */
539   UINT16_TO_STREAM(p, L2CAP_FCR_OVERHEAD + L2CAP_FCS_LEN);
540   UINT16_TO_STREAM(p, p_ccb->remote_cid);
541   UINT16_TO_STREAM(p, ctrl_word);
542 
543   /* Compute the FCS and add to the end of the buffer if not bypassed */
544   if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
545     fcs = l2c_fcr_tx_get_fcs(p_buf);
546 
547     UINT16_TO_STREAM(p, fcs);
548     p_buf->len += L2CAP_FCS_LEN;
549   } else {
550     /* rewrite the length without FCS length */
551     p -= 6;
552     UINT16_TO_STREAM(p, L2CAP_FCR_OVERHEAD);
553   }
554 
555   /* Now, the HCI transport header */
556   p_buf->layer_specific = L2CAP_NON_FLUSHABLE_PKT;
557   l2cu_set_acl_hci_header(p_buf, p_ccb);
558 
559   if ((((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 1) ||
560       (((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 3)) {
561     L2CAP_TRACE_WARNING(
562         "L2CAP eRTM Tx S-frame  CID: 0x%04x  ctrlword: 0x%04x  Type: %s  "
563         "ReqSeq: %u  P: %u  F: %u",
564         p_ccb->local_cid, ctrl_word,
565         SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
566         (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
567         (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
568         (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
569     L2CAP_TRACE_WARNING("                  Buf Len: %u", p_buf->len);
570   } else {
571     L2CAP_TRACE_EVENT(
572         "L2CAP eRTM Tx S-frame  CID: 0x%04x  ctrlword: 0x%04x  Type: %s  "
573         "ReqSeq: %u  P: %u  F: %u",
574         p_ccb->local_cid, ctrl_word,
575         SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
576         (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
577         (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
578         (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
579     L2CAP_TRACE_EVENT("                  Buf Len: %u", p_buf->len);
580   }
581 
582   l2c_link_check_send_pkts(p_ccb->p_lcb, NULL, p_buf);
583 
584   p_ccb->fcrb.last_ack_sent = p_ccb->fcrb.next_seq_expected;
585 
586   alarm_cancel(p_ccb->fcrb.ack_timer);
587 }
588 
589 /*******************************************************************************
590  *
591  * Function         l2c_fcr_proc_pdu
592  *
593  * Description      This function is the entry point for processing of a
594  *                  received PDU when in flow control and/or retransmission
595  *                  modes.
596  *
597  * Returns          -
598  *
599  ******************************************************************************/
l2c_fcr_proc_pdu(tL2C_CCB * p_ccb,BT_HDR * p_buf)600 void l2c_fcr_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) {
601   CHECK(p_ccb != NULL);
602   CHECK(p_buf != NULL);
603   uint8_t* p;
604   uint16_t fcs;
605   uint16_t min_pdu_len;
606   uint16_t ctrl_word;
607 
608   /* Check the length */
609   min_pdu_len = (p_ccb->bypass_fcs == L2CAP_BYPASS_FCS)
610                     ? (uint16_t)L2CAP_FCR_OVERHEAD
611                     : (uint16_t)(L2CAP_FCS_LEN + L2CAP_FCR_OVERHEAD);
612 
613   if (p_buf->len < min_pdu_len) {
614     L2CAP_TRACE_WARNING("Rx L2CAP PDU: CID: 0x%04x  Len too short: %u",
615                         p_ccb->local_cid, p_buf->len);
616     osi_free(p_buf);
617     return;
618   }
619 
620   if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_STREAM_MODE) {
621     process_stream_frame(p_ccb, p_buf);
622     return;
623   }
624 
625   /* Get the control word */
626   p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
627   STREAM_TO_UINT16(ctrl_word, p);
628 
629   if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) {
630     if ((((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 1) ||
631         (((ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT) == 3)) {
632       /* REJ or SREJ */
633       L2CAP_TRACE_WARNING(
634           "L2CAP eRTM Rx S-frame: cid: 0x%04x  Len: %u  Type: %s  ReqSeq: %u  "
635           "P: %u  F: %u",
636           p_ccb->local_cid, p_buf->len,
637           SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
638           (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
639           (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
640           (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
641     } else {
642       L2CAP_TRACE_EVENT(
643           "L2CAP eRTM Rx S-frame: cid: 0x%04x  Len: %u  Type: %s  ReqSeq: %u  "
644           "P: %u  F: %u",
645           p_ccb->local_cid, p_buf->len,
646           SUP_types[(ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT],
647           (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
648           (ctrl_word & L2CAP_FCR_P_BIT) >> L2CAP_FCR_P_BIT_SHIFT,
649           (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
650     }
651   } else {
652     L2CAP_TRACE_EVENT(
653         "L2CAP eRTM Rx I-frame: cid: 0x%04x  Len: %u  SAR: %-12s  TxSeq: %u  "
654         "ReqSeq: %u  F: %u",
655         p_ccb->local_cid, p_buf->len,
656         SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
657         (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
658         (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
659         (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
660   }
661 
662   L2CAP_TRACE_EVENT(
663       "      eRTM Rx Nxt_tx_seq %u, Lst_rx_ack %u, Nxt_seq_exp %u, Lst_ack_snt "
664       "%u, wt_q.cnt %u, tries %u",
665       p_ccb->fcrb.next_tx_seq, p_ccb->fcrb.last_rx_ack,
666       p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent,
667       fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q), p_ccb->fcrb.num_tries);
668 
669   /* Verify FCS if using */
670   if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
671     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len - L2CAP_FCS_LEN;
672 
673     /* Extract and drop the FCS from the packet */
674     STREAM_TO_UINT16(fcs, p);
675     p_buf->len -= L2CAP_FCS_LEN;
676 
677     if (l2c_fcr_rx_get_fcs(p_buf) != fcs) {
678       L2CAP_TRACE_WARNING("Rx L2CAP PDU: CID: 0x%04x  BAD FCS",
679                           p_ccb->local_cid);
680       osi_free(p_buf);
681       return;
682     }
683   }
684 
685   /* Get the control word */
686   p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
687 
688   STREAM_TO_UINT16(ctrl_word, p);
689 
690   p_buf->len -= L2CAP_FCR_OVERHEAD;
691   p_buf->offset += L2CAP_FCR_OVERHEAD;
692 
693   /* If we had a poll bit outstanding, check if we got a final response */
694   if (p_ccb->fcrb.wait_ack) {
695     /* If final bit not set, ignore the frame unless it is a polled S-frame */
696     if (!(ctrl_word & L2CAP_FCR_F_BIT)) {
697       if ((ctrl_word & L2CAP_FCR_P_BIT) &&
698           (ctrl_word & L2CAP_FCR_S_FRAME_BIT)) {
699         if (p_ccb->fcrb.srej_sent)
700           l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_SREJ, L2CAP_FCR_F_BIT);
701         else if (p_ccb->fcrb.local_busy)
702           l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, L2CAP_FCR_F_BIT);
703         else
704           l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_F_BIT);
705 
706         /* Got a poll while in wait_ack state, so re-start our timer with
707          * 1-second */
708         /* This is a small optimization... the monitor timer is 12 secs, but we
709          * saw */
710         /* that if the other side sends us a poll when we are waiting for a
711          * final,  */
712         /* then it speeds up recovery significantly if we poll him back soon
713          * after his poll. */
714         alarm_set_on_mloop(p_ccb->fcrb.mon_retrans_timer, BT_1SEC_TIMEOUT_MS,
715                            l2c_ccb_timer_timeout, p_ccb);
716       }
717       osi_free(p_buf);
718       return;
719     }
720 
721     p_ccb->fcrb.wait_ack = false;
722 
723     /* P and F are mutually exclusive */
724     if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) ctrl_word &= ~L2CAP_FCR_P_BIT;
725 
726     if (fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q))
727       p_ccb->fcrb.num_tries = 0;
728 
729     l2c_fcr_stop_timer(p_ccb);
730   } else {
731     /* Otherwise, ensure the final bit is ignored */
732     ctrl_word &= ~L2CAP_FCR_F_BIT;
733   }
734 
735   /* Process receive sequence number */
736   if (!process_reqseq(p_ccb, ctrl_word)) {
737     osi_free(p_buf);
738     return;
739   }
740 
741   /* Process based on whether it is an S-frame or an I-frame */
742   if (ctrl_word & L2CAP_FCR_S_FRAME_BIT)
743     process_s_frame(p_ccb, p_buf, ctrl_word);
744   else
745     process_i_frame(p_ccb, p_buf, ctrl_word, false);
746 
747   /* Return if the channel got disconnected by a bad packet or max
748    * retransmissions */
749   if ((!p_ccb->in_use) || (p_ccb->chnl_state != CST_OPEN)) return;
750 
751   /* If we have some buffers held while doing SREJ, and SREJ has cleared,
752    * process them now */
753   if ((!p_ccb->fcrb.local_busy) && (!p_ccb->fcrb.srej_sent) &&
754       (!fixed_queue_is_empty(p_ccb->fcrb.srej_rcv_hold_q))) {
755     fixed_queue_t* temp_q = p_ccb->fcrb.srej_rcv_hold_q;
756     p_ccb->fcrb.srej_rcv_hold_q = fixed_queue_new(SIZE_MAX);
757 
758     while ((p_buf = (BT_HDR*)fixed_queue_try_dequeue(temp_q)) != NULL) {
759       if (p_ccb->in_use && (p_ccb->chnl_state == CST_OPEN)) {
760         /* Get the control word */
761         p = ((uint8_t*)(p_buf + 1)) + p_buf->offset - L2CAP_FCR_OVERHEAD;
762 
763         STREAM_TO_UINT16(ctrl_word, p);
764 
765         L2CAP_TRACE_DEBUG(
766             "l2c_fcr_proc_pdu() CID: 0x%04x  Process Buffer from SREJ_Hold_Q   "
767             "TxSeq: %u  Expected_Seq: %u",
768             p_ccb->local_cid,
769             (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
770             p_ccb->fcrb.next_seq_expected);
771 
772         /* Process the SREJ held I-frame, but do not send an RR for each
773          * individual frame */
774         process_i_frame(p_ccb, p_buf, ctrl_word, true);
775       } else
776         osi_free(p_buf);
777 
778       /* If more frames were lost during SREJ, send a REJ */
779       if (p_ccb->fcrb.rej_after_srej) {
780         p_ccb->fcrb.rej_after_srej = false;
781         p_ccb->fcrb.rej_sent = true;
782 
783         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_REJ, 0);
784       }
785     }
786     fixed_queue_free(temp_q, NULL);
787 
788     /* Now, if needed, send one RR for the whole held queue */
789     if ((!p_ccb->fcrb.local_busy) && (!p_ccb->fcrb.rej_sent) &&
790         (!p_ccb->fcrb.srej_sent) &&
791         (p_ccb->fcrb.next_seq_expected != p_ccb->fcrb.last_ack_sent))
792       l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, 0);
793     else {
794       L2CAP_TRACE_DEBUG(
795           "l2c_fcr_proc_pdu() not sending RR CID: 0x%04x  local_busy:%d "
796           "rej_sent:%d srej_sent:%d Expected_Seq:%u Last_Ack:%u",
797           p_ccb->local_cid, p_ccb->fcrb.local_busy, p_ccb->fcrb.rej_sent,
798           p_ccb->fcrb.srej_sent, p_ccb->fcrb.next_seq_expected,
799           p_ccb->fcrb.last_ack_sent);
800     }
801   }
802 
803   /* If a window has opened, check if we can send any more packets */
804   if ((!fixed_queue_is_empty(p_ccb->fcrb.retrans_q) ||
805        !fixed_queue_is_empty(p_ccb->xmit_hold_q)) &&
806       (!p_ccb->fcrb.wait_ack) && (!l2c_fcr_is_flow_controlled(p_ccb))) {
807     l2c_link_check_send_pkts(p_ccb->p_lcb, NULL, NULL);
808   }
809 }
810 
811 /*******************************************************************************
812  *
813  * Function         l2c_lcc_proc_pdu
814  *
815  * Description      This function is the entry point for processing of a
816  *                  received PDU when in LE Coc flow control modes.
817  *
818  * Returns          -
819  *
820  ******************************************************************************/
l2c_lcc_proc_pdu(tL2C_CCB * p_ccb,BT_HDR * p_buf)821 void l2c_lcc_proc_pdu(tL2C_CCB* p_ccb, BT_HDR* p_buf) {
822   CHECK(p_ccb != NULL);
823   CHECK(p_buf != NULL);
824   uint8_t* p = (uint8_t*)(p_buf + 1) + p_buf->offset;
825   uint16_t sdu_length;
826   BT_HDR* p_data = NULL;
827 
828   /* Buffer length should not exceed local mps */
829   if (p_buf->len > p_ccb->local_conn_cfg.mps) {
830     /* Discard the buffer */
831     osi_free(p_buf);
832     return;
833   }
834 
835   if (p_ccb->is_first_seg) {
836     STREAM_TO_UINT16(sdu_length, p);
837     /* Check the SDU Length with local MTU size */
838     if (sdu_length > p_ccb->local_conn_cfg.mtu) {
839       /* Discard the buffer */
840       osi_free(p_buf);
841       return;
842     }
843 
844     p_data = (BT_HDR*)osi_malloc(BT_HDR_SIZE + sdu_length);
845     if (p_data == NULL) {
846       osi_free(p_buf);
847       return;
848     }
849 
850     p_ccb->ble_sdu = p_data;
851     p_data->len = 0;
852     p_ccb->ble_sdu_length = sdu_length;
853     L2CAP_TRACE_DEBUG("%s SDU Length = %d", __func__, sdu_length);
854     p_buf->len -= sizeof(sdu_length);
855     p_buf->offset += sizeof(sdu_length);
856     p_data->offset = 0;
857 
858   } else {
859     p_data = p_ccb->ble_sdu;
860     if (p_buf->len > (p_ccb->ble_sdu_length - p_data->len)) {
861       L2CAP_TRACE_ERROR("%s: buffer length=%d too big. max=%d. Dropped",
862                         __func__, p_data->len,
863                         (p_ccb->ble_sdu_length - p_data->len));
864       android_errorWriteWithInfoLog(0x534e4554, "75298652", -1, NULL, 0);
865       osi_free(p_buf);
866 
867       /* Throw away all pending fragments and disconnects */
868       p_ccb->is_first_seg = true;
869       osi_free(p_ccb->ble_sdu);
870       p_ccb->ble_sdu = NULL;
871       p_ccb->ble_sdu_length = 0;
872       l2cu_disconnect_chnl(p_ccb);
873       return;
874     }
875   }
876 
877   memcpy((uint8_t*)(p_data + 1) + p_data->offset + p_data->len,
878          (uint8_t*)(p_buf + 1) + p_buf->offset, p_buf->len);
879   p_data->len += p_buf->len;
880   p = (uint8_t*)(p_data + 1) + p_data->offset;
881   if (p_data->len == p_ccb->ble_sdu_length) {
882     l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DATA, p_data);
883     p_ccb->is_first_seg = true;
884     p_ccb->ble_sdu = NULL;
885     p_ccb->ble_sdu_length = 0;
886   } else if (p_data->len < p_ccb->ble_sdu_length) {
887     p_ccb->is_first_seg = false;
888   }
889 
890   osi_free(p_buf);
891   return;
892 }
893 
894 /*******************************************************************************
895  *
896  * Function         l2c_fcr_proc_tout
897  *
898  * Description      Handle a timeout. We should be in error recovery state.
899  *
900  * Returns          -
901  *
902  ******************************************************************************/
l2c_fcr_proc_tout(tL2C_CCB * p_ccb)903 void l2c_fcr_proc_tout(tL2C_CCB* p_ccb) {
904   CHECK(p_ccb != NULL);
905   L2CAP_TRACE_DEBUG(
906       "l2c_fcr_proc_tout:  CID: 0x%04x  num_tries: %u (max: %u)  wait_ack: %u  "
907       "ack_q_count: %u",
908       p_ccb->local_cid, p_ccb->fcrb.num_tries, p_ccb->peer_cfg.fcr.max_transmit,
909       p_ccb->fcrb.wait_ack, fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
910 
911 #if (L2CAP_ERTM_STATS == TRUE)
912   p_ccb->fcrb.retrans_touts++;
913 #endif
914 
915   if ((p_ccb->peer_cfg.fcr.max_transmit != 0) &&
916       (++p_ccb->fcrb.num_tries > p_ccb->peer_cfg.fcr.max_transmit)) {
917     l2cu_disconnect_chnl(p_ccb);
918   } else {
919     if (!p_ccb->fcrb.srej_sent && !p_ccb->fcrb.rej_sent) {
920       if (p_ccb->fcrb.local_busy)
921         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, L2CAP_FCR_P_BIT);
922       else
923         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_P_BIT);
924     }
925   }
926 }
927 
928 /*******************************************************************************
929  *
930  * Function         l2c_fcr_proc_ack_tout
931  *
932  * Description      Send RR/RNR if we have not acked I frame
933  *
934  * Returns          -
935  *
936  ******************************************************************************/
l2c_fcr_proc_ack_tout(tL2C_CCB * p_ccb)937 void l2c_fcr_proc_ack_tout(tL2C_CCB* p_ccb) {
938   CHECK(p_ccb != NULL);
939   L2CAP_TRACE_DEBUG(
940       "l2c_fcr_proc_ack_tout:  CID: 0x%04x State: %u  Wack:%u  Rq:%d  Acked:%d",
941       p_ccb->local_cid, p_ccb->chnl_state, p_ccb->fcrb.wait_ack,
942       p_ccb->fcrb.next_seq_expected, p_ccb->fcrb.last_ack_sent);
943 
944   if ((p_ccb->chnl_state == CST_OPEN) && (!p_ccb->fcrb.wait_ack) &&
945       (p_ccb->fcrb.last_ack_sent != p_ccb->fcrb.next_seq_expected)) {
946 #if (L2CAP_ERTM_STATS == TRUE)
947     p_ccb->fcrb.xmit_ack_touts++;
948 #endif
949     if (p_ccb->fcrb.local_busy)
950       l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, 0);
951     else
952       l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, 0);
953   }
954 }
955 
956 /*******************************************************************************
957  *
958  * Function         process_reqseq
959  *
960  * Description      Handle receive sequence number
961  *
962  * Returns          -
963  *
964  ******************************************************************************/
process_reqseq(tL2C_CCB * p_ccb,uint16_t ctrl_word)965 static bool process_reqseq(tL2C_CCB* p_ccb, uint16_t ctrl_word) {
966   CHECK(p_ccb != NULL);
967   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
968   uint8_t req_seq, num_bufs_acked, xx;
969   uint16_t ls;
970   uint16_t full_sdus_xmitted;
971 
972   /* Receive sequence number does not ack anything for SREJ with P-bit set to
973    * zero */
974   if ((ctrl_word & L2CAP_FCR_S_FRAME_BIT) &&
975       ((ctrl_word & L2CAP_FCR_SUP_BITS) ==
976        (L2CAP_FCR_SUP_SREJ << L2CAP_FCR_SUP_SHIFT)) &&
977       ((ctrl_word & L2CAP_FCR_P_BIT) == 0)) {
978     /* If anything still waiting for ack, restart the timer if it was stopped */
979     if (!fixed_queue_is_empty(p_fcrb->waiting_for_ack_q))
980       l2c_fcr_start_timer(p_ccb);
981 
982     return (true);
983   }
984 
985   /* Extract the receive sequence number from the control word */
986   req_seq =
987       (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT;
988 
989   num_bufs_acked = (req_seq - p_fcrb->last_rx_ack) & L2CAP_FCR_SEQ_MODULO;
990 
991   /* Verify the request sequence is in range before proceeding */
992   if (num_bufs_acked > fixed_queue_length(p_fcrb->waiting_for_ack_q)) {
993     /* The channel is closed if ReqSeq is not in range */
994     L2CAP_TRACE_WARNING(
995         "L2CAP eRTM Frame BAD Req_Seq - ctrl_word: 0x%04x  req_seq 0x%02x  "
996         "last_rx_ack: 0x%02x  QCount: %u",
997         ctrl_word, req_seq, p_fcrb->last_rx_ack,
998         fixed_queue_length(p_fcrb->waiting_for_ack_q));
999 
1000     l2cu_disconnect_chnl(p_ccb);
1001     return (false);
1002   }
1003 
1004   p_fcrb->last_rx_ack = req_seq;
1005 
1006   /* Now we can release all acknowledged frames, and restart the retransmission
1007    * timer if needed */
1008   if (num_bufs_acked != 0) {
1009     p_fcrb->num_tries = 0;
1010     full_sdus_xmitted = 0;
1011 
1012 #if (L2CAP_ERTM_STATS == TRUE)
1013     l2c_fcr_collect_ack_delay(p_ccb, num_bufs_acked);
1014 #endif
1015 
1016     for (xx = 0; xx < num_bufs_acked; xx++) {
1017       BT_HDR* p_tmp =
1018           (BT_HDR*)fixed_queue_try_dequeue(p_fcrb->waiting_for_ack_q);
1019       ls = p_tmp->layer_specific & L2CAP_FCR_SAR_BITS;
1020 
1021       if ((ls == L2CAP_FCR_UNSEG_SDU) || (ls == L2CAP_FCR_END_SDU))
1022         full_sdus_xmitted++;
1023 
1024       osi_free(p_tmp);
1025     }
1026 
1027     /* If we are still in a wait_ack state, do not mess with the timer */
1028     if (!p_ccb->fcrb.wait_ack) l2c_fcr_stop_timer(p_ccb);
1029 
1030     /* Check if we need to call the "packet_sent" callback */
1031     if ((p_ccb->p_rcb) && (p_ccb->p_rcb->api.pL2CA_TxComplete_Cb) &&
1032         (full_sdus_xmitted)) {
1033       /* Special case for eRTM, if all packets sent, send 0xFFFF */
1034       if (fixed_queue_is_empty(p_fcrb->waiting_for_ack_q) &&
1035           fixed_queue_is_empty(p_ccb->xmit_hold_q)) {
1036         full_sdus_xmitted = 0xFFFF;
1037       }
1038 
1039       (*p_ccb->p_rcb->api.pL2CA_TxComplete_Cb)(p_ccb->local_cid,
1040                                                full_sdus_xmitted);
1041     }
1042   }
1043 
1044   /* If anything still waiting for ack, restart the timer if it was stopped */
1045   if (!fixed_queue_is_empty(p_fcrb->waiting_for_ack_q))
1046     l2c_fcr_start_timer(p_ccb);
1047   return (true);
1048 }
1049 
1050 /*******************************************************************************
1051  *
1052  * Function         process_s_frame
1053  *
1054  * Description      Process an S frame
1055  *
1056  * Returns          -
1057  *
1058  ******************************************************************************/
process_s_frame(tL2C_CCB * p_ccb,BT_HDR * p_buf,uint16_t ctrl_word)1059 static void process_s_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf,
1060                             uint16_t ctrl_word) {
1061   CHECK(p_ccb != NULL);
1062   CHECK(p_buf != NULL);
1063 
1064   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
1065   uint16_t s_frame_type =
1066       (ctrl_word & L2CAP_FCR_SUP_BITS) >> L2CAP_FCR_SUP_SHIFT;
1067   bool remote_was_busy;
1068   bool all_ok = true;
1069 
1070   if (p_buf->len != 0) {
1071     L2CAP_TRACE_WARNING("Incorrect S-frame Length (%d)", p_buf->len);
1072   }
1073 
1074   L2CAP_TRACE_DEBUG("process_s_frame ctrl_word 0x%04x fcrb_remote_busy:%d",
1075                     ctrl_word, p_fcrb->remote_busy);
1076 
1077 #if (L2CAP_ERTM_STATS == TRUE)
1078   p_ccb->fcrb.s_frames_rcvd[s_frame_type]++;
1079 #endif
1080 
1081   if (ctrl_word & L2CAP_FCR_P_BIT) {
1082     p_fcrb->rej_sent = false;  /* After checkpoint, we can send anoher REJ */
1083     p_fcrb->send_f_rsp = true; /* Set a flag in case an I-frame is pending */
1084   }
1085 
1086   switch (s_frame_type) {
1087     case L2CAP_FCR_SUP_RR:
1088       remote_was_busy = p_fcrb->remote_busy;
1089       p_fcrb->remote_busy = false;
1090 
1091       if ((ctrl_word & L2CAP_FCR_F_BIT) || (remote_was_busy))
1092         all_ok = retransmit_i_frames(p_ccb, L2C_FCR_RETX_ALL_PKTS);
1093       break;
1094 
1095     case L2CAP_FCR_SUP_REJ:
1096       p_fcrb->remote_busy = false;
1097       all_ok = retransmit_i_frames(p_ccb, L2C_FCR_RETX_ALL_PKTS);
1098       break;
1099 
1100     case L2CAP_FCR_SUP_RNR:
1101       p_fcrb->remote_busy = true;
1102       l2c_fcr_stop_timer(p_ccb);
1103       break;
1104 
1105     case L2CAP_FCR_SUP_SREJ:
1106       p_fcrb->remote_busy = false;
1107       all_ok = retransmit_i_frames(
1108           p_ccb, (uint8_t)((ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >>
1109                            L2CAP_FCR_REQ_SEQ_BITS_SHIFT));
1110       break;
1111   }
1112 
1113   if (all_ok) {
1114     /* If polled, we need to respond with F-bit. Note, we may have sent a
1115      * I-frame with the F-bit */
1116     if (p_fcrb->send_f_rsp) {
1117       if (p_fcrb->srej_sent)
1118         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_SREJ, L2CAP_FCR_F_BIT);
1119       else if (p_fcrb->local_busy)
1120         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, L2CAP_FCR_F_BIT);
1121       else
1122         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, L2CAP_FCR_F_BIT);
1123 
1124       p_fcrb->send_f_rsp = false;
1125     }
1126   } else {
1127     L2CAP_TRACE_DEBUG("process_s_frame hit_max_retries");
1128   }
1129 
1130   osi_free(p_buf);
1131 }
1132 
1133 /*******************************************************************************
1134  *
1135  * Function         process_i_frame
1136  *
1137  * Description      Process an I frame
1138  *
1139  * Returns          -
1140  *
1141  ******************************************************************************/
process_i_frame(tL2C_CCB * p_ccb,BT_HDR * p_buf,uint16_t ctrl_word,bool delay_ack)1142 static void process_i_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf, uint16_t ctrl_word,
1143                             bool delay_ack) {
1144   CHECK(p_ccb != NULL);
1145   CHECK(p_buf != NULL);
1146 
1147   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
1148   uint8_t tx_seq, num_lost, num_to_ack, next_srej;
1149 
1150   /* If we were doing checkpoint recovery, first retransmit all unacked I-frames
1151    */
1152   if (ctrl_word & L2CAP_FCR_F_BIT) {
1153     if (!retransmit_i_frames(p_ccb, L2C_FCR_RETX_ALL_PKTS)) {
1154       osi_free(p_buf);
1155       return;
1156     }
1157   }
1158 
1159 #if (L2CAP_ERTM_STATS == TRUE)
1160   p_ccb->fcrb.ertm_pkt_counts[1]++;
1161   p_ccb->fcrb.ertm_byte_counts[1] += p_buf->len;
1162 #endif
1163 
1164   /* Extract the sequence number */
1165   tx_seq = (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;
1166 
1167   /* If we have flow controlled the peer, ignore any bad I-frames from him */
1168   if ((tx_seq != p_fcrb->next_seq_expected) && (p_fcrb->local_busy)) {
1169     L2CAP_TRACE_WARNING("Dropping bad I-Frame since we flowed off, tx_seq:%u",
1170                         tx_seq);
1171     l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, 0);
1172     osi_free(p_buf);
1173     return;
1174   }
1175 
1176   /* Check if tx-sequence is the expected one */
1177   if (tx_seq != p_fcrb->next_seq_expected) {
1178     num_lost = (tx_seq - p_fcrb->next_seq_expected) & L2CAP_FCR_SEQ_MODULO;
1179 
1180     /* Is the frame a duplicate ? If so, just drop it */
1181     if (num_lost >= p_ccb->our_cfg.fcr.tx_win_sz) {
1182       /* Duplicate - simply drop it */
1183       L2CAP_TRACE_WARNING(
1184           "process_i_frame() Dropping Duplicate Frame tx_seq:%u  ExpectedTxSeq "
1185           "%u",
1186           tx_seq, p_fcrb->next_seq_expected);
1187       osi_free(p_buf);
1188     } else {
1189       L2CAP_TRACE_WARNING(
1190           "process_i_frame() CID: 0x%04x  Lost: %u  tx_seq:%u  ExpTxSeq %u  "
1191           "Rej: %u  SRej: %u",
1192           p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected,
1193           p_fcrb->rej_sent, p_fcrb->srej_sent);
1194 
1195       if (p_fcrb->srej_sent) {
1196         /* If SREJ sent, save the frame for later processing as long as it is in
1197          * sequence */
1198         next_srej =
1199             (((BT_HDR*)fixed_queue_try_peek_last(p_fcrb->srej_rcv_hold_q))
1200                  ->layer_specific +
1201              1) &
1202             L2CAP_FCR_SEQ_MODULO;
1203 
1204         if ((tx_seq == next_srej) &&
1205             (fixed_queue_length(p_fcrb->srej_rcv_hold_q) <
1206              p_ccb->our_cfg.fcr.tx_win_sz)) {
1207           /* If user gave us a pool for held rx buffers, use that */
1208           /* TODO: Could that happen? Get rid of this code. */
1209           if (p_ccb->ertm_info.fcr_rx_buf_size != L2CAP_FCR_RX_BUF_SIZE) {
1210             BT_HDR* p_buf2;
1211 
1212             /* Adjust offset and len so that control word is copied */
1213             p_buf->offset -= L2CAP_FCR_OVERHEAD;
1214             p_buf->len += L2CAP_FCR_OVERHEAD;
1215 
1216             p_buf2 = l2c_fcr_clone_buf(p_buf, p_buf->offset, p_buf->len);
1217 
1218             if (p_buf2) {
1219               osi_free(p_buf);
1220               p_buf = p_buf2;
1221             }
1222             p_buf->offset += L2CAP_FCR_OVERHEAD;
1223             p_buf->len -= L2CAP_FCR_OVERHEAD;
1224           }
1225           L2CAP_TRACE_DEBUG(
1226               "process_i_frame() Lost: %u  tx_seq:%u  ExpTxSeq %u  Rej: %u  "
1227               "SRej1",
1228               num_lost, tx_seq, p_fcrb->next_seq_expected, p_fcrb->rej_sent);
1229 
1230           p_buf->layer_specific = tx_seq;
1231           fixed_queue_enqueue(p_fcrb->srej_rcv_hold_q, p_buf);
1232         } else {
1233           L2CAP_TRACE_WARNING(
1234               "process_i_frame() CID: 0x%04x  frame dropped in Srej Sent "
1235               "next_srej:%u  hold_q.count:%u  win_sz:%u",
1236               p_ccb->local_cid, next_srej,
1237               fixed_queue_length(p_fcrb->srej_rcv_hold_q),
1238               p_ccb->our_cfg.fcr.tx_win_sz);
1239 
1240           p_fcrb->rej_after_srej = true;
1241           osi_free(p_buf);
1242         }
1243       } else if (p_fcrb->rej_sent) {
1244         L2CAP_TRACE_WARNING(
1245             "process_i_frame() CID: 0x%04x  Lost: %u  tx_seq:%u  ExpTxSeq %u  "
1246             "Rej: 1  SRej: %u",
1247             p_ccb->local_cid, num_lost, tx_seq, p_fcrb->next_seq_expected,
1248             p_fcrb->srej_sent);
1249 
1250         /* If REJ sent, just drop the frame */
1251         osi_free(p_buf);
1252       } else {
1253         L2CAP_TRACE_DEBUG(
1254             "process_i_frame() CID: 0x%04x  tx_seq:%u  ExpTxSeq %u  Rej: %u",
1255             p_ccb->local_cid, tx_seq, p_fcrb->next_seq_expected,
1256             p_fcrb->rej_sent);
1257 
1258         /* If only one lost, we will send SREJ, otherwise we will send REJ */
1259         if (num_lost > 1) {
1260           osi_free(p_buf);
1261           p_fcrb->rej_sent = true;
1262           l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_REJ, 0);
1263         } else {
1264           if (!fixed_queue_is_empty(p_fcrb->srej_rcv_hold_q)) {
1265             L2CAP_TRACE_ERROR(
1266                 "process_i_frame() CID: 0x%04x  sending SREJ tx_seq:%d "
1267                 "hold_q.count:%u",
1268                 p_ccb->local_cid, tx_seq,
1269                 fixed_queue_length(p_fcrb->srej_rcv_hold_q));
1270           }
1271           p_buf->layer_specific = tx_seq;
1272           fixed_queue_enqueue(p_fcrb->srej_rcv_hold_q, p_buf);
1273           p_fcrb->srej_sent = true;
1274           l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_SREJ, 0);
1275         }
1276         alarm_cancel(p_ccb->fcrb.ack_timer);
1277       }
1278     }
1279     return;
1280   }
1281 
1282   /* Seq number is the next expected. Clear possible reject exception in case it
1283    * occured */
1284   p_fcrb->rej_sent = p_fcrb->srej_sent = false;
1285 
1286   /* Adjust the next_seq, so that if the upper layer sends more data in the
1287      callback
1288      context, the received frame is acked by an I-frame. */
1289   p_fcrb->next_seq_expected = (tx_seq + 1) & L2CAP_FCR_SEQ_MODULO;
1290 
1291   /* If any SAR problem in eRTM mode, spec says disconnect. */
1292   if (!do_sar_reassembly(p_ccb, p_buf, ctrl_word)) {
1293     L2CAP_TRACE_WARNING("process_i_frame() CID: 0x%04x  reassembly failed",
1294                         p_ccb->local_cid);
1295     l2cu_disconnect_chnl(p_ccb);
1296     return;
1297   }
1298 
1299   /* RR optimization - if peer can still send us more, then start an ACK timer
1300    */
1301   num_to_ack = (p_fcrb->next_seq_expected - p_fcrb->last_ack_sent) &
1302                L2CAP_FCR_SEQ_MODULO;
1303 
1304   if ((num_to_ack < p_ccb->fcrb.max_held_acks) && (!p_fcrb->local_busy))
1305     delay_ack = true;
1306 
1307   /* We should neve never ack frame if we are not in OPEN state */
1308   if ((num_to_ack != 0) && p_ccb->in_use && (p_ccb->chnl_state == CST_OPEN)) {
1309     /* If no frames are awaiting transmission or are held, send an RR or RNR
1310      * S-frame for ack */
1311     if (delay_ack) {
1312       /* If it is the first I frame we did not ack, start ack timer */
1313       if (!alarm_is_scheduled(p_ccb->fcrb.ack_timer)) {
1314         alarm_set_on_mloop(p_ccb->fcrb.ack_timer, L2CAP_FCR_ACK_TIMEOUT_MS,
1315                            l2c_fcrb_ack_timer_timeout, p_ccb);
1316       }
1317     } else if ((fixed_queue_is_empty(p_ccb->xmit_hold_q) ||
1318                 l2c_fcr_is_flow_controlled(p_ccb)) &&
1319                fixed_queue_is_empty(p_ccb->fcrb.srej_rcv_hold_q)) {
1320       if (p_fcrb->local_busy)
1321         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RNR, 0);
1322       else
1323         l2c_fcr_send_S_frame(p_ccb, L2CAP_FCR_SUP_RR, 0);
1324     }
1325   }
1326 }
1327 
1328 /*******************************************************************************
1329  *
1330  * Function         process_stream_frame
1331  *
1332  * Description      This function processes frames in streaming mode
1333  *
1334  * Returns          -
1335  *
1336  ******************************************************************************/
process_stream_frame(tL2C_CCB * p_ccb,BT_HDR * p_buf)1337 static void process_stream_frame(tL2C_CCB* p_ccb, BT_HDR* p_buf) {
1338   CHECK(p_ccb != NULL);
1339   CHECK(p_buf != NULL);
1340 
1341   uint16_t ctrl_word;
1342   uint16_t fcs;
1343   uint8_t* p;
1344   uint8_t tx_seq;
1345 
1346   /* Verify FCS if using */
1347   if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
1348     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len - L2CAP_FCS_LEN;
1349 
1350     /* Extract and drop the FCS from the packet */
1351     STREAM_TO_UINT16(fcs, p);
1352     p_buf->len -= L2CAP_FCS_LEN;
1353 
1354     if (l2c_fcr_rx_get_fcs(p_buf) != fcs) {
1355       L2CAP_TRACE_WARNING("Rx L2CAP PDU: CID: 0x%04x  BAD FCS",
1356                           p_ccb->local_cid);
1357       osi_free(p_buf);
1358       return;
1359     }
1360   }
1361 
1362   /* Get the control word */
1363   p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
1364 
1365   STREAM_TO_UINT16(ctrl_word, p);
1366 
1367   p_buf->len -= L2CAP_FCR_OVERHEAD;
1368   p_buf->offset += L2CAP_FCR_OVERHEAD;
1369 
1370   /* Make sure it is an I-frame */
1371   if (ctrl_word & L2CAP_FCR_S_FRAME_BIT) {
1372     L2CAP_TRACE_WARNING(
1373         "Rx L2CAP PDU: CID: 0x%04x  BAD S-frame in streaming mode  ctrl_word: "
1374         "0x%04x",
1375         p_ccb->local_cid, ctrl_word);
1376     osi_free(p_buf);
1377     return;
1378   }
1379 
1380   L2CAP_TRACE_EVENT(
1381       "L2CAP eRTM Rx I-frame: cid: 0x%04x  Len: %u  SAR: %-12s  TxSeq: %u  "
1382       "ReqSeq: %u  F: %u",
1383       p_ccb->local_cid, p_buf->len,
1384       SAR_types[(ctrl_word & L2CAP_FCR_SAR_BITS) >> L2CAP_FCR_SAR_BITS_SHIFT],
1385       (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT,
1386       (ctrl_word & L2CAP_FCR_REQ_SEQ_BITS) >> L2CAP_FCR_REQ_SEQ_BITS_SHIFT,
1387       (ctrl_word & L2CAP_FCR_F_BIT) >> L2CAP_FCR_F_BIT_SHIFT);
1388 
1389   /* Extract the sequence number */
1390   tx_seq = (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;
1391 
1392   /* Check if tx-sequence is the expected one */
1393   if (tx_seq != p_ccb->fcrb.next_seq_expected) {
1394     L2CAP_TRACE_WARNING(
1395         "Rx L2CAP PDU: CID: 0x%04x  Lost frames Exp: %u  Got: %u  p_rx_sdu: "
1396         "0x%08x",
1397         p_ccb->local_cid, p_ccb->fcrb.next_seq_expected, tx_seq,
1398         p_ccb->fcrb.p_rx_sdu);
1399 
1400     /* Lost one or more packets, so flush the SAR queue */
1401     osi_free_and_reset((void**)&p_ccb->fcrb.p_rx_sdu);
1402   }
1403 
1404   p_ccb->fcrb.next_seq_expected = (tx_seq + 1) & L2CAP_FCR_SEQ_MODULO;
1405 
1406   if (!do_sar_reassembly(p_ccb, p_buf, ctrl_word)) {
1407     /* Some sort of SAR error, so flush the SAR queue */
1408     osi_free_and_reset((void**)&p_ccb->fcrb.p_rx_sdu);
1409   }
1410 }
1411 
1412 /*******************************************************************************
1413  *
1414  * Function         do_sar_reassembly
1415  *
1416  * Description      Process SAR bits and re-assemble frame
1417  *
1418  * Returns          true if all OK, else false
1419  *
1420  ******************************************************************************/
do_sar_reassembly(tL2C_CCB * p_ccb,BT_HDR * p_buf,uint16_t ctrl_word)1421 static bool do_sar_reassembly(tL2C_CCB* p_ccb, BT_HDR* p_buf,
1422                               uint16_t ctrl_word) {
1423   CHECK(p_ccb != NULL);
1424   CHECK(p_buf != NULL);
1425 
1426   tL2C_FCRB* p_fcrb = &p_ccb->fcrb;
1427   uint16_t sar_type = ctrl_word & L2CAP_FCR_SEG_BITS;
1428   bool packet_ok = true;
1429   uint8_t* p;
1430 
1431   /* Check if the SAR state is correct */
1432   if ((sar_type == L2CAP_FCR_UNSEG_SDU) || (sar_type == L2CAP_FCR_START_SDU)) {
1433     if (p_fcrb->p_rx_sdu != NULL) {
1434       L2CAP_TRACE_WARNING(
1435           "SAR - got unexpected unsegmented or start SDU  Expected len: %u  "
1436           "Got so far: %u",
1437           p_fcrb->rx_sdu_len, p_fcrb->p_rx_sdu->len);
1438 
1439       packet_ok = false;
1440     }
1441     /* Check the length of the packet */
1442     if ((sar_type == L2CAP_FCR_START_SDU) &&
1443         (p_buf->len < L2CAP_SDU_LEN_OVERHEAD)) {
1444       L2CAP_TRACE_WARNING("SAR start packet too short: %u", p_buf->len);
1445       packet_ok = false;
1446     }
1447   } else {
1448     if (p_fcrb->p_rx_sdu == NULL) {
1449       L2CAP_TRACE_WARNING("SAR - got unexpected cont or end SDU");
1450       packet_ok = false;
1451     }
1452   }
1453 
1454   if ((packet_ok) && (sar_type != L2CAP_FCR_UNSEG_SDU)) {
1455     p = ((uint8_t*)(p_buf + 1)) + p_buf->offset;
1456 
1457     /* For start SDU packet, extract the SDU length */
1458     if (sar_type == L2CAP_FCR_START_SDU) {
1459       /* Get the SDU length */
1460       STREAM_TO_UINT16(p_fcrb->rx_sdu_len, p);
1461       p_buf->offset += 2;
1462       p_buf->len -= 2;
1463 
1464       if (p_fcrb->rx_sdu_len > p_ccb->max_rx_mtu) {
1465         L2CAP_TRACE_WARNING("SAR - SDU len: %u  larger than MTU: %u",
1466                             p_fcrb->rx_sdu_len, p_fcrb->rx_sdu_len);
1467         packet_ok = false;
1468       } else {
1469         p_fcrb->p_rx_sdu = (BT_HDR*)osi_malloc(
1470             BT_HDR_SIZE + OBX_BUF_MIN_OFFSET + p_fcrb->rx_sdu_len);
1471         p_fcrb->p_rx_sdu->offset = OBX_BUF_MIN_OFFSET;
1472         p_fcrb->p_rx_sdu->len = 0;
1473       }
1474     }
1475 
1476     if (packet_ok) {
1477       if ((p_fcrb->p_rx_sdu->len + p_buf->len) > p_fcrb->rx_sdu_len) {
1478         L2CAP_TRACE_ERROR(
1479             "SAR - SDU len exceeded  Type: %u   Lengths: %u %u %u", sar_type,
1480             p_fcrb->p_rx_sdu->len, p_buf->len, p_fcrb->rx_sdu_len);
1481         packet_ok = false;
1482       } else if ((sar_type == L2CAP_FCR_END_SDU) &&
1483                  ((p_fcrb->p_rx_sdu->len + p_buf->len) != p_fcrb->rx_sdu_len)) {
1484         L2CAP_TRACE_WARNING("SAR - SDU end rcvd but SDU incomplete: %u %u %u",
1485                             p_fcrb->p_rx_sdu->len, p_buf->len,
1486                             p_fcrb->rx_sdu_len);
1487         packet_ok = false;
1488       } else {
1489         memcpy(((uint8_t*)(p_fcrb->p_rx_sdu + 1)) + p_fcrb->p_rx_sdu->offset +
1490                    p_fcrb->p_rx_sdu->len,
1491                p, p_buf->len);
1492 
1493         p_fcrb->p_rx_sdu->len += p_buf->len;
1494 
1495         osi_free(p_buf);
1496         p_buf = NULL;
1497 
1498         if (sar_type == L2CAP_FCR_END_SDU) {
1499           p_buf = p_fcrb->p_rx_sdu;
1500           p_fcrb->p_rx_sdu = NULL;
1501         }
1502       }
1503     }
1504   }
1505 
1506   if (!packet_ok) {
1507     osi_free(p_buf);
1508   } else if (p_buf != NULL) {
1509 #if (L2CAP_NUM_FIXED_CHNLS > 0)
1510     if (p_ccb->local_cid < L2CAP_BASE_APPL_CID &&
1511         (p_ccb->local_cid >= L2CAP_FIRST_FIXED_CHNL &&
1512          p_ccb->local_cid <= L2CAP_LAST_FIXED_CHNL)) {
1513       if (l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL]
1514               .pL2CA_FixedData_Cb)
1515         (*l2cb.fixed_reg[p_ccb->local_cid - L2CAP_FIRST_FIXED_CHNL]
1516               .pL2CA_FixedData_Cb)(p_ccb->local_cid,
1517                                    p_ccb->p_lcb->remote_bd_addr, p_buf);
1518     } else
1519 #endif
1520       l2c_csm_execute(p_ccb, L2CEVT_L2CAP_DATA, p_buf);
1521   }
1522 
1523   return (packet_ok);
1524 }
1525 
1526 /*******************************************************************************
1527  *
1528  * Function         retransmit_i_frames
1529  *
1530  * Description      This function retransmits i-frames awaiting acks.
1531  *
1532  * Returns          bool    - true if retransmitted
1533  *
1534  ******************************************************************************/
retransmit_i_frames(tL2C_CCB * p_ccb,uint8_t tx_seq)1535 static bool retransmit_i_frames(tL2C_CCB* p_ccb, uint8_t tx_seq) {
1536   CHECK(p_ccb != NULL);
1537 
1538   BT_HDR* p_buf = NULL;
1539   uint8_t* p;
1540   uint8_t buf_seq;
1541   uint16_t ctrl_word;
1542 
1543   if ((!fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q)) &&
1544       (p_ccb->peer_cfg.fcr.max_transmit != 0) &&
1545       (p_ccb->fcrb.num_tries >= p_ccb->peer_cfg.fcr.max_transmit)) {
1546     L2CAP_TRACE_EVENT(
1547         "Max Tries Exceeded:  (last_acq: %d  CID: 0x%04x  num_tries: %u (max: "
1548         "%u) ack_q_count: %u",
1549         p_ccb->fcrb.last_rx_ack, p_ccb->local_cid, p_ccb->fcrb.num_tries,
1550         p_ccb->peer_cfg.fcr.max_transmit,
1551         fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
1552 
1553     l2cu_disconnect_chnl(p_ccb);
1554     return (false);
1555   }
1556 
1557   /* tx_seq indicates whether to retransmit a specific sequence or all (if ==
1558    * L2C_FCR_RETX_ALL_PKTS) */
1559   list_t* list_ack = NULL;
1560   const list_node_t* node_ack = NULL;
1561   if (!fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q)) {
1562     list_ack = fixed_queue_get_list(p_ccb->fcrb.waiting_for_ack_q);
1563     node_ack = list_begin(list_ack);
1564   }
1565   if (tx_seq != L2C_FCR_RETX_ALL_PKTS) {
1566     /* If sending only one, the sequence number tells us which one. Look for it.
1567     */
1568     if (list_ack != NULL) {
1569       for (; node_ack != list_end(list_ack); node_ack = list_next(node_ack)) {
1570         p_buf = (BT_HDR*)list_node(node_ack);
1571         /* Get the old control word */
1572         p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + L2CAP_PKT_OVERHEAD;
1573 
1574         STREAM_TO_UINT16(ctrl_word, p);
1575 
1576         buf_seq =
1577             (ctrl_word & L2CAP_FCR_TX_SEQ_BITS) >> L2CAP_FCR_TX_SEQ_BITS_SHIFT;
1578 
1579         L2CAP_TRACE_DEBUG(
1580             "retransmit_i_frames()   cur seq: %u  looking for: %u", buf_seq,
1581             tx_seq);
1582 
1583         if (tx_seq == buf_seq) break;
1584       }
1585     }
1586 
1587     if (!p_buf) {
1588       L2CAP_TRACE_ERROR("retransmit_i_frames() UNKNOWN seq: %u  q_count: %u",
1589                         tx_seq,
1590                         fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q));
1591       return (true);
1592     }
1593   } else {
1594     // Iterate though list and flush the amount requested from
1595     // the transmit data queue that satisfy the layer and event conditions.
1596     for (list_node_t* node_tmp = list_begin(p_ccb->p_lcb->link_xmit_data_q);
1597          node_tmp != list_end(p_ccb->p_lcb->link_xmit_data_q);) {
1598       BT_HDR* p_tmp = (BT_HDR*)list_node(node_tmp);
1599       node_tmp = list_next(node_tmp);
1600 
1601       /* Do not flush other CIDs or partial segments */
1602       if ((p_tmp->layer_specific == 0) && (p_tmp->event == p_ccb->local_cid)) {
1603         list_remove(p_ccb->p_lcb->link_xmit_data_q, p_tmp);
1604         osi_free(p_tmp);
1605       }
1606     }
1607 
1608     /* Also flush our retransmission queue */
1609     while (!fixed_queue_is_empty(p_ccb->fcrb.retrans_q))
1610       osi_free(fixed_queue_try_dequeue(p_ccb->fcrb.retrans_q));
1611 
1612     if (list_ack != NULL) node_ack = list_begin(list_ack);
1613   }
1614 
1615   if (list_ack != NULL) {
1616     while (node_ack != list_end(list_ack)) {
1617       p_buf = (BT_HDR*)list_node(node_ack);
1618       node_ack = list_next(node_ack);
1619 
1620       BT_HDR* p_buf2 = l2c_fcr_clone_buf(p_buf, p_buf->offset, p_buf->len);
1621       if (p_buf2) {
1622         p_buf2->layer_specific = p_buf->layer_specific;
1623 
1624         fixed_queue_enqueue(p_ccb->fcrb.retrans_q, p_buf2);
1625       }
1626 
1627       if ((tx_seq != L2C_FCR_RETX_ALL_PKTS) || (p_buf2 == NULL)) break;
1628     }
1629   }
1630 
1631   l2c_link_check_send_pkts(p_ccb->p_lcb, NULL, NULL);
1632 
1633   if (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q)) {
1634     p_ccb->fcrb.num_tries++;
1635     l2c_fcr_start_timer(p_ccb);
1636   }
1637 
1638   return (true);
1639 }
1640 
1641 /*******************************************************************************
1642  *
1643  * Function         l2c_fcr_get_next_xmit_sdu_seg
1644  *
1645  * Description      Get the next SDU segment to transmit.
1646  *
1647  * Returns          pointer to buffer with segment or NULL
1648  *
1649  ******************************************************************************/
l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB * p_ccb,uint16_t max_packet_length)1650 BT_HDR* l2c_fcr_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb,
1651                                       uint16_t max_packet_length) {
1652   CHECK(p_ccb != NULL);
1653 
1654   bool first_seg = false, /* The segment is the first part of data  */
1655       mid_seg = false,    /* The segment is the middle part of data */
1656       last_seg = false;   /* The segment is the last part of data   */
1657   uint16_t sdu_len = 0;
1658   BT_HDR *p_buf, *p_xmit;
1659   uint8_t* p;
1660   uint16_t max_pdu = p_ccb->tx_mps /* Needed? - L2CAP_MAX_HEADER_FCS*/;
1661 
1662   /* If there is anything in the retransmit queue, that goes first
1663   */
1664   p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->fcrb.retrans_q);
1665   if (p_buf != NULL) {
1666     /* Update Rx Seq and FCS if we acked some packets while this one was queued
1667      */
1668     prepare_I_frame(p_ccb, p_buf, true);
1669 
1670     p_buf->event = p_ccb->local_cid;
1671 
1672 #if (L2CAP_ERTM_STATS == TRUE)
1673     p_ccb->fcrb.pkts_retransmitted++;
1674     p_ccb->fcrb.ertm_pkt_counts[0]++;
1675     p_ccb->fcrb.ertm_byte_counts[0] += (p_buf->len - 8);
1676 #endif
1677     return (p_buf);
1678   }
1679 
1680   /* For BD/EDR controller, max_packet_length is set to 0             */
1681   /* For AMP controller, max_packet_length is set by available blocks */
1682   if ((max_packet_length > L2CAP_MAX_HEADER_FCS) &&
1683       (max_pdu + L2CAP_MAX_HEADER_FCS > max_packet_length)) {
1684     max_pdu = max_packet_length - L2CAP_MAX_HEADER_FCS;
1685   }
1686 
1687   p_buf = (BT_HDR*)fixed_queue_try_peek_first(p_ccb->xmit_hold_q);
1688 
1689   /* If there is more data than the MPS, it requires segmentation */
1690   if (p_buf->len > max_pdu) {
1691     /* We are using the "event" field to tell is if we already started
1692      * segmentation */
1693     if (p_buf->event == 0) {
1694       first_seg = true;
1695       sdu_len = p_buf->len;
1696     } else
1697       mid_seg = true;
1698 
1699     /* Get a new buffer and copy the data that can be sent in a PDU */
1700     p_xmit = l2c_fcr_clone_buf(p_buf, L2CAP_MIN_OFFSET + L2CAP_SDU_LEN_OFFSET,
1701                                max_pdu);
1702 
1703     if (p_xmit != NULL) {
1704       p_buf->event = p_ccb->local_cid;
1705       p_xmit->event = p_ccb->local_cid;
1706 
1707       p_buf->len -= max_pdu;
1708       p_buf->offset += max_pdu;
1709 
1710       /* copy PBF setting */
1711       p_xmit->layer_specific = p_buf->layer_specific;
1712     } else /* Should never happen if the application has configured buffers
1713               correctly */
1714     {
1715       L2CAP_TRACE_ERROR(
1716           "L2CAP - cannot get buffer for segmentation, max_pdu: %u", max_pdu);
1717       return (NULL);
1718     }
1719   } else /* Use the original buffer if no segmentation, or the last segment */
1720   {
1721     p_xmit = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
1722 
1723     if (p_xmit->event != 0) last_seg = true;
1724 
1725     p_xmit->event = p_ccb->local_cid;
1726   }
1727 
1728   /* Step back to add the L2CAP headers */
1729   p_xmit->offset -= (L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD);
1730   p_xmit->len += L2CAP_PKT_OVERHEAD + L2CAP_FCR_OVERHEAD;
1731 
1732   if (first_seg) {
1733     p_xmit->offset -= L2CAP_SDU_LEN_OVERHEAD;
1734     p_xmit->len += L2CAP_SDU_LEN_OVERHEAD;
1735   }
1736 
1737   /* Set the pointer to the beginning of the data */
1738   p = (uint8_t*)(p_xmit + 1) + p_xmit->offset;
1739 
1740   /* Now the L2CAP header */
1741 
1742   /* Note: if FCS has to be included then the length is recalculated later */
1743   UINT16_TO_STREAM(p, p_xmit->len - L2CAP_PKT_OVERHEAD);
1744 
1745   UINT16_TO_STREAM(p, p_ccb->remote_cid);
1746 
1747   if (first_seg) {
1748     /* Skip control word and add SDU length */
1749     p += 2;
1750     UINT16_TO_STREAM(p, sdu_len);
1751 
1752     /* We will store the SAR type in layer-specific */
1753     /* layer_specific is shared with flushable flag(bits 0-1), don't clear it */
1754     p_xmit->layer_specific |= L2CAP_FCR_START_SDU;
1755 
1756     first_seg = false;
1757   } else if (mid_seg)
1758     p_xmit->layer_specific |= L2CAP_FCR_CONT_SDU;
1759   else if (last_seg)
1760     p_xmit->layer_specific |= L2CAP_FCR_END_SDU;
1761   else
1762     p_xmit->layer_specific |= L2CAP_FCR_UNSEG_SDU;
1763 
1764   prepare_I_frame(p_ccb, p_xmit, false);
1765 
1766   if (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) {
1767     BT_HDR* p_wack =
1768         l2c_fcr_clone_buf(p_xmit, HCI_DATA_PREAMBLE_SIZE, p_xmit->len);
1769 
1770     if (!p_wack) {
1771       L2CAP_TRACE_ERROR(
1772           "L2CAP - no buffer for xmit cloning, CID: 0x%04x  Length: %u",
1773           p_ccb->local_cid, p_xmit->len);
1774 
1775       /* We will not save the FCS in case we reconfigure and change options */
1776       if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) p_xmit->len -= L2CAP_FCS_LEN;
1777 
1778       /* Pretend we sent it and it got lost */
1779       fixed_queue_enqueue(p_ccb->fcrb.waiting_for_ack_q, p_xmit);
1780       return (NULL);
1781     } else {
1782 #if (L2CAP_ERTM_STATS == TRUE)
1783       /* set timestamp at the end of tx I-frame to get acking delay */
1784       /*
1785        * NOTE: Here we assume the allocate buffer is large enough
1786        * to include extra 4 octets at the end.
1787        */
1788       p = ((uint8_t*)(p_wack + 1)) + p_wack->offset + p_wack->len;
1789       UINT32_TO_STREAM(p, time_get_os_boottime_ms());
1790 #endif
1791       /* We will not save the FCS in case we reconfigure and change options */
1792       if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) p_wack->len -= L2CAP_FCS_LEN;
1793 
1794       p_wack->layer_specific = p_xmit->layer_specific;
1795       fixed_queue_enqueue(p_ccb->fcrb.waiting_for_ack_q, p_wack);
1796     }
1797 
1798 #if (L2CAP_ERTM_STATS == TRUE)
1799     p_ccb->fcrb.ertm_pkt_counts[0]++;
1800     p_ccb->fcrb.ertm_byte_counts[0] += (p_xmit->len - 8);
1801 #endif
1802   }
1803 
1804   return (p_xmit);
1805 }
1806 
1807 /** Get the next PDU to transmit for LE connection oriented channel. Returns
1808  * pointer to buffer with PDU. |last_piece_of_sdu| will be set to true, if
1809  * returned PDU is last piece from this SDU.*/
l2c_lcc_get_next_xmit_sdu_seg(tL2C_CCB * p_ccb,bool * last_piece_of_sdu)1810 BT_HDR* l2c_lcc_get_next_xmit_sdu_seg(tL2C_CCB* p_ccb,
1811                                       bool* last_piece_of_sdu) {
1812   uint16_t max_pdu = p_ccb->peer_conn_cfg.mps - 4 /* Length and CID */;
1813 
1814   BT_HDR* p_buf = (BT_HDR*)fixed_queue_try_peek_first(p_ccb->xmit_hold_q);
1815   bool first_pdu = (p_buf->event == 0) ? true : false;
1816 
1817   uint16_t no_of_bytes_to_send = std::min(
1818       p_buf->len,
1819       (uint16_t)(first_pdu ? (max_pdu - L2CAP_LCC_SDU_LENGTH) : max_pdu));
1820   bool last_pdu = (no_of_bytes_to_send == p_buf->len);
1821 
1822   /* Get a new buffer and copy the data that can be sent in a PDU */
1823   BT_HDR* p_xmit =
1824       l2c_fcr_clone_buf(p_buf, first_pdu ? L2CAP_LCC_OFFSET : L2CAP_MIN_OFFSET,
1825                         no_of_bytes_to_send);
1826 
1827   p_buf->event = p_ccb->local_cid;
1828   p_xmit->event = p_ccb->local_cid;
1829 
1830   if (first_pdu) {
1831     p_xmit->offset -= L2CAP_LCC_SDU_LENGTH; /* for writing the SDU length. */
1832     uint8_t* p = (uint8_t*)(p_xmit + 1) + p_xmit->offset;
1833     UINT16_TO_STREAM(p, p_buf->len);
1834     p_xmit->len += L2CAP_LCC_SDU_LENGTH;
1835   }
1836 
1837   p_buf->len -= no_of_bytes_to_send;
1838   p_buf->offset += no_of_bytes_to_send;
1839 
1840   /* copy PBF setting */
1841   p_xmit->layer_specific = p_buf->layer_specific;
1842 
1843   if (last_piece_of_sdu) *last_piece_of_sdu = last_pdu;
1844 
1845   if (last_pdu) {
1846     p_buf = (BT_HDR*)fixed_queue_try_dequeue(p_ccb->xmit_hold_q);
1847     osi_free(p_buf);
1848   }
1849 
1850   /* Step back to add the L2CAP headers */
1851   p_xmit->offset -= L2CAP_PKT_OVERHEAD;
1852   p_xmit->len += L2CAP_PKT_OVERHEAD;
1853 
1854   /* Set the pointer to the beginning of the data */
1855   uint8_t* p = (uint8_t*)(p_xmit + 1) + p_xmit->offset;
1856 
1857   /* Note: if FCS has to be included then the length is recalculated later */
1858   UINT16_TO_STREAM(p, p_xmit->len - L2CAP_PKT_OVERHEAD);
1859   UINT16_TO_STREAM(p, p_ccb->remote_cid);
1860   return (p_xmit);
1861 }
1862 
1863 /*******************************************************************************
1864  * Configuration negotiation functions
1865  *
1866  * The following functions are used in negotiating channel modes during
1867  * configuration
1868  ******************************************************************************/
1869 
1870 /*******************************************************************************
1871  *
1872  * Function         l2c_fcr_chk_chan_modes
1873  *
1874  * Description      Validates and adjusts if necessary, the FCR options
1875  *                  based on remote EXT features.
1876  *
1877  *                  Note: This assumes peer EXT Features have been received.
1878  *                      Basic mode is used if FCR Options have not been received
1879  *
1880  * Returns          uint8_t - nonzero if can continue, '0' if no compatible
1881  *                            channels
1882  *
1883  ******************************************************************************/
l2c_fcr_chk_chan_modes(tL2C_CCB * p_ccb)1884 uint8_t l2c_fcr_chk_chan_modes(tL2C_CCB* p_ccb) {
1885   CHECK(p_ccb != NULL);
1886 
1887   /* Remove nonbasic options that the peer does not support */
1888   if (!(p_ccb->p_lcb->peer_ext_fea & L2CAP_EXTFEA_ENH_RETRANS))
1889     p_ccb->ertm_info.allowed_modes &= ~L2CAP_FCR_CHAN_OPT_ERTM;
1890 
1891   if (!(p_ccb->p_lcb->peer_ext_fea & L2CAP_EXTFEA_STREAM_MODE))
1892     p_ccb->ertm_info.allowed_modes &= ~L2CAP_FCR_CHAN_OPT_STREAM;
1893 
1894   /* At least one type needs to be set (Basic, ERTM, STM) to continue */
1895   if (!p_ccb->ertm_info.allowed_modes) {
1896     L2CAP_TRACE_WARNING(
1897         "L2CAP - Peer does not support our desired channel types");
1898   }
1899 
1900   return (p_ccb->ertm_info.allowed_modes);
1901 }
1902 
1903 /*******************************************************************************
1904  *
1905  * Function         l2c_fcr_adj_our_req_options
1906  *
1907  * Description      Validates and sets up the FCR options passed in from
1908  *                  L2CA_ConfigReq based on remote device's features.
1909  *
1910  * Returns          true if no errors, Otherwise false
1911  *
1912  ******************************************************************************/
l2c_fcr_adj_our_req_options(tL2C_CCB * p_ccb,tL2CAP_CFG_INFO * p_cfg)1913 bool l2c_fcr_adj_our_req_options(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
1914   CHECK(p_ccb != NULL);
1915   CHECK(p_cfg != NULL);
1916 
1917   tL2CAP_FCR_OPTS* p_fcr = &p_cfg->fcr;
1918 
1919   if (p_fcr->mode != p_ccb->ertm_info.preferred_mode) {
1920     L2CAP_TRACE_WARNING(
1921         "l2c_fcr_adj_our_req_options - preferred_mode (%d), does not match "
1922         "mode (%d)",
1923         p_ccb->ertm_info.preferred_mode, p_fcr->mode);
1924 
1925     /* The preferred mode is passed in through tL2CAP_ERTM_INFO, so override
1926      * this one */
1927     p_fcr->mode = p_ccb->ertm_info.preferred_mode;
1928   }
1929 
1930   /* If upper layer did not request eRTM mode, BASIC must be used */
1931   if (p_ccb->ertm_info.allowed_modes == L2CAP_FCR_CHAN_OPT_BASIC) {
1932     if (p_cfg->fcr_present && p_fcr->mode != L2CAP_FCR_BASIC_MODE) {
1933       L2CAP_TRACE_WARNING(
1934           "l2c_fcr_adj_our_req_options (mode %d): ERROR: No FCR options set "
1935           "using BASIC mode",
1936           p_fcr->mode);
1937     }
1938     p_fcr->mode = L2CAP_FCR_BASIC_MODE;
1939   }
1940 
1941   /* Process the FCR options if initial channel bring-up (not a reconfig
1942   *request)
1943   ** Determine initial channel mode to try based on our options and remote's
1944   *features
1945   */
1946   if (p_cfg->fcr_present && !(p_ccb->config_done & RECONFIG_FLAG)) {
1947     /* We need to have at least one mode type common with the peer */
1948     if (!l2c_fcr_chk_chan_modes(p_ccb)) {
1949       /* Two channels have incompatible supported types */
1950       l2cu_disconnect_chnl(p_ccb);
1951       return (false);
1952     }
1953 
1954     /* Basic is the only common channel mode between the two devices */
1955     else if (p_ccb->ertm_info.allowed_modes == L2CAP_FCR_CHAN_OPT_BASIC) {
1956       /* We only want to try Basic, so bypass sending the FCR options entirely
1957        */
1958       p_cfg->fcr_present = false;
1959       p_cfg->fcs_present = false; /* Illegal to use FCS option in basic mode */
1960       p_cfg->ext_flow_spec_present =
1961           false; /* Illegal to use extended flow spec in basic mode */
1962     }
1963 
1964     /* We have at least one non-basic mode available
1965      * Override mode from available mode options based on preference, if needed
1966      */
1967     else {
1968       /* If peer does not support STREAMING, try ERTM */
1969       if (p_fcr->mode == L2CAP_FCR_STREAM_MODE &&
1970           !(p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_STREAM)) {
1971         L2CAP_TRACE_DEBUG(
1972             "L2C CFG: mode is STREAM, but peer does not support; Try ERTM");
1973         p_fcr->mode = L2CAP_FCR_ERTM_MODE;
1974       }
1975 
1976       /* If peer does not support ERTM, try BASIC (will support this if made it
1977        * here in the code) */
1978       if (p_fcr->mode == L2CAP_FCR_ERTM_MODE &&
1979           !(p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_ERTM)) {
1980         L2CAP_TRACE_DEBUG(
1981             "L2C CFG: mode is ERTM, but peer does not support; Try BASIC");
1982         p_fcr->mode = L2CAP_FCR_BASIC_MODE;
1983       }
1984     }
1985 
1986     if (p_fcr->mode != L2CAP_FCR_BASIC_MODE) {
1987       /* MTU must be smaller than buffer size */
1988       if ((p_cfg->mtu_present) && (p_cfg->mtu > p_ccb->max_rx_mtu)) {
1989         L2CAP_TRACE_WARNING("L2CAP - MTU: %u  larger than buf size: %u",
1990                             p_cfg->mtu, p_ccb->max_rx_mtu);
1991         return (false);
1992       }
1993 
1994       /* application want to use the default MPS */
1995       if (p_fcr->mps == L2CAP_DEFAULT_ERM_MPS) {
1996         p_fcr->mps = L2CAP_MPS_OVER_BR_EDR;
1997       }
1998       /* MPS must be less than MTU */
1999       else if (p_fcr->mps > p_ccb->max_rx_mtu) {
2000         L2CAP_TRACE_WARNING("L2CAP - MPS  %u  invalid  MTU: %u", p_fcr->mps,
2001                             p_ccb->max_rx_mtu);
2002         return (false);
2003       }
2004 
2005       /* We always initially read into the HCI buffer pool, so make sure it fits
2006        */
2007       if (p_fcr->mps > (L2CAP_MTU_SIZE - L2CAP_MAX_HEADER_FCS))
2008         p_fcr->mps = L2CAP_MTU_SIZE - L2CAP_MAX_HEADER_FCS;
2009     } else {
2010       p_cfg->fcs_present = false; /* Illegal to use FCS option in basic mode */
2011       p_cfg->ext_flow_spec_present =
2012           false; /* Illegal to use extended flow spec in basic mode */
2013     }
2014 
2015     p_ccb->our_cfg.fcr = *p_fcr;
2016   } else /* Not sure how to send a reconfiguration(??) should fcr be included?
2017             */
2018   {
2019     p_ccb->our_cfg.fcr_present = false;
2020   }
2021 
2022   return (true);
2023 }
2024 
2025 /*******************************************************************************
2026  *
2027  * Function         l2c_fcr_adj_monitor_retran_timeout
2028  *
2029  * Description      Overrides monitor/retrans timer value based on controller
2030  *
2031  * Returns          None
2032  *
2033  ******************************************************************************/
l2c_fcr_adj_monitor_retran_timeout(tL2C_CCB * p_ccb)2034 void l2c_fcr_adj_monitor_retran_timeout(tL2C_CCB* p_ccb) {
2035   CHECK(p_ccb != NULL);
2036 
2037   /* adjust our monitor/retran timeout */
2038   if (p_ccb->out_cfg_fcr_present) {
2039     /*
2040     ** if we requestd ERTM or accepted ERTM
2041     ** We may accept ERTM even if we didn't request ERTM, in case of requesting
2042     *STREAM
2043     */
2044     if ((p_ccb->our_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE) ||
2045         (p_ccb->peer_cfg.fcr.mode == L2CAP_FCR_ERTM_MODE)) {
2046       /* upper layer setting is ignored */
2047       p_ccb->our_cfg.fcr.mon_tout = L2CAP_MIN_MONITOR_TOUT;
2048       p_ccb->our_cfg.fcr.rtrans_tout = L2CAP_MIN_RETRANS_TOUT;
2049     } else {
2050       p_ccb->our_cfg.fcr.mon_tout = 0;
2051       p_ccb->our_cfg.fcr.rtrans_tout = 0;
2052     }
2053 
2054     L2CAP_TRACE_DEBUG(
2055         "l2c_fcr_adj_monitor_retran_timeout: mon_tout:%d, rtrans_tout:%d",
2056         p_ccb->our_cfg.fcr.mon_tout, p_ccb->our_cfg.fcr.rtrans_tout);
2057   }
2058 }
2059 /*******************************************************************************
2060  *
2061  * Function         l2c_fcr_adj_our_rsp_options
2062  *
2063  * Description      Overrides any neccesary FCR options passed in from
2064  *                  L2CA_ConfigRsp based on our FCR options.
2065  *                  Only makes adjustments if channel is in ERTM mode.
2066  *
2067  * Returns          None
2068  *
2069  ******************************************************************************/
l2c_fcr_adj_our_rsp_options(tL2C_CCB * p_ccb,tL2CAP_CFG_INFO * p_cfg)2070 void l2c_fcr_adj_our_rsp_options(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
2071   CHECK(p_ccb != NULL);
2072   CHECK(p_cfg != NULL);
2073 
2074   /* adjust our monitor/retran timeout */
2075   l2c_fcr_adj_monitor_retran_timeout(p_ccb);
2076 
2077   p_cfg->fcr_present = p_ccb->out_cfg_fcr_present;
2078 
2079   if (p_cfg->fcr_present) {
2080     /* Temporary - until a better algorithm is implemented */
2081     /* If peer's tx_wnd_sz requires too many buffers for us to support, then
2082      * adjust it. For now, respond with our own tx_wnd_sz. */
2083     /* Note: peer is not guaranteed to obey our adjustment */
2084     if (p_ccb->peer_cfg.fcr.tx_win_sz > p_ccb->our_cfg.fcr.tx_win_sz) {
2085       L2CAP_TRACE_DEBUG("%s: adjusting requested tx_win_sz from %i to %i",
2086                         __func__, p_ccb->peer_cfg.fcr.tx_win_sz,
2087                         p_ccb->our_cfg.fcr.tx_win_sz);
2088       p_ccb->peer_cfg.fcr.tx_win_sz = p_ccb->our_cfg.fcr.tx_win_sz;
2089     }
2090 
2091     p_cfg->fcr.mode = p_ccb->peer_cfg.fcr.mode;
2092     p_cfg->fcr.tx_win_sz = p_ccb->peer_cfg.fcr.tx_win_sz;
2093     p_cfg->fcr.max_transmit = p_ccb->peer_cfg.fcr.max_transmit;
2094     p_cfg->fcr.mps = p_ccb->peer_cfg.fcr.mps;
2095     p_cfg->fcr.rtrans_tout = p_ccb->our_cfg.fcr.rtrans_tout;
2096     p_cfg->fcr.mon_tout = p_ccb->our_cfg.fcr.mon_tout;
2097   }
2098 }
2099 
2100 /*******************************************************************************
2101  *
2102  * Function         l2c_fcr_renegotiate_chan
2103  *
2104  * Description      Called upon unsuccessful peer response to config request.
2105  *                  If the error is because of the channel mode, it will try
2106  *                  to resend using another supported optional channel.
2107  *
2108  * Returns          true if resent configuration, False if channel matches or
2109  *                  cannot match.
2110  *
2111  ******************************************************************************/
l2c_fcr_renegotiate_chan(tL2C_CCB * p_ccb,tL2CAP_CFG_INFO * p_cfg)2112 bool l2c_fcr_renegotiate_chan(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
2113   CHECK(p_ccb != NULL);
2114   CHECK(p_cfg != NULL);
2115 
2116   uint8_t peer_mode = p_ccb->our_cfg.fcr.mode;
2117   bool can_renegotiate;
2118 
2119   /* Skip if this is a reconfiguration from OPEN STATE or if FCR is not returned
2120    */
2121   if (!p_cfg->fcr_present || (p_ccb->config_done & RECONFIG_FLAG))
2122     return (false);
2123 
2124   /* Only retry if there are more channel options to try */
2125   if (p_cfg->result == L2CAP_CFG_UNACCEPTABLE_PARAMS) {
2126     peer_mode = (p_cfg->fcr_present) ? p_cfg->fcr.mode : L2CAP_FCR_BASIC_MODE;
2127 
2128     if (p_ccb->our_cfg.fcr.mode != peer_mode) {
2129       if ((--p_ccb->fcr_cfg_tries) == 0) {
2130         p_cfg->result = L2CAP_CFG_FAILED_NO_REASON;
2131         L2CAP_TRACE_WARNING("l2c_fcr_renegotiate_chan (Max retries exceeded)");
2132       }
2133 
2134       can_renegotiate = false;
2135 
2136       /* Try another supported mode if available based on our last attempted
2137        * channel */
2138       switch (p_ccb->our_cfg.fcr.mode) {
2139         /* Our Streaming mode request was unnacceptable; try ERTM or Basic */
2140         case L2CAP_FCR_STREAM_MODE:
2141           /* Peer wants ERTM and we support it */
2142           if ((peer_mode == L2CAP_FCR_ERTM_MODE) &&
2143               (p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_ERTM)) {
2144             L2CAP_TRACE_DEBUG("l2c_fcr_renegotiate_chan(Trying ERTM)");
2145             p_ccb->our_cfg.fcr.mode = L2CAP_FCR_ERTM_MODE;
2146             can_renegotiate = true;
2147           } else /* Falls through */
2148 
2149           case L2CAP_FCR_ERTM_MODE: {
2150             /* We can try basic for any other peer mode if we support it */
2151             if (p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_BASIC) {
2152               L2CAP_TRACE_DEBUG("l2c_fcr_renegotiate_chan(Trying Basic)");
2153               can_renegotiate = true;
2154               p_ccb->our_cfg.fcr.mode = L2CAP_FCR_BASIC_MODE;
2155             }
2156           } break;
2157 
2158           default:
2159             /* All other scenarios cannot be renegotiated */
2160             break;
2161       }
2162 
2163       if (can_renegotiate) {
2164         p_ccb->our_cfg.fcr_present = true;
2165 
2166         if (p_ccb->our_cfg.fcr.mode == L2CAP_FCR_BASIC_MODE) {
2167           p_ccb->our_cfg.fcs_present = false;
2168           p_ccb->our_cfg.ext_flow_spec_present = false;
2169 
2170           /* Basic Mode uses ACL Data Pool, make sure the MTU fits */
2171           if ((p_cfg->mtu_present) && (p_cfg->mtu > L2CAP_MTU_SIZE)) {
2172             L2CAP_TRACE_WARNING("L2CAP - adjust MTU: %u too large", p_cfg->mtu);
2173             p_cfg->mtu = L2CAP_MTU_SIZE;
2174           }
2175         }
2176 
2177         l2cu_process_our_cfg_req(p_ccb, &p_ccb->our_cfg);
2178         l2cu_send_peer_config_req(p_ccb, &p_ccb->our_cfg);
2179         alarm_set_on_mloop(p_ccb->l2c_ccb_timer, L2CAP_CHNL_CFG_TIMEOUT_MS,
2180                            l2c_ccb_timer_timeout, p_ccb);
2181         return (true);
2182       }
2183     }
2184   }
2185 
2186   /* Disconnect if the channels do not match */
2187   if (p_ccb->our_cfg.fcr.mode != peer_mode) {
2188     L2CAP_TRACE_WARNING("L2C CFG:  Channels incompatible (local %d, peer %d)",
2189                         p_ccb->our_cfg.fcr.mode, peer_mode);
2190     l2cu_disconnect_chnl(p_ccb);
2191   }
2192 
2193   return (false);
2194 }
2195 
2196 /*******************************************************************************
2197  *
2198  * Function         l2c_fcr_process_peer_cfg_req
2199  *
2200  * Description      This function is called to process the FCR options passed
2201  *                  in the peer's configuration request.
2202  *
2203  * Returns          uint8_t - L2CAP_PEER_CFG_OK, L2CAP_PEER_CFG_UNACCEPTABLE,
2204  *                          or L2CAP_PEER_CFG_DISCONNECT.
2205  *
2206  ******************************************************************************/
l2c_fcr_process_peer_cfg_req(tL2C_CCB * p_ccb,tL2CAP_CFG_INFO * p_cfg)2207 uint8_t l2c_fcr_process_peer_cfg_req(tL2C_CCB* p_ccb, tL2CAP_CFG_INFO* p_cfg) {
2208   CHECK(p_ccb != NULL);
2209   CHECK(p_cfg != NULL);
2210 
2211   uint16_t max_retrans_size;
2212   uint8_t fcr_ok = L2CAP_PEER_CFG_OK;
2213 
2214   p_ccb->p_lcb->w4_info_rsp =
2215       false; /* Handles T61x SonyEricsson Bug in Info Request */
2216 
2217   L2CAP_TRACE_EVENT(
2218       "l2c_fcr_process_peer_cfg_req() CFG fcr_present:%d fcr.mode:%d CCB FCR "
2219       "mode:%d preferred: %u allowed:%u",
2220       p_cfg->fcr_present, p_cfg->fcr.mode, p_ccb->our_cfg.fcr.mode,
2221       p_ccb->ertm_info.preferred_mode, p_ccb->ertm_info.allowed_modes);
2222 
2223   /* If Peer wants basic, we are done (accept it or disconnect) */
2224   if (p_cfg->fcr.mode == L2CAP_FCR_BASIC_MODE) {
2225     /* If we do not allow basic, disconnect */
2226     if (!(p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_BASIC))
2227       fcr_ok = L2CAP_PEER_CFG_DISCONNECT;
2228   }
2229 
2230   /* Need to negotiate if our modes are not the same */
2231   else if (p_cfg->fcr.mode != p_ccb->ertm_info.preferred_mode) {
2232     /* If peer wants a mode that we don't support then retry our mode (ex.
2233     *rtx/flc), OR
2234     ** If we want ERTM and they wanted streaming retry our mode.
2235     ** Note: If we have already determined they support our mode previously
2236     **       from their EXF mask.
2237     */
2238     if ((((1 << p_cfg->fcr.mode) & L2CAP_FCR_CHAN_OPT_ALL_MASK) == 0) ||
2239         (p_ccb->ertm_info.preferred_mode == L2CAP_FCR_ERTM_MODE)) {
2240       p_cfg->fcr.mode = p_ccb->our_cfg.fcr.mode;
2241       p_cfg->fcr.tx_win_sz = p_ccb->our_cfg.fcr.tx_win_sz;
2242       p_cfg->fcr.max_transmit = p_ccb->our_cfg.fcr.max_transmit;
2243       fcr_ok = L2CAP_PEER_CFG_UNACCEPTABLE;
2244     }
2245 
2246     /* If we wanted basic, then try to renegotiate it */
2247     else if (p_ccb->ertm_info.preferred_mode == L2CAP_FCR_BASIC_MODE) {
2248       p_cfg->fcr.mode = L2CAP_FCR_BASIC_MODE;
2249       p_cfg->fcr.max_transmit = p_cfg->fcr.tx_win_sz = 0;
2250       p_cfg->fcr.rtrans_tout = p_cfg->fcr.mon_tout = p_cfg->fcr.mps = 0;
2251       p_ccb->our_cfg.fcr.rtrans_tout = p_ccb->our_cfg.fcr.mon_tout =
2252           p_ccb->our_cfg.fcr.mps = 0;
2253       fcr_ok = L2CAP_PEER_CFG_UNACCEPTABLE;
2254     }
2255 
2256     /* Only other valid case is if they want ERTM and we wanted STM which should
2257        be
2258        accepted if we support it; otherwise the channel should be disconnected
2259        */
2260     else if ((p_cfg->fcr.mode != L2CAP_FCR_ERTM_MODE) ||
2261              !(p_ccb->ertm_info.allowed_modes & L2CAP_FCR_CHAN_OPT_ERTM)) {
2262       fcr_ok = L2CAP_PEER_CFG_DISCONNECT;
2263     }
2264   }
2265 
2266   /* Configuration for FCR channels so make any adjustments and fwd to upper
2267    * layer */
2268   if (fcr_ok == L2CAP_PEER_CFG_OK) {
2269     /* by default don't need to send params in the response */
2270     p_ccb->out_cfg_fcr_present = false;
2271 
2272     /* Make any needed adjustments for the response to the peer */
2273     if (p_cfg->fcr_present && p_cfg->fcr.mode != L2CAP_FCR_BASIC_MODE) {
2274       /* Peer desires to bypass FCS check, and streaming or ERTM mode */
2275       if (p_cfg->fcs_present) {
2276         p_ccb->peer_cfg.fcs = p_cfg->fcs;
2277         p_ccb->peer_cfg_bits |= L2CAP_CH_CFG_MASK_FCS;
2278         if (p_cfg->fcs == L2CAP_CFG_FCS_BYPASS)
2279           p_ccb->bypass_fcs |= L2CAP_CFG_FCS_PEER;
2280       }
2281 
2282       max_retrans_size = p_ccb->ertm_info.fcr_tx_buf_size - sizeof(BT_HDR) -
2283                          L2CAP_MIN_OFFSET - L2CAP_SDU_LEN_OFFSET -
2284                          L2CAP_FCS_LEN;
2285 
2286       /* Ensure the MPS is not bigger than the MTU */
2287       if ((p_cfg->fcr.mps == 0) || (p_cfg->fcr.mps > p_ccb->peer_cfg.mtu)) {
2288         p_cfg->fcr.mps = p_ccb->peer_cfg.mtu;
2289         p_ccb->out_cfg_fcr_present = true;
2290       }
2291 
2292       /* Ensure the MPS is not bigger than our retransmission buffer */
2293       if (p_cfg->fcr.mps > max_retrans_size) {
2294         L2CAP_TRACE_DEBUG("CFG: Overriding MPS to %d (orig %d)",
2295                           max_retrans_size, p_cfg->fcr.mps);
2296 
2297         p_cfg->fcr.mps = max_retrans_size;
2298         p_ccb->out_cfg_fcr_present = true;
2299       }
2300 
2301       if (p_cfg->fcr.mode == L2CAP_FCR_ERTM_MODE ||
2302           p_cfg->fcr.mode == L2CAP_FCR_STREAM_MODE) {
2303         /* Always respond with FCR ERTM parameters */
2304         p_ccb->out_cfg_fcr_present = true;
2305       }
2306     }
2307 
2308     /* Everything ok, so save the peer's adjusted fcr options */
2309     p_ccb->peer_cfg.fcr = p_cfg->fcr;
2310 
2311     if (p_cfg->fcr_present) p_ccb->peer_cfg_bits |= L2CAP_CH_CFG_MASK_FCR;
2312   } else if (fcr_ok == L2CAP_PEER_CFG_UNACCEPTABLE) {
2313     /* Allow peer only one retry for mode */
2314     if (p_ccb->peer_cfg_already_rejected)
2315       fcr_ok = L2CAP_PEER_CFG_DISCONNECT;
2316     else
2317       p_ccb->peer_cfg_already_rejected = true;
2318   }
2319 
2320   return (fcr_ok);
2321 }
2322 
2323 #if (L2CAP_ERTM_STATS == TRUE)
2324 /*******************************************************************************
2325  *
2326  * Function         l2c_fcr_collect_ack_delay
2327  *
2328  * Description      collect throughput, delay, queue size of waiting ack
2329  *
2330  * Parameters
2331  *                  tL2C_CCB
2332  *
2333  * Returns          void
2334  *
2335  ******************************************************************************/
l2c_fcr_collect_ack_delay(tL2C_CCB * p_ccb,uint8_t num_bufs_acked)2336 static void l2c_fcr_collect_ack_delay(tL2C_CCB* p_ccb, uint8_t num_bufs_acked) {
2337   uint32_t index;
2338   BT_HDR* p_buf;
2339   uint8_t* p;
2340   uint32_t timestamp, delay;
2341   uint8_t xx;
2342   uint8_t str[120];
2343 
2344   index = p_ccb->fcrb.ack_delay_avg_index;
2345 
2346   /* update sum, max and min of waiting for ack queue size */
2347   p_ccb->fcrb.ack_q_count_avg[index] +=
2348       fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q);
2349 
2350   if (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q) >
2351       p_ccb->fcrb.ack_q_count_max[index])
2352     p_ccb->fcrb.ack_q_count_max[index] =
2353         fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q);
2354 
2355   if (fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q) <
2356       p_ccb->fcrb.ack_q_count_min[index])
2357     p_ccb->fcrb.ack_q_count_min[index] =
2358         fixed_queue_length(p_ccb->fcrb.waiting_for_ack_q);
2359 
2360   /* update sum, max and min of round trip delay of acking */
2361   list_t* list = NULL;
2362   if (!fixed_queue_is_empty(p_ccb->fcrb.waiting_for_ack_q))
2363     list = fixed_queue_get_list(p_ccb->fcrb.waiting_for_ack_q);
2364   if (list != NULL) {
2365     for (const list_node_t *node = list_begin(list), xx = 0;
2366          (node != list_end(list)) && (xx < num_bufs_acked);
2367          node = list_next(node), xx++) {
2368       p_buf = list_node(node);
2369       /* adding up length of acked I-frames to get throughput */
2370       p_ccb->fcrb.throughput[index] += p_buf->len - 8;
2371 
2372       if (xx == num_bufs_acked - 1) {
2373         /* get timestamp from tx I-frame that receiver is acking */
2374         p = ((uint8_t*)(p_buf + 1)) + p_buf->offset + p_buf->len;
2375         if (p_ccb->bypass_fcs != L2CAP_BYPASS_FCS) {
2376           p += L2CAP_FCS_LEN;
2377         }
2378 
2379         STREAM_TO_UINT32(timestamp, p);
2380         delay = time_get_os_boottime_ms() - timestamp;
2381 
2382         p_ccb->fcrb.ack_delay_avg[index] += delay;
2383         if (delay > p_ccb->fcrb.ack_delay_max[index])
2384           p_ccb->fcrb.ack_delay_max[index] = delay;
2385         if (delay < p_ccb->fcrb.ack_delay_min[index])
2386           p_ccb->fcrb.ack_delay_min[index] = delay;
2387       }
2388     }
2389   }
2390 
2391   p_ccb->fcrb.ack_delay_avg_count++;
2392 
2393   /* calculate average and initialize next avg, min and max */
2394   if (p_ccb->fcrb.ack_delay_avg_count > L2CAP_ERTM_STATS_AVG_NUM_SAMPLES) {
2395     p_ccb->fcrb.ack_delay_avg_count = 0;
2396 
2397     p_ccb->fcrb.ack_q_count_avg[index] /= L2CAP_ERTM_STATS_AVG_NUM_SAMPLES;
2398     p_ccb->fcrb.ack_delay_avg[index] /= L2CAP_ERTM_STATS_AVG_NUM_SAMPLES;
2399 
2400     /* calculate throughput */
2401     timestamp = time_get_os_boottime_ms();
2402     if (timestamp - p_ccb->fcrb.throughput_start > 0)
2403       p_ccb->fcrb.throughput[index] /=
2404           (timestamp - p_ccb->fcrb.throughput_start);
2405 
2406     p_ccb->fcrb.throughput_start = timestamp;
2407 
2408     snprintf(
2409         str, sizeof(str),
2410         "[%02u] throughput: %5u, ack_delay avg:%3u, min:%3u, max:%3u, "
2411         "ack_q_count avg:%3u, min:%3u, max:%3u",
2412         index, p_ccb->fcrb.throughput[index], p_ccb->fcrb.ack_delay_avg[index],
2413         p_ccb->fcrb.ack_delay_min[index], p_ccb->fcrb.ack_delay_max[index],
2414         p_ccb->fcrb.ack_q_count_avg[index], p_ccb->fcrb.ack_q_count_min[index],
2415         p_ccb->fcrb.ack_q_count_max[index]);
2416 
2417     BT_TRACE(TRACE_CTRL_GENERAL | TRACE_LAYER_GKI | TRACE_ORG_GKI,
2418              TRACE_TYPE_GENERIC, "%s", str);
2419 
2420     index = (index + 1) % L2CAP_ERTM_STATS_NUM_AVG;
2421     p_ccb->fcrb.ack_delay_avg_index = index;
2422 
2423     p_ccb->fcrb.ack_q_count_max[index] = 0;
2424     p_ccb->fcrb.ack_q_count_min[index] = 0xFFFFFFFF;
2425     p_ccb->fcrb.ack_q_count_avg[index] = 0;
2426 
2427     p_ccb->fcrb.ack_delay_max[index] = 0;
2428     p_ccb->fcrb.ack_delay_min[index] = 0xFFFFFFFF;
2429     p_ccb->fcrb.ack_delay_avg[index] = 0;
2430 
2431     p_ccb->fcrb.throughput[index] = 0;
2432   }
2433 }
2434 #endif
2435